<?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'] ?? 0);
$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 ($callId > 0) {
    $stmt = $db->prepare('SELECT * FROM call_requests WHERE id = :id LIMIT 1');
    $stmt->execute([':id' => $callId]);
} else {
    $stmt = $db->prepare('SELECT * FROM call_requests WHERE room_token = :room LIMIT 1');
    $stmt->execute([':room' => $room]);
}

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

if ($csrId > 0 && function_exists('canCsrAccessCallRequest') && !canCsrAccessCallRequest($db, $csrId, (int)$call['id'])) {
    webrtc_json(['ok' => false, 'error' => 'Access denied'], 403);
}

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

$update = $db->prepare("UPDATE call_requests
    SET accepted_by = COALESCE(accepted_by, :csr_id),
        assigned_csr_id = COALESCE(assigned_csr_id, :csr_id2),
        status = CASE WHEN status IN ('manager_queue','assigned','accepted') THEN 'accepted' ELSE status END,
        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");
$update->execute([
    ':csr_id' => $csrId ?: null,
    ':csr_id2' => $csrId ?: null,
    ':room_token' => $roomToken,
    ':id' => (int)$call['id'],
]);

webrtc_json([
    'ok' => true,
    'call_id' => (int)$call['id'],
    'room_token' => $roomToken,
]);
