<?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);
    ensureOperationalTables($db);

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

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

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

    // Some older/newer dumps use preferred_date, not cx_preferred_date.
    // Build the SELECT safely so the details popup works on both schemas.
    $cxPreferredDateExpr = 'NULL';
    if (function_exists('columnExists') && columnExists($db, 'service_requests', 'cx_preferred_date')) {
        $cxPreferredDateExpr = 'sr.cx_preferred_date';
    } elseif (function_exists('columnExists') && columnExists($db, 'service_requests', 'preferred_date')) {
        $cxPreferredDateExpr = 'sr.preferred_date';
    }

    $stmt = $db->prepare("SELECT
            cr.*,
            COALESCE(sr.request_number, CONCAT('CALL-', DATE_FORMAT(cr.queued_at, '%Y%m%d'), '-', cr.id)) AS request_number,
            sr.full_name AS request_full_name,
            sr.phone_number AS request_phone,
            sr.secondary_phone AS request_secondary_phone,
            sr.customer_email AS request_customer_email,
            sr.service_address,
            sr.service_address_2,
            sr.zip_code,
            sr.state AS request_state,
            sr.region AS request_region,
            sr.issue_description,
            sr.special_request,
            sr.model_number,
            sr.serial_number,
            sr.product_model_version,
            sr.purchase_date,
            sr.warranty_type,
            {$cxPreferredDateExpr} AS cx_preferred_date,
            sr.call_received_date,
            b.name AS brand_name,
            a.name AS appliance_name,
            city.city_name,
            city.state AS city_state,
            city.region AS city_region,
            cust.email AS customer_account_email,
            cust.phone_number AS customer_account_phone,
            t.team_name,
            CONCAT(assigned.first_name, ' ', assigned.last_name) AS assigned_csr_name,
            CONCAT(accepted.first_name, ' ', accepted.last_name) AS accepted_by_name,
            (SELECT cl.notes FROM call_logs cl WHERE cl.call_request_id = cr.id AND cl.notes IS NOT NULL AND cl.notes <> '' ORDER BY cl.id DESC LIMIT 1) AS latest_log_notes
        FROM call_requests cr
        LEFT JOIN service_requests sr ON sr.id = cr.request_id
        LEFT JOIN brands b ON b.id = sr.brand_id
        LEFT JOIN appliance_types a ON a.id = sr.appliance_type_id
        LEFT JOIN cities city ON city.id = sr.city_id
        LEFT JOIN customers cust ON cust.id = cr.customer_id
        LEFT JOIN csr_teams t ON t.id = cr.team_id
        LEFT JOIN csr_users assigned ON assigned.id = cr.assigned_csr_id
        LEFT JOIN csr_users accepted ON accepted.id = cr.accepted_by
        WHERE cr.id = :id
        LIMIT 1");
    $stmt->execute([':id' => $callId]);
    $call = $stmt->fetch(PDO::FETCH_ASSOC);

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

    $notes = trim((string)($call['notes'] ?? ''));
    $logNotes = trim((string)($call['latest_log_notes'] ?? ''));
    if ($logNotes !== '' && $logNotes !== $notes) {
        $notes = $notes !== '' ? ($notes . "\n\n--- Additional saved note ---\n" . $logNotes) : $logNotes;
    }
    $call['combined_notes'] = $notes;

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