<?php
session_start();

if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit;
}

$title = 'Call Queue';

require_once '../config/database.php';
require_once '../includes/app_helpers.php';

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

$csrId = (int)$_SESSION['csr_id'];
$scope = getCsrRequestScope($db, $csrId);
$teamMembers = [];

if (!empty($scope['is_manager'])) {
    $ids = $scope['member_ids'] ?? [];

    if ($ids) {
        $params = [];
        $in = addInClauseParams($params, $ids, 'm');

        $stmt = $db->prepare("
            SELECT 
                id, 
                CONCAT(first_name, ' ', last_name) AS name 
            FROM csr_users 
            WHERE id IN ($in) 
              AND is_active = 1 
            ORDER BY first_name, last_name
        ");

        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v, PDO::PARAM_INT);
        }

        $stmt->execute();
        $teamMembers = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

ob_start();
?>

<style>
.call-shell {
    display: grid;
    gap: 16px;
}

.call-card {
    background: linear-gradient(135deg, #17295e, #102448);
    border: 1px solid rgba(56, 189, 248, .28);
    border-radius: 16px;
    color: #fff;
    box-shadow: 0 10px 24px rgba(0, 0, 0, .24);
    overflow: hidden;
}

.call-head {
    padding: 16px;
    background: linear-gradient(135deg, rgba(29, 155, 240, .18), rgba(23, 189, 212, .08));
    border-bottom: 1px solid rgba(56, 189, 248, .22);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 14px;
}

.call-head h2,
.call-card h4 {
    font-weight: 900;
    color: #fff !important;
}

.call-body {
    padding: 16px;
}

.call-table {
    width: 100%;
    color: #fff;
}

.call-table th {
    background: rgba(8, 20, 48, .62);
    padding: 12px;
    border-bottom: 1px solid rgba(96, 165, 250, .22);
    white-space: nowrap;
    color: #fff;
}

.call-table td {
    padding: 12px;
    border-bottom: 1px solid rgba(96, 165, 250, .20);
    color: #d7e7ff;
    vertical-align: middle;
}

.badge-soft {
    border-radius: 999px;
    background: rgba(56, 189, 248, .18);
    border: 1px solid rgba(56, 189, 248, .34);
    color: #dff7ff !important;
    padding: 6px 10px;
    font-weight: 900;
    text-decoration: none;
}

.badge-live {
    background: rgba(34, 197, 94, .18);
    border-color: rgba(34, 197, 94, .34);
    color: #bbf7d0 !important;
}

.badge-done {
    background: rgba(148, 163, 184, .18);
    border-color: rgba(148, 163, 184, .34);
    color: #e2e8f0 !important;
}

.btn-main {
    background: linear-gradient(135deg, #1d9bf0, #17bdd4) !important;
    border: 0 !important;
    color: #fff !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-done {
    background: linear-gradient(135deg, #16a34a, #22c55e) !important;
    border: 0 !important;
    color: #fff !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-miss {
    background: linear-gradient(135deg, #ef4444, #f87171) !important;
    border: 0 !important;
    color: #fff !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-rec {
    background: linear-gradient(135deg, #7c3aed, #a855f7) !important;
    border: 0 !important;
    color: #fff !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-delete-record {
    background: rgba(244, 63, 94, 0.16) !important;
    border: 1px solid rgba(244, 63, 94, 0.45) !important;
    color: #fecaca !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-delete-record:hover {
    background: rgba(244, 63, 94, 0.30) !important;
    color: #ffffff !important;
}

.form-select {
    background: rgba(8, 20, 48, .72) !important;
    border: 1px solid rgba(96, 165, 250, .34) !important;
    color: #fff !important;
    border-radius: 10px !important;
}

.form-select option {
    background: #102448;
    color: #fff;
}

.empty-call {
    text-align: center;
    color: #aebbd4;
    padding: 40px;
}

.call-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    align-items: center;
}

.call-toast-wrap {
    position: fixed;
    top: 82px;
    right: 18px;
    z-index: 3000;
    display: grid;
    gap: 10px;
    width: min(390px, calc(100vw - 28px));
}

.call-toast {
    background: linear-gradient(135deg, #17295e, #102448);
    border: 1px solid rgba(56, 189, 248, .42);
    border-radius: 16px;
    padding: 14px;
    color: #fff;
    box-shadow: 0 18px 55px rgba(0, 0, 0, .42);
    animation: callToastIn .25s ease;
}

.call-toast strong {
    color: #fff;
}

.call-toast small {
    color: #aebbd4;
}

.call-toast .toast-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 10px;
}

@keyframes callToastIn {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }

    to {
        opacity: 1;
        transform: none;
    }
}

.call-modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(2, 6, 23, .72);
    z-index: 4000;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 18px;
}

.call-modal {
    width: min(560px, 100%);
    background: linear-gradient(135deg, #17295e, #102448);
    border: 1px solid rgba(56, 189, 248, .42);
    border-radius: 18px;
    color: #fff;
    box-shadow: 0 24px 80px rgba(0, 0, 0, .55);
    overflow: hidden;
}

.call-modal-header {
    padding: 16px;
    background: rgba(56, 189, 248, .12);
    border-bottom: 1px solid rgba(96, 165, 250, .25);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.call-modal-body {
    padding: 18px;
}

.call-modal-footer {
    padding: 14px 18px;
    border-top: 1px solid rgba(96, 165, 250, .22);
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    flex-wrap: wrap;
}

.recording-dot {
    display: inline-flex;
    width: 10px;
    height: 10px;
    border-radius: 999px;
    background: #ef4444;
    box-shadow: 0 0 0 rgba(239, 68, 68, .7);
    animation: recordPulse 1.4s infinite;
}

@keyframes recordPulse {
    0% {
        box-shadow: 0 0 0 0 rgba(239, 68, 68, .7);
    }

    70% {
        box-shadow: 0 0 0 10px rgba(239, 68, 68, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
    }
}

audio {
    max-width: 260px;
    width: 100%;
}

.history-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.record-note {
    background: rgba(250, 204, 21, .12);
    border: 1px solid rgba(250, 204, 21, .30);
    color: #fde68a;
    border-radius: 12px;
    padding: 10px 12px;
    font-weight: 700;
    margin-top: 10px;
}

/* Custom delete confirmation modal */
.delete-confirm-overlay {
    position: fixed;
    inset: 0;
    background: rgba(2, 6, 23, 0.74);
    z-index: 4500;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 18px;
}

.delete-confirm-modal {
    width: min(460px, 100%);
    background: linear-gradient(135deg, #17295e, #102448);
    border: 1px solid rgba(244, 63, 94, 0.42);
    border-radius: 18px;
    color: #ffffff;
    box-shadow: 0 24px 80px rgba(0, 0, 0, 0.55);
    overflow: hidden;
    animation: callToastIn 0.22s ease;
}

.delete-confirm-header {
    padding: 16px;
    background: rgba(244, 63, 94, 0.13);
    border-bottom: 1px solid rgba(244, 63, 94, 0.28);
    display: flex;
    align-items: center;
    gap: 12px;
}

.delete-confirm-icon {
    width: 42px;
    height: 42px;
    border-radius: 14px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: rgba(244, 63, 94, 0.22);
    color: #fecaca;
    border: 1px solid rgba(244, 63, 94, 0.34);
    flex-shrink: 0;
}

.delete-confirm-header h4 {
    margin: 0;
    color: #ffffff !important;
    font-weight: 900;
}

.delete-confirm-header small {
    color: #fecaca;
    font-weight: 700;
}

.delete-confirm-body {
    padding: 18px;
    color: #d7e7ff;
}

.delete-confirm-body strong {
    color: #ffffff;
}

.delete-confirm-warning {
    background: rgba(250, 204, 21, 0.12);
    border: 1px solid rgba(250, 204, 21, 0.30);
    color: #fde68a;
    border-radius: 12px;
    padding: 10px 12px;
    font-weight: 700;
    margin-top: 12px;
}

.delete-confirm-footer {
    padding: 14px 18px;
    border-top: 1px solid rgba(96, 165, 250, 0.22);
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    flex-wrap: wrap;
}

.btn-cancel-delete {
    background: rgba(148, 163, 184, 0.16) !important;
    border: 1px solid rgba(148, 163, 184, 0.34) !important;
    color: #e2e8f0 !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.btn-confirm-delete {
    background: linear-gradient(135deg, #dc2626, #f43f5e) !important;
    border: 0 !important;
    color: #ffffff !important;
    border-radius: 10px !important;
    font-weight: 900 !important;
}

.call-detail-link {
    border: 0 !important;
    background: transparent !important;
    background-color: transparent !important;
    color: #dff7ff !important;
    font-weight: 900;
    padding: 0 !important;
    margin: 0 !important;
    text-decoration: underline;
    text-underline-offset: 3px;
    cursor: pointer;
    box-shadow: none !important;
    outline: none !important;
    border-radius: 0 !important;
    appearance: none;
    -webkit-appearance: none;
    display: inline;
    line-height: inherit;
    user-select: none;
    -webkit-user-select: none;
}

.call-detail-link:hover,
.call-detail-link:focus,
.call-detail-link:active {
    color: #ffffff !important;
    background: transparent !important;
    background-color: transparent !important;
    box-shadow: none !important;
    outline: none !important;
}

.call-detail-link::selection {
    background: transparent;
}

.call-detail-overlay {
    position: fixed;
    inset: 0;
    background: rgba(2, 6, 23, .74);
    z-index: 4500;
    display: none;
    align-items: center;
    justify-content: center;
    padding: 18px;
}

.call-detail-modal {
    width: min(920px, 100%);
    max-height: 88vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    background: linear-gradient(135deg, #17295e, #102448);
    border: 1px solid rgba(56, 189, 248, .42);
    border-radius: 18px;
    box-shadow: 0 25px 80px rgba(0, 0, 0, .52);
}

.call-detail-header,
.call-detail-footer {
    padding: 14px 16px;
    border-bottom: 1px solid rgba(96, 165, 250, .22);
    display: flex;
    justify-content: space-between;
    gap: 12px;
    align-items: center;
}

.call-detail-footer {
    border-top: 1px solid rgba(96, 165, 250, .22);
    border-bottom: 0;
    justify-content: flex-end;
}

.call-detail-body {
    padding: 16px;
    overflow-y: auto;
}

.call-detail-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px;
}

.call-detail-section {
    background: rgba(8, 20, 48, .46);
    border: 1px solid rgba(96, 165, 250, .20);
    border-radius: 14px;
    padding: 14px;
}

.call-detail-section.full {
    grid-column: 1 / -1;
}

.call-detail-section h5 {
    color: #fff;
    font-weight: 900;
    font-size: .98rem;
    margin: 0 0 10px;
}

.call-detail-row {
    display: grid;
    grid-template-columns: 150px 1fr;
    gap: 8px;
    padding: 6px 0;
    border-bottom: 1px solid rgba(96, 165, 250, .12);
}

.call-detail-row:last-child { border-bottom: 0; }
.call-detail-row span:first-child { color: #aebbd4; font-weight: 800; }
.call-detail-row span:last-child { color: #f8fafc; font-weight: 700; word-break: break-word; }
.call-detail-notes { white-space: pre-wrap; color: #f8fafc; line-height: 1.55; }

@media(max-width: 720px) {
    .call-detail-grid { grid-template-columns: 1fr; }
    .call-detail-row { grid-template-columns: 1fr; }
}

@media(max-width: 900px) {
    .call-table {
        min-width: 1080px;
    }

    .call-body {
        overflow-x: auto;
    }

    .call-head {
        display: block;
    }

    .call-head button {
        margin-top: 12px;
    }
}
</style>

<div class="call-toast-wrap" id="callToastWrap"></div>

<div class="call-modal-overlay" id="activeCallOverlay">
    <div class="call-modal">
        <div class="call-modal-header">
            <div>
                <h4 class="mb-0">
                    <i class="fas fa-headset me-2"></i>
                    Active Call Session
                </h4>

                <small class="text-muted">
                    Use this panel while handling the customer call.
                </small>
            </div>

            <button class="btn btn-sm btn-secondary" onclick="closeActiveCallModal()">
                <i class="fas fa-times"></i>
            </button>
        </div>

        <div class="call-modal-body">
            <div id="activeCallInfo"></div>

            <div class="record-note">
                <i class="fas fa-circle-info me-1"></i>
                Browser recording captures this device microphone. For real two-way call recording, a VoIP provider integration is needed later.
            </div>

            <div class="mt-3 d-flex align-items-center gap-2 flex-wrap">
                <button class="btn btn-rec" id="recordBtn" onclick="toggleRecording()">
                    <i class="fas fa-microphone me-1"></i>
                    Start Recording
                </button>

                <span id="recordingStatus" class="text-muted">
                    Recording idle
                </span>
            </div>
        </div>

        <div class="call-modal-footer">
            <button class="btn btn-done" onclick="endActiveCall('completed')">
                <i class="fas fa-check me-1"></i>
                End as Completed
            </button>

            <button class="btn btn-miss" onclick="endActiveCall('missed')">
                <i class="fas fa-phone-slash me-1"></i>
                Mark Missed
            </button>
        </div>
    </div>
</div>

<div class="delete-confirm-overlay" id="deleteConfirmOverlay">
    <div class="delete-confirm-modal">
        <div class="delete-confirm-header">
            <div class="delete-confirm-icon">
                <i class="fas fa-trash"></i>
            </div>

            <div>
                <h4>Delete Call Record?</h4>
                <small>This action cannot be undone.</small>
            </div>
        </div>

        <div class="delete-confirm-body">
            <p class="mb-1">
                Are you sure you want to delete this call history record?
            </p>

            <p class="mb-0">
                If this record has a saved audio recording, the recording file will also be removed.
            </p>

            <div class="delete-confirm-warning">
                <i class="fas fa-triangle-exclamation me-1"></i>
                Only delete old, duplicate, or test call records.
            </div>
        </div>

        <div class="delete-confirm-footer">
            <button type="button" class="btn btn-cancel-delete" onclick="closeDeleteCallModal()">
                Cancel
            </button>

            <button type="button" class="btn btn-confirm-delete" onclick="confirmDeleteCallRecord()">
                <i class="fas fa-trash me-1"></i>
                Delete Record
            </button>
        </div>
    </div>
</div>

<div class="call-detail-overlay" id="callDetailOverlay">
    <div class="call-detail-modal">
        <div class="call-detail-header">
            <div>
                <h4 class="mb-0"><i class="fas fa-circle-info me-2"></i>Call / Request Details</h4>
                <small class="text-muted">Caller info, linked request details, and saved call room notes.</small>
            </div>
            <button class="btn btn-sm btn-secondary" onclick="closeCallDetails()"><i class="fas fa-times"></i></button>
        </div>
        <div class="call-detail-body" id="callDetailBody">
            <div class="empty-call"><i class="fas fa-spinner fa-spin"></i> Loading details…</div>
        </div>
        <div class="call-detail-footer">
            <button class="btn btn-secondary" onclick="closeCallDetails()">Close</button>
        </div>
    </div>
</div>

<div class="call-shell">
    <div class="call-card">
        <div class="call-head">
            <div>
                <h2 class="mb-1">
                    <i class="fas fa-phone-volume me-2"></i>
                    Incoming Call Queue
                </h2>

                <p class="text-muted mb-0">
                    Customer call requests are routed to Team Leaders first, then assigned or accepted by CSR.
                </p>
            </div>

            <button class="btn btn-main" onclick="loadCalls(true)">
                <i class="fas fa-sync-alt me-1"></i>
                Refresh
            </button>
        </div>

        <div class="call-body">
            <table class="call-table">
                <thead>
                    <tr>
                        <th>Queued</th>
                        <th>Request #</th>
                        <th>Customer</th>
                        <th>Phone</th>
                        <th>Team</th>
                        <th>Status</th>
                        <th>Assigned CSR</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody id="callQueueBody">
                    <tr>
                        <td colspan="8" class="empty-call">
                            Loading call queue...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <div class="call-card">
        <div class="call-body">
            <div class="history-title">
                <h4 class="mb-0">
                    <i class="fas fa-clock-rotate-left me-2"></i>
                    Call History & Recordings
                </h4>

                <span class="badge-soft" id="historyCount">
                    0 records
                </span>
            </div>

            <table class="call-table">
                <thead>
                    <tr>
                        <th>Ended</th>
                        <th>Request #</th>
                        <th>Customer</th>
                        <th>Type</th>
                        <th>Handled By</th>
                        <th>Status</th>
                        <th>Duration</th>
                        <th>Replay</th>
                        <th>Action</th>
                    </tr>
                </thead>

                <tbody id="callHistoryBody">
                    <tr>
                        <td colspan="9" class="empty-call">
                            Loading call history...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script>
const IS_MANAGER = <?= !empty($scope['is_manager']) ? 'true' : 'false' ?>;
const CURRENT_CSR_ID = <?= (int)$csrId ?>;
const TEAM_MEMBERS = <?= json_encode($teamMembers) ?>;

let knownActiveCallIds = new Set();
let firstLoadDone = false;
let activeCall = null;
let latestActiveCalls = [];
let mediaRecorder = null;
let recordedChunks = [];
let recordingStream = null;
let isRecording = false;
let pendingDeleteCallId = null;

function esc(t) {
    return String(t ?? '').replace(/[&<>"']/g, function(m) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[m];
    });
}

function fmt(d) {
    if (!d) return 'N/A';

    let x = new Date(String(d).replace(' ', 'T'));

    return isNaN(x) ? esc(d) : x.toLocaleString();
}

function callRoomUrl(roomToken) { return '../call_room.php?room=' + encodeURIComponent(roomToken || ''); }

function dur(sec) {
    sec = parseInt(sec || 0, 10);

    if (!sec) return 'N/A';

    const m = Math.floor(sec / 60);
    const s = sec % 60;

    return `${m}:${String(s).padStart(2, '0')}`;
}

function badgeForStatus(status) {
    const label = String(status || '').replace('_', ' ');
    const cls = status === 'accepted'
        ? 'badge-live'
        : (['completed', 'missed', 'cancelled'].includes(status) ? 'badge-done' : '');

    return `<span class="badge-soft ${cls}">${esc(label)}</span>`;
}

function directionBadge(direction) {
    const normalized = String(direction || 'inbound').toLowerCase();
    const icon = normalized === 'outbound' ? 'fa-arrow-up-right-from-square' : 'fa-arrow-down-left';
    const label = normalized === 'outbound' ? 'Outbound' : 'Inbound';
    return `<span class="badge-soft"><i class="fas ${icon} me-1"></i>${label}</span>`;
}

function yesNo(value) {
    return value && value !== '0000-00-00' ? esc(value) : '—';
}

function showCallToast(title, message, actionsHtml = '') {
    const id = 'toast_' + Date.now();

    $('#callToastWrap').append(`
        <div class="call-toast" id="${id}">
            <strong>${esc(title)}</strong><br>
            <small>${esc(message)}</small>

            <div class="toast-actions">
                ${actionsHtml}
                <button class="btn btn-sm btn-secondary" onclick="$('#${id}').remove()">
                    Dismiss
                </button>
            </div>
        </div>
    `);

    setTimeout(function() {
        $('#' + id).fadeOut(250, function() {
            $(this).remove();
        });
    }, 12000);
}

function loadCalls(manual = false) {
    $.getJSON('ajax/get_call_queue.php', function(r) {
        if (!r.success) {
            $('#callQueueBody').html(`
                <tr>
                    <td colspan="8" class="empty-call text-danger">
                        ${esc(r.message)}
                    </td>
                </tr>
            `);

            $('#callHistoryBody').html(`
                <tr>
                    <td colspan="8" class="empty-call text-danger">
                        ${esc(r.message)}
                    </td>
                </tr>
            `);

            return;
        }

        renderActiveCalls(r.calls || []);
        renderHistory(r.history || []);

        if (manual) {
            showCallToast('Call Queue', 'Call queue refreshed.');
        }

        firstLoadDone = true;
    }).fail(function() {
        $('#callQueueBody').html(`
            <tr>
                <td colspan="8" class="empty-call text-danger">
                    Unable to load call queue.
                </td>
            </tr>
        `);
    });
}

function renderActiveCalls(calls) {
    latestActiveCalls = calls || [];

    if (!calls.length) {
        $('#callQueueBody').html(`
            <tr>
                <td colspan="8" class="empty-call">
                    <i class="fas fa-phone-slash fa-2x mb-2"></i><br>
                    No active call requests.
                </td>
            </tr>
        `);

        knownActiveCallIds = new Set();
        return;
    }

    let html = '';
    const newIds = new Set();

    calls.forEach(function(c) {
        const id = Number(c.id);
        newIds.add(id);

        if (firstLoadDone && !knownActiveCallIds.has(id)) {
            if (IS_MANAGER && c.status === 'manager_queue') {
                showCallToast(
                    'New Call in Team Queue',
                    `${c.customer_name || c.full_name || 'Customer'} is requesting a call for ${c.request_number || 'a manual call'}. Please assign it to one of your regular CSRs.`,
                    `<button class="btn btn-sm btn-main" onclick="focusCallRow(${id})">Open Queue</button>`
                );
            } else if (!IS_MANAGER && c.status === 'assigned') {
                showCallToast(
                    'Incoming Assigned Call',
                    `${c.customer_name || c.full_name || 'Customer'} is waiting for you to answer ${c.request_number || 'this call'}.`,
                    `<button class="btn btn-sm btn-main" onclick="acceptCall(${id})">Answer Call</button>`
                );
            }
        }

        let assign = '';
        let actionButtons = '';

        if (IS_MANAGER) {
            if (c.status === 'manager_queue' || c.status === 'assigned') {
                const options = '<option value="">Assign to CSR</option>' + TEAM_MEMBERS.map(function(m) {
                    const selected = Number(c.assigned_csr_id || 0) === Number(m.id) ? 'selected' : '';
                    return `<option value="${m.id}" ${selected}>${esc(m.name)}</option>`;
                }).join('');

                assign = `
                    <select class="form-select form-select-sm" onchange="assignCall(${c.id}, this.value)">
                        ${options}
                    </select>
                `;
            }

            if (c.status === 'manager_queue') {
                actionButtons = `
                    <span class="badge-soft">
                        <i class="fas fa-share me-1"></i>
                        Assign to CSR first
                    </span>
                `;
            } else if (c.status === 'assigned') {
                actionButtons = `
                    <span class="badge-soft">
                        <i class="fas fa-user-check me-1"></i>
                        Waiting for CSR
                    </span>
                `;
            } else if (c.status === 'accepted') {
                actionButtons = `
                    <span class="badge-soft badge-live">
                        <i class="fas fa-headset me-1"></i>
                        CSR handling
                    </span>
                `;
            }
        } else {
            if (c.status === 'assigned') {
                actionButtons = `
                    <button class="btn btn-sm btn-main" onclick="acceptCall(${c.id})">
                        <i class="fas fa-headset me-1"></i>
                        Answer
                    </button>
                    ${c.room_token ? `<a class="btn btn-sm btn-main" href="${callRoomUrl(c.room_token)}"><i class="fas fa-wifi me-1"></i>Join Room</a>` : ''}

                    <button class="btn btn-sm btn-miss" onclick="finishCall(${c.id}, 'missed')">
                        Missed
                    </button>
                `;
            } else if (c.status === 'accepted') {
                actionButtons = `
                    <button class="btn btn-sm btn-done" onclick="openActiveCallById(${c.id})">
                        <i class="fas fa-headset me-1"></i>
                        Panel
                    </button>
                    ${c.room_token ? `<a class="btn btn-sm btn-main" href="${callRoomUrl(c.room_token)}"><i class="fas fa-wifi me-1"></i>Join Room</a>` : ''}

                    <button class="btn btn-sm btn-miss" onclick="finishCall(${c.id}, 'missed')">
                        Missed
                    </button>
                `;
            }
        }

        const phone = c.phone_number || c.request_phone || '';

        html += `
            <tr id="call-row-${id}">
                <td>${fmt(c.queued_at)}</td>

                <td>
                    <button type="button" class="call-detail-link" onclick="openCallDetails(${id})">${esc(c.request_number || 'Manual Call')}</button>
                </td>

                <td>${esc(c.customer_name || c.full_name)}</td>

                <td>
                    <a class="badge-soft" href="tel:${esc(phone)}">
                        <i class="fas fa-phone me-1"></i>
                        ${esc(phone)}
                    </a>
                </td>

                <td>${esc(c.team_name || 'Queue')}</td>
                <td>${badgeForStatus(c.status)}</td>
                <td>${esc(c.assigned_csr_name || c.accepted_by_name || 'Unassigned')}</td>

                <td>
                    <div class="call-actions">
                        ${assign}
                        ${actionButtons || '<span class="badge-soft">No action</span>'}
                    </div>
                </td>
            </tr>
        `;
    });

    knownActiveCallIds = newIds;
    $('#callQueueBody').html(html);
}

function focusCallRow(id) {
    const row = document.getElementById('call-row-' + id);
    if (row) {
        row.scrollIntoView({ behavior: 'smooth', block: 'center' });
        row.style.boxShadow = 'inset 0 0 0 2px rgba(56, 189, 248, .75)';
        setTimeout(function() {
            row.style.boxShadow = '';
        }, 2200);
    }
}

function renderHistory(history) {
    $('#historyCount').text((history || []).length + ' records');

    if (!history.length) {
        $('#callHistoryBody').html(`
            <tr>
                <td colspan="9" class="empty-call">
                    No completed or missed calls yet.
                </td>
            </tr>
        `);

        return;
    }

    let html = '';

    history.forEach(function(c) {
        const recording = c.recording_path
            ? `<audio controls src="../${esc(c.recording_path)}"></audio>`
            : '<span class="text-muted">No recording</span>';

        const deleteButton = `
            <button class="btn btn-sm btn-delete-record" onclick="deleteCallRecord(${Number(c.id)})">
                <i class="fas fa-trash me-1"></i>
                Delete
            </button>
        `;

        html += `
            <tr>
                <td>${fmt(c.completed_at || c.call_ended_at || c.updated_at)}</td>

                <td>
                    <button type="button" class="call-detail-link" onclick="openCallDetails(${Number(c.id)})">${esc(c.request_number || 'Manual Call')}</button>
                </td>

                <td>${esc(c.customer_name || c.full_name)}</td>
                <td>${directionBadge(c.call_direction)}</td>
                <td>${esc(c.accepted_by_name || c.assigned_csr_name || 'CSR')}</td>
                <td>${badgeForStatus(c.status)}</td>
                <td>${dur(c.call_duration_seconds)}</td>
                <td>${recording}</td>
                <td>${deleteButton}</td>
            </tr>
        `;
    });

    $('#callHistoryBody').html(html);
}


function detailRow(label, value) {
    const text = value === null || value === undefined || value === '' ? '—' : value;
    return `<div class="call-detail-row"><span>${esc(label)}</span><span>${esc(text)}</span></div>`;
}

function closeCallDetails() {
    $('#callDetailOverlay').hide();
}

function openCallDetails(callId) {
    if (!callId) return;

    $('#callDetailBody').html('<div class="empty-call"><i class="fas fa-spinner fa-spin"></i> Loading details…</div>');
    $('#callDetailOverlay').css('display', 'flex');

    $.ajax({
        url: 'ajax/get_call_details.php',
        method: 'GET',
        data: { call_id: callId, _: Date.now() },
        dataType: 'json',
        success: function(res) {
            if (!res.success || !res.call) {
                $('#callDetailBody').html(`<div class="empty-call text-danger">${esc(res.message || 'Unable to load call details.')}</div>`);
                return;
            }
            renderCallDetails(res.call);
        },
        error: function() {
            $('#callDetailBody').html('<div class="empty-call text-danger">Unable to load call details.</div>');
        }
    });
}

function renderCallDetails(c) {
    const phone = c.phone_number || c.request_phone || c.customer_account_phone || '';
    const email = c.customer_email || c.request_customer_email || c.customer_account_email || '';
    const state = c.request_state || c.city_state || '';
    const region = c.request_region || c.city_region || '';
    const notes = c.combined_notes || c.notes || 'No call notes saved yet.';
    const recording = c.recording_path ? `<audio controls src="../${esc(c.recording_path)}" style="width:100%;max-width:360px;"></audio>` : '<span class="text-muted">No recording saved</span>';

    $('#callDetailBody').html(`
        <div class="call-detail-grid">
            <div class="call-detail-section">
                <h5><i class="fas fa-phone me-1"></i> Call Information</h5>
                ${detailRow('Request #', c.request_number || 'Manual Call')}
                ${detailRow('Call Type', (String(c.call_direction || 'inbound').toLowerCase() === 'outbound') ? 'Outbound' : 'Inbound')}
                ${detailRow('Status', c.status || '—')}
                ${detailRow('Queued', fmt(c.queued_at))}
                ${detailRow('Started', fmt(c.call_started_at || c.accepted_at))}
                ${detailRow('Ended', fmt(c.call_ended_at || c.completed_at))}
                ${detailRow('Duration', dur(c.call_duration_seconds))}
                ${detailRow('Team', c.team_name || 'Queue')}
                ${detailRow('Assigned CSR', c.assigned_csr_name || 'Unassigned')}
                ${detailRow('Handled By', c.accepted_by_name || c.assigned_csr_name || 'CSR')}
            </div>

            <div class="call-detail-section">
                <h5><i class="fas fa-user me-1"></i> Caller Information</h5>
                ${detailRow('Customer', c.customer_name || c.request_full_name || 'Customer')}
                ${detailRow('Phone', phone)}
                ${detailRow('Email', email)}
                ${detailRow('Address', c.service_address || '')}
                ${detailRow('Address Note', c.service_address_2 || '')}
                ${detailRow('City', c.city_name || '')}
                ${detailRow('State', state)}
                ${detailRow('ZIP', c.zip_code || '')}
                ${detailRow('Region', region)}
            </div>

            <div class="call-detail-section">
                <h5><i class="fas fa-screwdriver-wrench me-1"></i> Product / Request</h5>
                ${detailRow('Appliance', c.appliance_name || '')}
                ${detailRow('Brand', c.brand_name || '')}
                ${detailRow('Model', c.model_number || '')}
                ${detailRow('Serial', c.serial_number || '')}
                ${detailRow('Model Version', c.product_model_version || '')}
                ${detailRow('Purchase Date', c.purchase_date || '')}
                ${detailRow('Warranty Type', c.warranty_type || '')}
                ${detailRow('CX Preferred Date', c.cx_preferred_date || '')}
            </div>

            <div class="call-detail-section">
                <h5><i class="fas fa-volume-high me-1"></i> Replay</h5>
                ${recording}
            </div>

            <div class="call-detail-section full">
                <h5><i class="fas fa-clipboard me-1"></i> Problem / Special Request</h5>
                ${detailRow('Problem', c.issue_description || '')}
                ${detailRow('Special Request', c.special_request || '')}
            </div>

            <div class="call-detail-section full">
                <h5><i class="fas fa-note-sticky me-1"></i> Call Room Notes</h5>
                <div class="call-detail-notes">${esc(notes)}</div>
            </div>
        </div>
    `);
}

function acceptCall(id) {
    $.post('ajax/accept_call_request.php', { call_id: id }, function(r) {
        if (!r.success) {
            showCallToast('Call Error', r.message || 'Unable to accept call.');
            return;
        }

        showCallToast('Call Accepted', r.message || 'Call accepted. Opening call room...');
        loadCalls();

        if (r.room_url) {
            window.location.href = r.room_url;
            return;
        }

        $.getJSON('ajax/get_call_queue.php', function(q) {
            const call = (q.calls || []).find(function(x) {
                return Number(x.id) === Number(id);
            });

            if (call && call.room_token) {
                window.location.href = callRoomUrl(call.room_token);
                return;
            }

            if (call) {
                openActiveCall(call);
            }
        });
    }, 'json').fail(function() {
        showCallToast('Call Error', 'Unable to accept call.');
    });
}

function finishCall(id, status) {
    $.post('ajax/update_call_request.php', { call_id: id, status: status }, function(r) {
        showCallToast(
            r.success ? 'Call Updated' : 'Call Error',
            r.message || 'Updated.'
        );

        loadCalls();
    }, 'json').fail(function() {
        showCallToast('Call Error', 'Unable to update call.');
    });
}

function assignCall(id, csr) {
    if (!csr) return;

    $.post('ajax/assign_call_request.php', { call_id: id, csr_id: csr }, function(r) {
        showCallToast(
            r.success ? 'Call Assigned' : 'Call Error',
            r.message || 'Assigned.'
        );

        loadCalls();
    }, 'json').fail(function() {
        showCallToast('Call Error', 'Unable to assign call.');
    });
}

function openActiveCallById(id) {
    const call = (latestActiveCalls || []).find(function(x) {
        return Number(x.id) === Number(id);
    });

    if (call) {
        openActiveCall(call);
    }
}

function openActiveCall(call) {
    if (typeof call === 'string') {
        try {
            call = JSON.parse(decodeURIComponent(call));
        } catch(e) {
            call = null;
        }
    }

    if (!call) return;

    activeCall = call;

    const phone = call.phone_number || call.request_phone || '';

    $('#activeCallInfo').html(`
        <div class="mb-2">
            <span class="badge-soft badge-live">
                <i class="fas fa-phone me-1"></i>
                Connected / Handling
            </span>
        </div>

        <h4>${esc(call.customer_name || call.full_name || 'Customer')}</h4>

        <p class="mb-1">
            <strong>Request:</strong>
            ${esc(call.request_number || 'Manual Call')}
        </p>

        <p class="mb-1">
            <strong>Phone:</strong>
            <a class="badge-soft" href="tel:${esc(phone)}">
                ${esc(phone)}
            </a>
        </p>

        <p class="mb-0">
            <strong>Team:</strong>
            ${esc(call.team_name || 'Queue')}
        </p>
    `);

    $('#activeCallOverlay').css('display', 'flex');
}

function closeActiveCallModal() {
    $('#activeCallOverlay').hide();
}

async function toggleRecording() {
    if (isRecording) {
        stopRecording();
        return;
    }

    if (!activeCall) {
        showCallToast('Recording', 'No active call selected.');
        return;
    }

    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia || !window.MediaRecorder) {
        showCallToast('Recording Unsupported', 'Your browser does not support microphone recording.');
        return;
    }

    try {
        recordingStream = await navigator.mediaDevices.getUserMedia({ audio: true });
        recordedChunks = [];
        mediaRecorder = new MediaRecorder(recordingStream);

        mediaRecorder.ondataavailable = function(e) {
            if (e.data && e.data.size > 0) {
                recordedChunks.push(e.data);
            }
        };

        mediaRecorder.onstop = uploadRecording;
        mediaRecorder.start();

        isRecording = true;

        $('#recordBtn').html('<i class="fas fa-stop me-1"></i>Stop Recording');
        $('#recordingStatus').html('<span class="recording-dot me-2"></span>Recording...');
    } catch(e) {
        showCallToast('Microphone Permission Needed', 'Allow microphone access to record the call notes/audio.');
    }
}

function stopRecording() {
    if (mediaRecorder && mediaRecorder.state !== 'inactive') {
        mediaRecorder.stop();
    }

    if (recordingStream) {
        recordingStream.getTracks().forEach(function(t) {
            t.stop();
        });
    }

    isRecording = false;

    $('#recordBtn').html('<i class="fas fa-microphone me-1"></i>Start Recording');
    $('#recordingStatus').text('Saving recording...');
}

function uploadRecording() {
    if (!activeCall || !recordedChunks.length) {
        $('#recordingStatus').text('No recording captured.');
        return;
    }

    const blob = new Blob(recordedChunks, {
        type: recordedChunks[0].type || 'audio/webm'
    });

    const fd = new FormData();

    fd.append('call_id', activeCall.id);
    fd.append('recording', blob, `call_${activeCall.id}.webm`);

    $.ajax({
        url: 'ajax/upload_call_recording.php',
        method: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(r) {
            $('#recordingStatus').text(
                r.success ? 'Recording saved.' : (r.message || 'Recording upload failed.')
            );

            showCallToast(
                r.success ? 'Recording Saved' : 'Recording Error',
                r.message || 'Recording upload finished.'
            );

            loadCalls();
        },
        error: function() {
            $('#recordingStatus').text('Recording upload failed.');
            showCallToast('Recording Error', 'Unable to upload recording.');
        }
    });
}

async function endActiveCall(status) {
    if (!activeCall) return;

    if (isRecording) {
        stopRecording();
        await new Promise(function(resolve) {
            setTimeout(resolve, 800);
        });
    }

    finishCall(activeCall.id, status);
    closeActiveCallModal();
    activeCall = null;
}

function deleteCallRecord(id) {
    if (!id) return;

    pendingDeleteCallId = id;
    $('#deleteConfirmOverlay').css('display', 'flex');
}

function closeDeleteCallModal() {
    pendingDeleteCallId = null;
    $('#deleteConfirmOverlay').hide();
}

function confirmDeleteCallRecord() {
    if (!pendingDeleteCallId) return;

    const callId = pendingDeleteCallId;

    $('.btn-confirm-delete')
        .prop('disabled', true)
        .html('<i class="fas fa-spinner fa-spin me-1"></i>Deleting...');

    $.ajax({
        url: 'ajax/delete_call_record.php',
        method: 'POST',
        data: { call_id: callId },
        dataType: 'json',
        success: function(response) {
            closeDeleteCallModal();

            if (response.success) {
                showCallToast(
                    'Call Record Deleted',
                    response.message || 'The call record was deleted successfully.'
                );

                loadCalls(true);
            } else {
                showCallToast(
                    'Delete Failed',
                    response.message || 'Unable to delete this call record.'
                );
            }
        },
        error: function() {
            closeDeleteCallModal();

            showCallToast(
                'Delete Failed',
                'Unable to delete this call record. Please try again.'
            );
        },
        complete: function() {
            $('.btn-confirm-delete')
                .prop('disabled', false)
                .html('<i class="fas fa-trash me-1"></i>Delete Record');
        }
    });
}

$(function() {
    loadCalls();
    setInterval(loadCalls, 5000);
});
</script>

<?php
$content = ob_get_clean();
include 'layout.php';
?>