<?php
require_once __DIR__ . '/../../config/webrtc_config.php';
webrtc_require_login();

if (!webrtc_is_csr()) {
    webrtc_json(['ok' => false, 'error' => 'CSR access only'], 403);
}

$db = webrtc_db();
ensureAddressAndCallQueueTables($db);
ensureWebRtcCallWorkflow($db);

$csrId = (int)$_SESSION['csr_id'];
$room = trim((string)($_POST['room_token'] ?? ''));
$callId = (int)($_POST['call_id'] ?? 0);

if ($room === '' && $callId <= 0) {
    webrtc_json(['ok' => false, 'error' => 'Missing room token or call id'], 400);
}

if ($room !== '') {
    $stmt = $db->prepare('SELECT id, room_token, accepted_by FROM call_requests WHERE room_token = :room LIMIT 1');
    $stmt->execute([':room' => $room]);
} else {
    $stmt = $db->prepare('SELECT id, room_token, accepted_by FROM call_requests WHERE id = :id LIMIT 1');
    $stmt->execute([':id' => $callId]);
}

$call = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$call) {
    webrtc_json(['ok' => false, 'error' => 'Call not found'], 404);
}

$roomToken = trim((string)($call['room_token'] ?? ''));
if ($roomToken === '') {
    $roomToken = webrtc_room_token();
}

$db->prepare("UPDATE call_requests
              SET accepted_by = :csr,
                  assigned_csr_id = COALESCE(assigned_csr_id, :csr2),
                  status = 'accepted',
                  accepted_at = COALESCE(accepted_at, NOW()),
                  call_started_at = COALESCE(call_started_at, NOW()),
                  room_token = :room_token,
                  call_mode = 'webrtc',
                  browser_call_status = 'connected'
              WHERE id = :id
                AND status IN ('manager_queue','assigned','accepted')
                AND (accepted_by IS NULL OR accepted_by = :csr3)")
   ->execute([
       ':csr' => $csrId,
       ':csr2' => $csrId,
       ':csr3' => $csrId,
       ':room_token' => $roomToken,
       ':id' => (int)$call['id'],
   ]);

webrtc_json([
    'ok' => true,
    'call_id' => (int)$call['id'],
    'room_token' => $roomToken,
    'room_url' => '../../call_room.php?room=' . urlencode($roomToken),
]);
