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

if (!isset($_SESSION['customer_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login first.']);
    exit;
}

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

    $customerId = (int)$_SESSION['customer_id'];
    $callId = (int)($_GET['call_id'] ?? 0);

    if ($callId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid call request.']);
        exit;
    }

    $stmt = $db->prepare("SELECT cr.id, cr.status, cr.queued_at, cr.assigned_at, cr.accepted_at, cr.completed_at,
                                 cr.customer_name, cr.phone_number, cr.notes,
                                 sr.request_number,
                                 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 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 cr.id = :id
                            AND cr.customer_id = :customer_id
                          LIMIT 1");
    $stmt->execute([
        ':id' => $callId,
        ':customer_id' => $customerId
    ]);
    $call = $stmt->fetch(PDO::FETCH_ASSOC);

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

    echo json_encode(['success' => true, 'call' => $call]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
