<?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'];
    $scope = getCsrRequestScope($db, $csrId);
    $role = (string)($scope['role'] ?? 'csr');
    $isManager = !empty($scope['is_manager']);
    $params = [];

    if ($isManager) {
        $teamIn = addInClauseParams($params, $scope['team_ids'] ?? [], 'cq_team');
        $params[':manager_id_1'] = $csrId;
        $params[':manager_id_2'] = $csrId;
        $params[':manager_id_3'] = $csrId;

        // CSR Manager sees all team queues. Team Leader sees own team queue.
        $where = "(
            cr.manager_id = :manager_id_1
            OR cr.team_id IN ($teamIn)
            OR cr.assigned_csr_id = :manager_id_2
            OR cr.accepted_by = :manager_id_3
        )";
    } else {
        $params[':csr_id_1'] = $csrId;
        $params[':csr_id_2'] = $csrId;

        // Regular CSRs should not see manager_queue calls.
        // They only see calls already assigned to them or calls they accepted.
        $where = "(
            cr.assigned_csr_id = :csr_id_1
            OR cr.accepted_by = :csr_id_2
        )";
    }

    $agentFilter = (int)($_GET['agent_filter'] ?? 0);
    if ($agentFilter > 0 && $isManager) {
        $params[':agent_filter'] = $agentFilter;
        $where .= " AND (cr.assigned_csr_id = :agent_filter OR cr.accepted_by = :agent_filter)";
    }

    $statusFilter = trim((string)($_GET['status_filter'] ?? ''));
    $statusMap = [
        'queued' => ['manager_queue'],
        'manager_queue' => ['manager_queue'],
        'assigned' => ['assigned'],
        'active' => ['accepted'],
        'accepted' => ['accepted'],
        'completed' => ['completed'],
        'missed' => ['missed'],
        'cancelled' => ['cancelled'],
    ];
    if ($statusFilter !== '' && isset($statusMap[$statusFilter])) {
        $keys = [];
        foreach ($statusMap[$statusFilter] as $i => $st) {
            $k = ':status_filter_' . $i;
            $params[$k] = $st;
            $keys[] = $k;
        }
        $where .= ' AND cr.status IN (' . implode(',', $keys) . ')';
    }

    $limit = (int)($_GET['limit'] ?? 100);
    $limit = max(1, min($limit, 250));

    $sql = "SELECT
                cr.*,
                sr.request_number,
                sr.full_name,
                sr.phone_number AS request_phone,
                sr.service_address,
                sr.zip_code,
                c.city_name,
                c.state,
                c.region AS city_region,
                t.team_name,
                CONCAT(cu.first_name, ' ', cu.last_name) AS assigned_csr_name,
                CONCAT(acc.first_name, ' ', acc.last_name) AS accepted_by_name
            FROM call_requests cr
            LEFT JOIN service_requests sr ON sr.id = cr.request_id
            LEFT JOIN cities c ON c.id = sr.city_id
            LEFT JOIN csr_teams t ON t.id = cr.team_id
            LEFT JOIN csr_users cu ON cu.id = cr.assigned_csr_id
            LEFT JOIN csr_users acc ON acc.id = cr.accepted_by
            WHERE $where
            ORDER BY
                CASE WHEN cr.status = 'manager_queue' THEN 0
                     WHEN cr.status = 'assigned' THEN 1
                     WHEN cr.status = 'accepted' THEN 2
                     ELSE 3 END ASC,
                cr.queued_at DESC
            LIMIT $limit";

    $stmt = $db->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v, is_int($v) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->execute();

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $active = [];
    $history = [];
    $counts = [
        'queued' => 0,
        'manager_queue' => 0,
        'assigned' => 0,
        'active' => 0,
        'accepted' => 0,
        'completed' => 0,
        'missed' => 0,
        'cancelled' => 0,
    ];

    foreach ($rows as $row) {
        $status = (string)($row['status'] ?? '');
        if ($status === 'manager_queue') {
            $counts['queued']++;
            $counts['manager_queue']++;
        } elseif ($status === 'accepted') {
            $counts['active']++;
            $counts['accepted']++;
        } elseif (isset($counts[$status])) {
            $counts[$status]++;
        }

        if (in_array($status, ['manager_queue', 'assigned', 'accepted'], true)) {
            $active[] = $row;
        } else {
            $history[] = $row;
        }
    }

    echo json_encode([
        'success' => true,
        'calls' => $active,
        'queue' => $active,
        'history' => $history,
        'counts' => $counts,
        'is_manager' => $isManager,
        'role' => $role,
    ]);
} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
