<?php
error_reporting(0);
ini_set('display_errors', 0);
header('Content-Type: application/json');
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

$conn_path = '../db_connect.php'; 
if(file_exists($conn_path)) {
    include $conn_path;
} else {
    echo json_encode(['action' => 'none', 'error' => 'db_not_found']);
    exit;
}

$action = $_GET['action'] ?? '';

// قراءة البيانات مرة واحدة فقط
$raw_input = file_get_contents('php://input');
$input = json_decode($raw_input, true);
$tid = $_GET['tid'] ?? $input['tid'] ?? '';

if (empty($tid)) {
    echo json_encode(['action' => 'none']);
    exit;
}

// 1. المدرس يرسل الأمر
if ($action == 'send_command') {
    $data = $raw_input; 
    
    $stmt = $conn->prepare("UPDATE webrtc_signals SET media_cmd=? WHERE tid=?");
    if($stmt){
        $stmt->bind_param("ss", $data, $tid);
        $stmt->execute();
    }
    echo json_encode(['status' => 'success']);
} 
// 2. الطالب يستقبل الأمر
elseif ($action == 'get_command' || $action == 'check_commands') {
    $res = $conn->query("SELECT media_cmd FROM webrtc_signals WHERE tid='$tid' LIMIT 1");
    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $cmd = $row['media_cmd'];
        if(!empty($cmd)){
            echo $cmd; 
            exit;
        }
    }
    echo json_encode(['action' => 'none']);
} else {
    echo json_encode(['action' => 'none']);
}
?>