<?php
error_reporting(0);
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
include_once '../db_connect.php'; 

$action = $_REQUEST['action'] ?? '';
$tid = $_REQUEST['tid'] ?? '';
$sid = $_REQUEST['sid'] ?? 'guest'; // رقم الطالب (ضروري لعدم اختلاط الطلاب)
$role = $_REQUEST['role'] ?? '';

if (empty($tid) || empty($action)) { echo json_encode(['error' => 'Missing parameters']); exit; }

// تحديث الجدول ليدعم (رقم المدرس + رقم الطالب) معاً
$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,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY unique_conn (tid, sid)
)";
$conn->query($table_sql);
$conn->query("INSERT IGNORE INTO webrtc_signals (tid, sid) VALUES ('$tid', '$sid')");

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'");
    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'");
    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'");
    $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'");
    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'");
    $row = $result->fetch_assoc();
    if ($row) {
        $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 == 'get_all_students') {
    $result = $conn->query("SELECT sid, answer FROM webrtc_signals WHERE tid='$tid' AND answer IS NOT NULL");
    $students = [];
    while($row = $result->fetch_assoc()) { $students[] = $row['sid']; }
    echo json_encode(['students' => $students]);
}
?>