<?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);

    $managerId = (int)$_SESSION['csr_id'];
    $scope = getCsrRequestScope($db, $managerId);
    $role = (string)($scope['role'] ?? 'csr');

    if (empty($scope['is_manager']) || !in_array($role, ['team_leader', 'csr_manager'], true)) {
        echo json_encode(['success' => false, 'message' => 'Only Team Leaders or CSR Managers can assign calls.']);
        exit;
    }

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

    if ($callId <= 0 || $csrId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Missing call or CSR selection.']);
        exit;
    }

    if (!canCsrAccessCallRequest($db, $managerId, $callId)) {
        echo json_encode(['success' => false, 'message' => 'Access denied for this call.']);
        exit;
    }

    $callStmt = $db->prepare("SELECT id, team_id, manager_id, status, accepted_by 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 (!in_array((string)$call['status'], ['manager_queue', 'assigned'], true)) {
        echo json_encode(['success' => false, 'message' => 'This call cannot be assigned because it is already accepted, completed, missed, or cancelled.']);
        exit;
    }

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

    // CSR Manager can assign to any active regular CSR.
    // Team Leader can assign only to active regular CSRs inside their team(s).
    if ($role === 'csr_manager') {
        $allowedStmt = $db->query("SELECT id FROM csr_users WHERE is_active = 1 AND COALESCE(role, 'csr') = 'csr'");
        $allowedIds = array_map('intval', $allowedStmt ? $allowedStmt->fetchAll(PDO::FETCH_COLUMN) : []);
    } else {
        $allowedIds = array_map('intval', $scope['member_ids'] ?? []);
        if ($allowedIds) {
            $params = [];
            $in = addInClauseParams($params, $allowedIds, 'allowed_csr');
            $allowedStmt = $db->prepare("SELECT id FROM csr_users WHERE id IN ($in) AND is_active = 1 AND COALESCE(role, 'csr') = 'csr'");
            foreach ($params as $k => $v) {
                $allowedStmt->bindValue($k, $v, PDO::PARAM_INT);
            }
            $allowedStmt->execute();
            $allowedIds = array_map('intval', $allowedStmt->fetchAll(PDO::FETCH_COLUMN));
        }
    }

    if (!in_array($csrId, $allowedIds, true)) {
        echo json_encode(['success' => false, 'message' => 'Selected user is not an active regular CSR you can assign calls to.']);
        exit;
    }

    $roomToken = null;
    try {
        $rt = $db->prepare("SELECT room_token FROM call_requests WHERE id = :id LIMIT 1");
        $rt->execute([':id' => $callId]);
        $roomToken = trim((string)$rt->fetchColumn());
    } catch (Throwable $e) {
        $roomToken = '';
    }

    if ($roomToken === '') {
        $roomToken = bin2hex(random_bytes(32));
    }

    $stmt = $db->prepare("UPDATE call_requests
                          SET assigned_csr_id = :csr,
                              accepted_by = NULL,
                              status = 'assigned',
                              assigned_at = NOW(),
                              accepted_at = NULL,
                              call_started_at = NULL,
                              call_ended_at = NULL,
                              call_duration_seconds = NULL,
                              room_token = :room_token,
                              call_mode = CASE WHEN COALESCE(call_mode, '') = '' THEN 'webrtc' ELSE call_mode END,
                              browser_call_status = 'ringing'
                          WHERE id = :id
                            AND status IN ('manager_queue','assigned')
                            AND accepted_by IS NULL");
    $stmt->execute([
        ':csr' => $csrId,
        ':id' => $callId,
        ':room_token' => $roomToken,
    ]);

    if ($stmt->rowCount() < 1) {
        echo json_encode(['success' => false, 'message' => 'Unable to assign this call. It may already be accepted, completed, or missed.']);
        exit;
    }

    $nameStmt = $db->prepare("SELECT CONCAT(first_name, ' ', last_name) FROM csr_users WHERE id = :id LIMIT 1");
    $nameStmt->execute([':id' => $csrId]);
    $csrName = trim((string)$nameStmt->fetchColumn()) ?: 'CSR';

    echo json_encode([
        'success' => true,
        'message' => 'Call assigned to ' . $csrName . '. They can now answer it from their CSR Call Queue.',
        'assigned_csr_id' => $csrId,
        'assigned_csr_name' => $csrName,
        'room_token' => $roomToken,
    ]);
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
