<?php
error_reporting(0);
if (session_status() == PHP_SESSION_NONE) { session_start(); }
header('Content-Type: application/json; charset=utf-8');
include_once '../db_connect.php';
mysqli_set_charset($conn, 'utf8mb4');

$action = $_REQUEST['action'] ?? '';
$sid = $conn->real_escape_string($_REQUEST['sid'] ?? '');
$tid = $conn->real_escape_string($_REQUEST['tid'] ?? '');

// 1. الدخول المباشر
if ($action === 'join') {
    $sname = "طالب";
    $st_q = $conn->query("SELECT student_name FROM students WHERE student_id = '$sid' LIMIT 1");
    if ($st_q && $st_q->num_rows > 0) { $sname = $conn->real_escape_string($st_q->fetch_assoc()['student_name']); }

    $conn->query("DELETE FROM live_waiting_room WHERE student_id = '$sid'");
    $insert = $conn->query("INSERT INTO live_waiting_room (teacher_id, student_id, student_name, status) VALUES ('$tid', '$sid', '$sname', 'accepted')");
    echo json_encode(['success' => (bool)$insert, 'name' => $sname]);
    exit;
}

// 2. المدرس يجلب قائمة الحضور
if ($action === 'get_pending') {
    $accepted = [];
    $q = $conn->query("SELECT * FROM live_waiting_room WHERE TRIM(teacher_id) = TRIM('$tid') AND status = 'accepted' ORDER BY id DESC");
    if($q) { while($row = $q->fetch_assoc()) { $accepted[] = $row; } }
    echo json_encode(['accepted' => $accepted]);
    exit;
}

// 3. المدرس يرسل أوامر
if ($action === 'update_state') {
    $field = $_POST['field'] ?? ''; 
    $val = intval($_POST['value']);
    $allowed = ['can_mic', 'can_cam', 'can_draw', 'is_kicked', 'hand_raised'];
    if (in_array($field, $allowed)) {
        $conn->query("UPDATE live_waiting_room SET $field = $val WHERE TRIM(student_id) = TRIM('$sid') AND TRIM(teacher_id) = TRIM('$tid')");
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'حقل غير مسموح']);
    }
    exit;
}

// 4. الطالب يستقبل الأوامر اللحظية
if ($action === 'get_student_state') {
    $q = $conn->query("SELECT * FROM live_waiting_room WHERE TRIM(student_id) = TRIM('$sid') AND TRIM(teacher_id) = TRIM('$tid') LIMIT 1");
    if($q && $q->num_rows > 0) { echo json_encode($q->fetch_assoc()); } 
    else { echo json_encode(['is_kicked' => 0]); }
    exit;
}

// 5. مسح رفع اليد
if ($action === 'lower_hand') {
    $conn->query("UPDATE live_waiting_room SET hand_raised = 0 WHERE TRIM(student_id) = TRIM('$sid') AND TRIM(teacher_id) = TRIM('$tid')");
    echo json_encode(['success' => true]);
    exit;
}

// 6. إنهاء البث
if ($action === 'end_broadcast') {
    $conn->query("DELETE FROM live_waiting_room WHERE TRIM(teacher_id) = TRIM('$tid')");
    echo json_encode(['success' => true]);
    exit;
}

// 7. استقبال صورة السبورة من (المدرس)
if ($action === 'sync_whiteboard') {
    $payload = $conn->real_escape_string($_POST['payload'] ?? '');
    if (!empty($payload)) {
        $conn->query("INSERT INTO live_whiteboard_sync (teacher_id, payload_json) VALUES ('$tid', '$payload') ON DUPLICATE KEY UPDATE payload_json = '$payload'");
    }
    echo json_encode(['success' => true]);
    exit;
}

// 8. استقبال رسمات وإحداثيات (الطالب)
if ($action === 'sync_student_draw') {
    $payload = $conn->real_escape_string($_POST['payload'] ?? '');
    if (!empty($payload)) {
        $conn->query("INSERT INTO live_whiteboard_sync (teacher_id, student_payload) VALUES ('$tid', '$payload') ON DUPLICATE KEY UPDATE student_payload = '$payload'");
    }
    echo json_encode(['success' => true]);
    exit;
}

// 9. الجلب المزدوج
if ($action === 'get_whiteboard_sync') {
    $q = $conn->query("SELECT payload_json, student_payload FROM live_whiteboard_sync WHERE teacher_id = '$tid' LIMIT 1");
    if ($q && $q->num_rows > 0) {
        $row = $q->fetch_assoc();
        echo json_encode(['teacher_payload' => json_decode($row['payload_json']), 'student_payload' => json_decode($row['student_payload'])]);
    } else {
        echo json_encode(['teacher_payload' => null, 'student_payload' => null]);
    }
    exit;
}

// مسح بيانات الطالب عند خروجه
if ($action === 'leave') {
    $conn->query("DELETE FROM live_waiting_room WHERE student_id = '$sid'");
    $conn->query("DELETE FROM webrtc_signals WHERE sid = '$sid' AND tid = '$tid'");
    echo json_encode(['success' => true]);
    exit;
}

// =========================================================
// 🚀 نظام الكاميرات (WebRTC) تم إدراجه هنا بدون أخطاء برمجية
// =========================================================
$webrtc_actions = [
    'save_offer', 'save_answer', 'save_ice', 'get_signal', 'clear_signal', 
    'get_all_students_signals', 'save_student_cam_offer', 'save_answer_for_student', 
    'save_teacher_ice_for_student', 'save_student_cam_ice', 'get_teacher_answer_for_student'
];

if (in_array($action, $webrtc_actions)) {
    // تجهيز رقم الطالب أو تعيينه كضيف
    $sid_webrtc = (isset($_REQUEST['sid']) && !empty($_REQUEST['sid'])) ? $conn->real_escape_string($_REQUEST['sid']) : 'guest';
    $role = $_REQUEST['role'] ?? '';

    // إنشاء الجدول إذا لم يكن موجوداً
    $table_sql = "CREATE TABLE IF NOT EXISTS webrtc_signals (
        id INT AUTO_INCREMENT PRIMARY KEY,
        tid VARCHAR(50), sid VARCHAR(50),
        offer TEXT, answer TEXT, teacher_ice TEXT, student_ice TEXT, media_cmd TEXT,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY unique_conn (tid, sid)
    )";
    $conn->query($table_sql);
    
    // 🚀 إجبار النظام على تسجيل المدرس في قاعدة البيانات فوراً
    if ($action !== 'clear_signal' && $action !== 'get_all_students_signals') {
        $conn->query("INSERT IGNORE INTO webrtc_signals (tid, sid) VALUES ('$tid', '$sid_webrtc')");
    }

    if ($action == 'save_offer') {
        $offer = $conn->real_escape_string($_POST['offer']);
        $conn->query("UPDATE webrtc_signals SET offer='$offer', answer=NULL, teacher_ice='[]', student_ice='[]' WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status' => 'success']);
    }
    elseif ($action == 'save_answer') {
        $answer = $conn->real_escape_string($_POST['answer']);
        $conn->query("UPDATE webrtc_signals SET answer='$answer' WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status' => 'success']);
    }
    elseif ($action == 'save_ice') {
        $candidate = $_POST['candidate'];
        $field = ($role == 'teacher') ? 'teacher_ice' : 'student_ice';
        $result = $conn->query("SELECT $field FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        if ($row = $result->fetch_assoc()) {
            $ice_arr = json_decode($row[$field], true);
            if (!is_array($ice_arr)) $ice_arr = [];
            $ice_arr[] = $candidate;
            $new_ice = $conn->real_escape_string(json_encode($ice_arr));
            $conn->query("UPDATE webrtc_signals SET $field='$new_ice' WHERE tid='$tid' AND sid='$sid_webrtc'");
        }
        echo json_encode(['status' => 'success']);
    }
    elseif ($action == 'get_signal') {
        $result = $conn->query("SELECT offer, answer, teacher_ice, student_ice FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        if ($row = $result->fetch_assoc()) {
            $candidates = ($role == 'teacher') ? $row['student_ice'] : $row['teacher_ice'];
            echo json_encode([
                'offer' => $row['offer'] ? json_decode($row['offer']) : null,
                'answer' => $row['answer'] ? json_decode($row['answer']) : null,
                'candidates' => json_decode($candidates, true) ?: []
            ]);
        } else {
            echo json_encode(['offer' => null, 'answer' => null, 'candidates' => []]);
        }
    }
    elseif ($action == 'clear_signal') {
        // عند إغلاق البث نمسح الإشارة ليختفي المدرس من لوحة الإدارة
        $conn->query("UPDATE webrtc_signals SET offer=NULL, answer=NULL, teacher_ice='[]', student_ice='[]' WHERE tid='$tid'");
        echo json_encode(['status' => 'success']);
    }
    elseif ($action == 'get_all_students_signals') {
        $res = $conn->query("SELECT sid, offer, student_ice FROM webrtc_signals WHERE tid='$tid' AND sid != 'guest' AND offer IS NOT NULL");
        $data = []; while($row = $res->fetch_assoc()) { $data[] = $row; }
        echo json_encode($data);
    }
    elseif ($action == 'save_student_cam_offer') {
        $offer = $conn->real_escape_string($_POST['offer'] ?? '');
        $conn->query("UPDATE webrtc_signals SET offer='$offer', answer=NULL, teacher_ice=NULL, student_ice=NULL WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status'=>'ok']);
    }
    elseif ($action == 'save_answer_for_student') {
        $answer = $conn->real_escape_string($_POST['answer'] ?? '');
        $conn->query("UPDATE webrtc_signals SET answer='$answer' WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status'=>'ok']);
    }
    elseif ($action == 'save_teacher_ice_for_student') {
        $candidate = $_POST['candidate'] ?? '';
        $res = $conn->query("SELECT teacher_ice FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        $row = $res->fetch_assoc();
        $ice_arr = $row['teacher_ice'] ? json_decode($row['teacher_ice'], true) : [];
        $ice_arr[] = json_decode($candidate, true);
        $new_ice = $conn->real_escape_string(json_encode($ice_arr));
        $conn->query("UPDATE webrtc_signals SET teacher_ice='$new_ice' WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status'=>'ok']);
    }
    elseif ($action == 'save_student_cam_ice') {
        $candidate = $_POST['candidate'] ?? '';
        $res = $conn->query("SELECT student_ice FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        $row = $res->fetch_assoc();
        $ice_arr = $row['student_ice'] ? json_decode($row['student_ice'], true) : [];
        $ice_arr[] = json_decode($candidate, true);
        $new_ice = $conn->real_escape_string(json_encode($ice_arr));
        $conn->query("UPDATE webrtc_signals SET student_ice='$new_ice' WHERE tid='$tid' AND sid='$sid_webrtc'");
        echo json_encode(['status'=>'ok']);
    }
    elseif ($action == 'get_teacher_answer_for_student') {
        $res = $conn->query("SELECT answer, teacher_ice FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        if($res->num_rows > 0) { echo json_encode($res->fetch_assoc()); } else { echo json_encode([]); }
    }
    exit;
}
?>
```eof

#### 2️⃣ استبدل كود ملف `api_live_streams.php`:
*(قمنا هنا بتحسين جلب البيانات ليراقب وجود الـ Offer ليكون البث حقيقياً وفورياً)*

```php:api_live_streams.php
<?php
// إخفاء الأخطاء العشوائية لضمان استقرار الـ JSON
ini_set('display_errors', 0);
error_reporting(E_ALL);
session_start();
header('Content-Type: application/json; charset=utf-8');

if (!file_exists('db_connect.php')) {
    echo json_encode(['status' => 'error', 'message' => 'ملف الاتصال غير موجود!']);
    exit;
}
require_once 'db_connect.php'; 

try {
    $data = [];
    
    // جلب اسم مدرسة المدير الذي يستخدم اللوحة الآن
    $admin_school = isset($_SESSION['school_name']) ? $conn->real_escape_string($_SESSION['school_name']) : '';

    // 🚀 الاستعلام الذكي الجديد (يعتمد على إشارة البث offer ليجلب البثوث النشطة فقط!)
    $sql = "
        SELECT w.tid as stream_id, w.updated_at, 
               t.display_name, t.subject, t.school_name, t.teacher_name as real_id
        FROM `webrtc_signals` w
        INNER JOIN `teachers` t ON (t.teacher_name = w.tid OR t.teacher_name = CONCAT('teacher_', w.tid))
        WHERE w.offer IS NOT NULL AND w.offer != '' AND w.sid = 'guest'
    ";
    
    // جدار العزل: منع عرض بثوث المدرسين المستقلين داخل لوحات المدارس
    if (!empty($admin_school) && $admin_school !== 'مستقل') {
        $sql .= " AND t.school_name = '$admin_school'";
    }

    $sql .= " GROUP BY w.tid ORDER BY w.updated_at DESC";
    
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            
            // رابط دخول الإدارة كـ مراقب
            $admin_join_url = "live_v2/student_live_v2.php?sid=ADMIN_MONITOR&tid=" . urlencode($row['stream_id']); 
            
            $data[] = [
                'teacher_name' => !empty($row['display_name']) ? $row['display_name'] : $row['stream_id'],
                'subject'      => 'المعرف: ' . $row['real_id'] . ' | ' . (!empty($row['subject']) ? $row['subject'] : 'مادة عامة'),
                'stage'        => 'بث مباشر',
                'platform'     => 'WebRTC',
                'join_url'     => $admin_join_url
            ];
        }
    }
    
    echo json_encode(['status' => 'success', 'data' => $data]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'حدث خطأ في قاعدة البيانات.']);
}

if(isset($conn)) $conn->close();
elseif ($action == 'get_teacher_answer_for_student') {
        $res = $conn->query("SELECT answer, teacher_ice FROM webrtc_signals WHERE tid='$tid' AND sid='$sid_webrtc'");
        if($res->num_rows > 0) { echo json_encode($res->fetch_assoc()); } else { echo json_encode([]); }
    }
    
    // 🚀 [الإضافة الجديدة]: التحكم الرسمي بحالة البث للإدارة عبر الأزرار
    elseif ($action == 'set_live_status') {
        $status = $_REQUEST['status'] ?? '';
        // التأكد من وجود سجل للمدرس أولاً
        $conn->query("INSERT IGNORE INTO webrtc_signals (tid, sid) VALUES ('$tid', 'guest')");
        
        if ($status === 'active') {
            // إذا ضغط الزر الأخضر: نسجل كلمة LIVE_STARTED
            $conn->query("UPDATE webrtc_signals SET media_cmd = '{\"action\":\"LIVE_STARTED\"}' WHERE tid='$tid' AND sid='guest'");
        } else {
            // إذا ضغط الزر الأحمر: نسجل كلمة CLEAR لإخفائه
            $conn->query("UPDATE webrtc_signals SET media_cmd = '{\"action\":\"CLEAR\"}' WHERE tid='$tid' AND sid='guest'");
        }
        echo json_encode(['status' => 'success']);
    }

    exit;

?>
