<?php
session_start();
require_once '../../config/database.php';
require_once '../../includes/app_helpers.php';
header('Content-Type: application/json');

if (!isset($_SESSION['csr_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

try {
    $db = (new Database())->getConnection();
    ensureAddressAndCallQueueTables($db);
ensureWebRtcCallWorkflow($db);
    ensureCsrTeamTables($db);

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

    if ($callId <= 0 || !canCsrAccessCallRequest($db, $csrId, $callId)) {
        echo json_encode(['success' => false, 'message' => 'Access denied.']);
        exit;
    }

    $scope = getCsrRequestScope($db, $csrId);
    $isManager = !empty($scope['is_manager']);

    $callStmt = $db->prepare("SELECT id, status, assigned_csr_id, accepted_by, room_token, call_mode FROM call_requests WHERE id = :id LIMIT 1");
    $callStmt->execute([':id' => $callId]);
    $call = $callStmt->fetch(PDO::FETCH_ASSOC);

    if (!$call) {
        echo json_encode(['success' => false, 'message' => 'Call request not found.']);
        exit;
    }

    if ($isManager) {
        echo json_encode([
            'success' => false,
            'message' => 'Team Leaders should assign the call to a regular CSR first. Regular CSR accounts are the ones who answer calls.'
        ]);
        exit;
    }

    if (!in_array($call['status'], ['manager_queue', 'assigned', 'accepted'], true)) {
        echo json_encode(['success' => false, 'message' => 'This call is no longer available.']);
        exit;
    }

    if (!empty($call['accepted_by']) && (int)$call['accepted_by'] !== $csrId) {
        echo json_encode(['success' => false, 'message' => 'This call was already accepted by another CSR.']);
        exit;
    }

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

    $stmt = $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 = CASE WHEN COALESCE(call_mode, '') = '' THEN 'webrtc' ELSE call_mode END,
                              browser_call_status = 'connected'
                          WHERE id = :id
                            AND status IN ('manager_queue','assigned','accepted')
                            AND (accepted_by IS NULL OR accepted_by = :csr4)");
    $stmt->execute([
        ':csr' => $csrId,
        ':csr2' => $csrId,
        ':id' => $callId,
        ':room_token' => $roomToken,
        ':csr4' => $csrId
    ]);

    if ($stmt->rowCount() < 1) {
        echo json_encode(['success' => false, 'message' => 'Unable to answer this call. It may have been reassigned or closed.']);
        exit;
    }

    echo json_encode([
        'success' => true,
        'message' => 'Call accepted. The active call panel is ready.',
        'call_id' => $callId,
        'room_token' => $roomToken,
        'room_url' => '../call_room.php?room=' . urlencode($roomToken)
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
