<?php
// csr/report.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../config/database.php';
require_once '../includes/csr_report_helpers.php';
if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit();
}
$databaseForReport = new Database();
$dbForReport = $databaseForReport->getConnection();
$reportAccess = getCsrReportAccessContext($dbForReport, (int)$_SESSION['csr_id']);
$reportRole = $reportAccess['role'];
$canDownloadReports = $reportAccess['can_download'];
$reportTeamOptions = $reportAccess['team_options'];
$reportSelectableCsrs = getCsrReportSelectableCsrs($dbForReport, $reportAccess['allowed_csr_ids']);
$title = 'Report';
ob_start();
?>

<style>
:root {
    --csr-bg-1: #080240;
    --csr-bg-2: #093349;
    --csr-card-1: #17295e;
    --csr-card-2: #102448;
    --csr-border: rgba(96, 165, 250, 0.24);
    --csr-cyan: #17bdd4;
    --csr-blue: #1d9bf0;
    --csr-text: #f8fafc;
    --csr-muted: #aebbd4;
    --csr-soft: #d7e7ff;
}

body {
    background: linear-gradient(135deg, var(--csr-bg-1) 0%, var(--csr-bg-2) 100%) !important;
    color: var(--csr-text) !important;
}

.container-fluid,
.main-content,
.content-wrapper {
    background: transparent !important;
}

.report-page-title {
    color: #ffffff !important;
    font-weight: 950;
    letter-spacing: 0.2px;
}

.report-page-subtitle {
    color: var(--csr-muted) !important;
    font-weight: 700;
}

.report-panel {
    background: linear-gradient(135deg, rgba(23, 41, 94, 0.96) 0%, rgba(16, 36, 72, 0.96) 100%) !important;
    border: 1px solid rgba(96, 165, 250, 0.26) !important;
    border-radius: 18px !important;
    box-shadow: 0 14px 32px rgba(0, 0, 0, 0.26) !important;
    overflow: hidden;
}

.report-nav {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 16px 18px;
    background: rgba(56, 189, 248, 0.10) !important;
    border-bottom: 1px solid rgba(96, 165, 250, 0.24) !important;
}

.report-nav-title {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    color: var(--csr-text) !important;
    font-weight: 950;
    letter-spacing: 0.3px;
    margin: 0;
}

.report-nav-pill {
    border-radius: 999px;
    background: linear-gradient(135deg, #1d9bf0 0%, #17bdd4 100%) !important;
    color: #ffffff !important;
    padding: 7px 14px;
    font-weight: 900;
    font-size: 12px;
    box-shadow: 0 8px 20px rgba(29, 155, 240, 0.20);
    white-space: nowrap;
}

.report-stat-card {
    height: 100%;
    min-height: 150px;
    padding: 20px;
    border-radius: 15px;
    background: rgba(8, 20, 48, 0.28) !important;
    border: 1px solid rgba(96, 165, 250, 0.22) !important;
    transition: all 0.25s ease;
}

.report-stat-card:hover {
    transform: translateY(-3px);
    background: rgba(56, 189, 248, 0.10) !important;
    border-color: rgba(56, 189, 248, 0.45) !important;
}

.report-stat-card .report-icon {
    width: 42px;
    height: 42px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(56, 189, 248, 0.15);
    color: #dff7ff;
    margin-bottom: 14px;
    font-size: 18px;
}

.report-stat-card h6 {
    color: var(--csr-muted) !important;
    font-weight: 850;
    font-size: 13px;
    line-height: 1.35;
    margin-bottom: 8px;
}

.report-stat-card h3 {
    color: var(--csr-text) !important;
    font-size: 36px;
    font-weight: 950;
    margin: 0;
}

.report-stat-card small {
    color: var(--csr-soft) !important;
    font-weight: 700;
}

.report-section-label {
    color: #ffffff !important;
    font-weight: 950;
    letter-spacing: 0.2px;
    margin: 24px 0 12px;
}

.report-section-label span {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    border-radius: 999px;
    padding: 8px 13px;
    background: rgba(23, 189, 212, 0.13);
    border: 1px solid rgba(23, 189, 212, 0.30);
    color: #e6fbff !important;
    font-size: 13px;
    font-weight: 900;
}

.report-stat-card.report-today-card {
    background: linear-gradient(135deg, rgba(23, 189, 212, 0.13) 0%, rgba(29, 155, 240, 0.08) 100%) !important;
    border-color: rgba(23, 189, 212, 0.34) !important;
}

.report-loading {
    color: var(--csr-muted) !important;
    font-weight: 800;
}

.report-stat-card[data-report-card] {
    cursor: pointer;
}

.report-stat-card[data-report-card].active-report-card {
    border-color: rgba(23, 189, 212, 0.85) !important;
    box-shadow: 0 0 0 2px rgba(23, 189, 212, 0.16), 0 14px 32px rgba(0, 0, 0, 0.28) !important;
}

.report-ticket-panel {
    margin-top: 24px;
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid rgba(96, 165, 250, 0.24);
    background: rgba(8, 20, 48, 0.26);
}

.report-ticket-panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 12px;
    padding: 14px 16px;
    background: rgba(56, 189, 248, 0.10);
    border-bottom: 1px solid rgba(96, 165, 250, 0.22);
}

.report-ticket-panel-header h6 {
    margin: 0;
    color: #ffffff;
    font-weight: 950;
}

.report-ticket-panel-header small,
.report-ticket-empty {
    color: #ffffff !important;
    font-weight: 750;
}

/* Added report ticket list/details text color fix */
.report-ticket-panel,
.report-ticket-panel *,
.report-detail-modal,
.report-detail-modal * {
    color: #ffffff !important;
}

.report-ticket-panel .badge,
.report-ticket-panel .badge *,
.report-detail-modal .badge,
.report-detail-modal .badge *,
.report-detail-modal .btn,
.report-ticket-panel .btn {
    color: #ffffff !important;
}

.report-ticket-table {
    color: #ffffff !important;
    margin-bottom: 0;
}

.report-ticket-table thead th {
    color: #ffffff !important;
    background: rgba(2, 8, 28, 0.28) !important;
    border-color: rgba(96, 165, 250, 0.20) !important;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.4px;
}

.report-ticket-table tbody td {
    border-color: rgba(96, 165, 250, 0.16) !important;
    vertical-align: middle;
    color: #ffffff !important;
}

.report-ticket-table small,
.report-detail-card small,
.report-detail-card strong,
.report-detail-card th,
.report-detail-card td,
.report-detail-card div {
    color: #ffffff !important;
}

.report-ticket-row {
    cursor: pointer;
}

.report-ticket-row:hover {
    background: rgba(23, 189, 212, 0.11) !important;
}

.report-detail-modal .modal-content {
    background: linear-gradient(135deg, rgba(14, 31, 70, 0.98), rgba(8, 28, 52, 0.98)) !important;
    color: var(--csr-text) !important;
    border: 1px solid rgba(96, 165, 250, 0.28);
    border-radius: 18px;
}

.report-detail-modal .modal-header,
.report-detail-modal .modal-footer {
    border-color: rgba(96, 165, 250, 0.20) !important;
}

.report-detail-card {
    background: rgba(255,255,255,0.06);
    border: 1px solid rgba(96, 165, 250, 0.20);
    border-radius: 14px;
    padding: 14px;
    height: 100%;
}

.report-detail-card h6 {
    color: #ffffff;
    font-weight: 950;
    margin-bottom: 12px;
}

.report-detail-card .table {
    color: #ffffff !important;
}

.report-detail-card .table th,
.report-detail-card .table td {
    border-color: rgba(96, 165, 250, 0.16) !important;
}

.report-detail-timeline-item {
    border-left: 3px solid rgba(23, 189, 212, 0.65);
    background: rgba(255,255,255,0.06);
    border-radius: 10px;
    padding: 10px 12px;
    margin-bottom: 10px;
}


.report-filter-card {
    margin: 18px 18px 0;
    padding: 16px;
    border-radius: 16px;
    background: rgba(8, 20, 48, 0.30) !important;
    border: 1px solid rgba(96, 165, 250, 0.22) !important;
}

.report-filter-card label {
    color: var(--csr-soft) !important;
    font-weight: 850;
    font-size: 13px;
    margin-bottom: 7px;
}

.report-filter-card .form-control {
    background: rgba(255, 255, 255, 0.08) !important;
    border: 1px solid rgba(96, 165, 250, 0.35) !important;
    color: #ffffff !important;
    border-radius: 12px !important;
    font-weight: 750;
}

.report-filter-card .form-control:focus {
    background: rgba(255, 255, 255, 0.12) !important;
    border-color: rgba(23, 189, 212, 0.85) !important;
    color: #ffffff !important;
    box-shadow: 0 0 0 0.2rem rgba(23, 189, 212, 0.18) !important;
}

.report-filter-card .form-control::-webkit-calendar-picker-indicator {
    filter: invert(1);
    cursor: pointer;
}

.report-filter-note {
    color: var(--csr-muted) !important;
    font-size: 12px;
    font-weight: 700;
}

.report-filter-badge {
    display: none;
    border-radius: 999px;
    background: rgba(23, 189, 212, 0.14) !important;
    border: 1px solid rgba(23, 189, 212, 0.34) !important;
    color: #e6fbff !important;
    padding: 7px 12px;
    font-size: 12px;
    font-weight: 850;
}


.report-export-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: flex-end;
}

.report-export-actions .btn {
    border-radius: 12px !important;
    font-weight: 900 !important;
    box-shadow: 0 8px 18px rgba(0, 0, 0, 0.18);
}

@media (max-width: 768px) {
    .report-nav {
        align-items: flex-start;
        flex-direction: column;
    }

    .report-stat-card {
        min-height: 130px;
        padding: 17px;
    }

    .report-stat-card h3 {
        font-size: 30px;
    }
}
</style>

<div class="d-flex align-items-center justify-content-between mb-3 flex-wrap gap-2">
    <div>
        <h3 class="report-page-title mb-1">
            <i class="fas fa-chart-line me-2"></i>Report
        </h3>
        <div class="report-page-subtitle"><?= $reportRole === 'csr' ? 'View your own CSR ticket totals. Downloads are limited to Team Leaders and CSR Manager.' : 'View role-based CSR totals with team filters and downloads.' ?></div>
    </div>
    <button type="button" class="btn btn-info text-white fw-bold" onclick="loadReportData()">
        <i class="fas fa-sync-alt me-2"></i>Refresh
    </button>
</div>

<div class="report-panel">
    <div class="report-nav">
        <h5 class="report-nav-title">
            <i class="fas fa-user-check"></i> <?= h(getCsrReportScopeLabel($reportAccess)) ?>
        </h5>
        <span class="report-nav-pill"><?= h($reportAccess['role_label']) ?></span>
    </div>

    <div class="report-filter-card">
        <form id="reportFilterForm" class="row g-3 align-items-end">
            <div class="col-12 col-md-4">
                <label for="reportStartDate">Start date</label>
                <input type="date" class="form-control" id="reportStartDate" name="start_date">
            </div>
            <div class="col-12 col-md-4">
                <label for="reportEndDate">End date</label>
                <input type="date" class="form-control" id="reportEndDate" name="end_date">
            </div>
            <?php if ($reportAccess['can_filter_team']): ?>
            <div class="col-12 col-md-4">
                <label for="reportTeamFilter">Team filter</label>
                <select class="form-control" id="reportTeamFilter" name="team_id">
                    <?php if ($reportRole === 'csr_manager'): ?>
                        <option value="0">All Teams</option>
                    <?php endif; ?>
                    <?php foreach ($reportTeamOptions as $team): ?>
                        <option value="<?= (int)$team['id'] ?>"><?= h($team['team_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <?php if ($reportAccess['can_filter_csr']): ?>
            <div class="col-12 col-md-4">
                <label for="reportCsrFilter">CSR filter</label>
                <select class="form-control" id="reportCsrFilter" name="csr_id">
                    <option value="0">All allowed CSRs</option>
                    <?php foreach ($reportSelectableCsrs as $csrOption): ?>
                        <option value="<?= (int)$csrOption['id'] ?>"><?= h($csrOption['name'] . ' — ' . getCsrRoleLabelForReport($csrOption['role'] ?? 'csr')) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div class="col-12 d-flex gap-2 flex-wrap">
                <button type="button" class="btn btn-outline-light fw-bold" data-quick-range="1">
                    <i class="fas fa-clock me-2"></i>24 Hours
                </button>
                <button type="button" class="btn btn-outline-light fw-bold" data-quick-range="3">
                    <i class="fas fa-calendar-alt me-2"></i>3 Days
                </button>
                <button type="button" class="btn btn-outline-light fw-bold" data-quick-range="7">
                    <i class="fas fa-calendar-week me-2"></i>7 Days
                </button>
                <button type="submit" class="btn btn-info text-white fw-bold">
                    <i class="fas fa-filter me-2"></i>Apply Filter
                </button>
                <button type="button" class="btn btn-outline-light fw-bold" id="clearReportFilter">
                    <i class="fas fa-times me-2"></i>Clear
                </button>
            </div>
            <?php if ($canDownloadReports): ?>
            <div class="col-12 report-export-actions">
                <button type="button" class="btn btn-success text-white" id="downloadExcelReport">
                    <i class="fas fa-file-excel me-2"></i>Download Excel Table
                </button>
                <button type="button" class="btn btn-info text-white" id="downloadCsvReport">
                    <i class="fas fa-file-csv me-2"></i>Download CSV
                </button>
                <button type="button" class="btn btn-danger text-white" id="downloadPdfReport">
                    <i class="fas fa-file-pdf me-2"></i>Download PDF
                </button>
            </div>
            <?php else: ?>
            <div class="col-12">
                <div class="alert alert-info mb-0 fw-bold">
                    <i class="fas fa-eye me-2"></i>Regular CSR accounts can view report totals and ticket lists only. Download access is for Team Leaders and CSR Manager.
                </div>
            </div>
            <?php endif; ?>
            <div class="col-12 d-flex align-items-center justify-content-between flex-wrap gap-2">
                <div class="report-filter-note">
                    <?= $reportRole === 'csr' ? 'Filter counts by the date when you handled, assigned, completed, or canceled a ticket.' : 'Filter by date, quick range, team, or CSR depending on your role access.' ?>
                </div>
                <div id="reportFilterBadge" class="report-filter-badge"></div>
            </div>
        </form>
    </div>

    <div class="p-3 p-md-4">
        <div id="reportLoading" class="report-loading mb-3">
            <i class="fas fa-circle-notch fa-spin me-2"></i>Loading report totals...
        </div>

        <div class="report-section-label mt-0">
            <span><i class="fas fa-chart-bar"></i> Filtered / selected date range</span>
        </div>

        <div class="row g-3">
            <div class="col-6 col-lg">
                <div class="report-stat-card" data-report-card data-report-type="handled" data-report-scope="range" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-ticket-alt"></i></div>
                    <h6>Total tickets handled</h6>
                    <h3 id="reportTotalHandled">0</h3>
                    <small>Tickets you handled</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card" data-report-card data-report-type="assigned" data-report-scope="range" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-user-cog"></i></div>
                    <h6>Total technician assigned</h6>
                    <h3 id="reportTechAssigned">0</h3>
                    <small>Assigned by you</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card" data-report-card data-report-type="in_progress" data-report-scope="range" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-spinner"></i></div>
                    <h6>Total In progress status</h6>
                    <h3 id="reportInProgress">0</h3>
                    <small>Your active handled tickets</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card" data-report-card data-report-type="completed" data-report-scope="range" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-check-circle"></i></div>
                    <h6>Total Completed</h6>
                    <h3 id="reportCompleted">0</h3>
                    <small>Completed by you</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card" data-report-card data-report-type="canceled" data-report-scope="range" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-times-circle"></i></div>
                    <h6>Total Canceled</h6>
                    <h3 id="reportCanceled">0</h3>
                    <small>Canceled by you</small>
                </div>
            </div>
        </div>

        <div class="report-section-label">
            <span><i class="fas fa-calendar-day"></i> Today only — resets every 12 AM</span>
        </div>

        <div class="row g-3">
            <div class="col-6 col-lg">
                <div class="report-stat-card report-today-card" data-report-card data-report-type="handled" data-report-scope="today" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-ticket-alt"></i></div>
                    <h6>Today tickets handled</h6>
                    <h3 id="todayReportTotalHandled">0</h3>
                    <small>Today only</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card report-today-card" data-report-card data-report-type="assigned" data-report-scope="today" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-user-cog"></i></div>
                    <h6>Today technician assigned</h6>
                    <h3 id="todayReportTechAssigned">0</h3>
                    <small>Assigned today</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card report-today-card" data-report-card data-report-type="in_progress" data-report-scope="today" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-spinner"></i></div>
                    <h6>Today In progress status</h6>
                    <h3 id="todayReportInProgress">0</h3>
                    <small>Handled today and currently in progress</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card report-today-card" data-report-card data-report-type="completed" data-report-scope="today" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-check-circle"></i></div>
                    <h6>Today Completed</h6>
                    <h3 id="todayReportCompleted">0</h3>
                    <small>Completed today</small>
                </div>
            </div>

            <div class="col-6 col-lg">
                <div class="report-stat-card report-today-card" data-report-card data-report-type="canceled" data-report-scope="today" role="button" tabindex="0">
                    <div class="report-icon"><i class="fas fa-times-circle"></i></div>
                    <h6>Today Canceled</h6>
                    <h3 id="todayReportCanceled">0</h3>
                    <small>Canceled today</small>
                </div>
            </div>
        </div>

        <div id="reportTicketPanel" class="report-ticket-panel" style="display:none;">
            <div class="report-ticket-panel-header">
                <div>
                    <h6 id="reportTicketPanelTitle"><i class="fas fa-list me-2"></i>Tickets</h6>
                    <small id="reportTicketPanelSubtitle">Click a ticket row to view full details.</small>
                </div>
                <button type="button" class="btn btn-sm btn-outline-light fw-bold" id="closeReportTicketPanel">
                    <i class="fas fa-times me-1"></i>Close
                </button>
            </div>
            <div id="reportTicketListBody" class="p-3">
                <div class="report-ticket-empty">Click a report container above to show tickets.</div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade report-detail-modal" id="reportTicketDetailsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reportTicketDetailsTitle">Ticket Details</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="reportTicketDetailsBody">
                <div class="text-center py-5 report-loading">
                    <i class="fas fa-circle-notch fa-spin me-2"></i>Loading details...
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-light fw-bold" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    if (window.jQuery) {
        initializeReport();
    } else {
        var checkJQuery = setInterval(function() {
            if (window.jQuery) {
                clearInterval(checkJQuery);
                initializeReport();
            }
        }, 100);
    }

    function initializeReport() {
        $(document).ready(function() {
            setDefaultReportDatesFromUrl();
            bindReportFilters();
            loadReportData();
            setInterval(loadReportData, 30000);
            scheduleReportMidnightRefresh();
        });
    }
})();

function bindReportFilters() {
    $('#reportFilterForm').on('submit', function(e) {
        e.preventDefault();
        loadReportData();
    });

    $('#clearReportFilter').on('click', function() {
        $('#reportStartDate').val('');
        $('#reportEndDate').val('');
        $('#reportTeamFilter').val($('#reportTeamFilter option:first').val() || '0');
        $('#reportCsrFilter').val('0');
        updateReportFilterBadge();
        loadReportData();
    });

    $('#reportStartDate, #reportEndDate, #reportTeamFilter, #reportCsrFilter').on('change', function() {
        updateReportFilterBadge();
        if (this.id === 'reportTeamFilter') {
            $('#reportCsrFilter').val('0');
        }
    });

    $('[data-quick-range]').on('click', function() {
        var days = parseInt($(this).data('quick-range'), 10) || 1;
        applyQuickRange(days);
    });

    $('#downloadExcelReport').on('click', function() {
        downloadReport('xls');
    });

    $('#downloadCsvReport').on('click', function() {
        downloadReport('csv');
    });

    $('#downloadPdfReport').on('click', function() {
        downloadReport('pdf');
    });

    $('[data-report-card]').on('click', function() {
        loadReportTicketList($(this).data('report-type'), $(this).data('report-scope'), this);
    });

    $('[data-report-card]').on('keypress', function(e) {
        if (e.which === 13 || e.which === 32) {
            e.preventDefault();
            loadReportTicketList($(this).data('report-type'), $(this).data('report-scope'), this);
        }
    });

    $('#closeReportTicketPanel').on('click', function() {
        $('#reportTicketPanel').slideUp(180);
        $('[data-report-card]').removeClass('active-report-card');
    });
}


function setDefaultReportDatesFromUrl() {
    var params = new URLSearchParams(window.location.search);
    if (params.get('start_date')) {
        $('#reportStartDate').val(params.get('start_date'));
    }
    if (params.get('end_date')) {
        $('#reportEndDate').val(params.get('end_date'));
    }
    updateReportFilterBadge();
}

function getReportFilterData() {
    return {
        start_date: $('#reportStartDate').val(),
        end_date: $('#reportEndDate').val(),
        team_id: $('#reportTeamFilter').length ? $('#reportTeamFilter').val() : '',
        csr_id: $('#reportCsrFilter').length ? $('#reportCsrFilter').val() : ''
    };
}

function applyQuickRange(days) {
    var end = new Date();
    var start = new Date();
    start.setDate(end.getDate() - (days - 1));
    $('#reportStartDate').val(formatDateInput(start));
    $('#reportEndDate').val(formatDateInput(end));
    updateReportFilterBadge();
    loadReportData();
}

function formatDateInput(date) {
    var y = date.getFullYear();
    var m = String(date.getMonth() + 1).padStart(2, '0');
    var d = String(date.getDate()).padStart(2, '0');
    return y + '-' + m + '-' + d;
}

function buildReportQueryString(extraData) {
    var filters = getReportFilterData();
    var params = new URLSearchParams();

    if (filters.start_date) {
        params.set('start_date', filters.start_date);
    }

    if (filters.end_date) {
        params.set('end_date', filters.end_date);
    }

    Object.keys(extraData || {}).forEach(function(key) {
        params.set(key, extraData[key]);
    });

    return params.toString();
}

function downloadReport(format) {
    var queryString = buildReportQueryString({ format: format });
    window.location.href = 'export_report.php' + (queryString ? '?' + queryString : '');
}

function updateReportFilterBadge() {
    var filters = getReportFilterData();
    var badge = $('#reportFilterBadge');

    var extras = [];
    if (filters.team_id && filters.team_id !== '0') extras.push('Team selected');
    if (filters.csr_id && filters.csr_id !== '0') extras.push('CSR selected');

    if (filters.start_date && filters.end_date) {
        badge.text('Filtered: ' + filters.start_date + ' to ' + filters.end_date + (extras.length ? ' • ' + extras.join(' • ') : '')).show();
    } else if (filters.start_date) {
        badge.text('Filtered from: ' + filters.start_date + (extras.length ? ' • ' + extras.join(' • ') : '')).show();
    } else if (filters.end_date) {
        badge.text('Filtered until: ' + filters.end_date + (extras.length ? ' • ' + extras.join(' • ') : '')).show();
    } else {
        if (extras.length) { badge.text(extras.join(' • ')).show(); } else { badge.hide().text(''); }
    }
}

function loadReportData() {
    updateReportFilterBadge();
    $('#reportLoading').html('<i class="fas fa-circle-notch fa-spin me-2"></i>Loading report totals...').show();

    $.ajax({
        url: 'ajax/get_dashboard_data.php',
        method: 'GET',
        data: getReportFilterData(),
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                updateReportStats(response.report_stats || {});
                updateTodayReportStats(response.today_report_stats || {});
                refreshReportContextOptions(response.report_context || {});
                $('#reportLoading').html('<i class="fas fa-check-circle me-2"></i>Report updated').fadeOut(1400);
            } else {
                showReportError(response.message || 'Unable to load report data.');
            }
        },
        error: function(xhr, status, error) {
            console.error('Report AJAX Error:', error);
            showReportError('Failed to connect to server.');
        }
    });
}

function refreshReportContextOptions(context) {
    if (!context || !context.selectable_csrs || !$('#reportCsrFilter').length) return;
    var selected = String($('#reportCsrFilter').val() || '0');
    var html = '<option value="0">All allowed CSRs</option>';
    (context.selectable_csrs || []).forEach(function(csr) {
        var role = csr.role === 'team_leader' ? 'Team Leader' : (csr.role === 'csr_manager' ? 'CSR Manager' : 'CSR');
        html += '<option value="' + parseInt(csr.id, 10) + '">' + escapeHtml((csr.name || 'CSR') + ' — ' + role) + '</option>';
    });
    $('#reportCsrFilter').html(html);
    if ($('#reportCsrFilter option[value="' + selected + '"]').length) {
        $('#reportCsrFilter').val(selected);
    } else {
        $('#reportCsrFilter').val('0');
    }
}

function updateReportStats(reportStats) {
    $('#reportTotalHandled').text(reportStats.total_tickets_handled || 0);
    $('#reportTechAssigned').text(reportStats.total_technician_assigned || 0);
    $('#reportInProgress').text(reportStats.total_in_progress || 0);
    $('#reportCompleted').text(reportStats.total_completed || 0);
    $('#reportCanceled').text(reportStats.total_canceled || 0);
}

function updateTodayReportStats(todayStats) {
    $('#todayReportTotalHandled').text(todayStats.total_tickets_handled || 0);
    $('#todayReportTechAssigned').text(todayStats.total_technician_assigned || 0);
    $('#todayReportInProgress').text(todayStats.total_in_progress || 0);
    $('#todayReportCompleted').text(todayStats.total_completed || 0);
    $('#todayReportCanceled').text(todayStats.total_canceled || 0);
}

function scheduleReportMidnightRefresh() {
    var now = new Date();
    var nextMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 5);
    var delay = Math.max(1000, nextMidnight.getTime() - now.getTime());

    setTimeout(function() {
        loadReportData();
        scheduleReportMidnightRefresh();
    }, delay);
}

function getReportTypeLabel(type) {
    var labels = {
        handled: 'Tickets handled',
        assigned: 'Technician assigned',
        in_progress: 'In progress tickets',
        completed: 'Completed tickets',
        canceled: 'Canceled tickets'
    };
    return labels[type] || 'Tickets';
}

function loadReportTicketList(type, scope, cardElement) {
    $('[data-report-card]').removeClass('active-report-card');
    $(cardElement).addClass('active-report-card');

    var data = getReportFilterData();
    data.type = type;
    data.scope = scope;

    var scopeLabel = scope === 'today' ? 'Today only' : 'Filtered / selected date range';
    $('#reportTicketPanelTitle').html('<i class="fas fa-list me-2"></i>' + escapeHtml(getReportTypeLabel(type)));
    $('#reportTicketPanelSubtitle').text(scopeLabel + ' — click a ticket row to view details, edit history, technician assigned, and notes.');
    $('#reportTicketListBody').html('<div class="report-ticket-empty"><i class="fas fa-circle-notch fa-spin me-2"></i>Loading tickets...</div>');
    $('#reportTicketPanel').slideDown(180);

    $.ajax({
        url: 'ajax/get_report_ticket_list.php',
        method: 'GET',
        data: data,
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderReportTicketList(response.tickets || [], type, scope);
            } else {
                $('#reportTicketListBody').html('<div class="alert alert-warning mb-0">' + escapeHtml(response.message || 'Unable to load tickets.') + '</div>');
            }
        },
        error: function() {
            $('#reportTicketListBody').html('<div class="alert alert-danger mb-0">Error loading ticket list.</div>');
        }
    });
}

function renderReportTicketList(tickets, type, scope) {
    if (!tickets.length) {
        $('#reportTicketListBody').html('<div class="report-ticket-empty">No tickets found for this container.</div>');
        return;
    }

    var html = `
        <div class="table-responsive">
            <table class="table table-hover report-ticket-table">
                <thead>
                    <tr>
                        <th>Request #</th>
                        <th>Source</th>
                        <th>Customer</th>
                        <th>Appliance / Brand</th>
                        <th>Status</th>
                        <th>Technician assigned</th>
                        <th>Notes</th>
                        <th>Ticket Age</th>
                        <th>Last Updated</th>
                        <th>Activity date</th>
                    </tr>
                </thead>
                <tbody>
    `;

    tickets.forEach(function(ticket) {
        var statusColor = ticket.status_color || '#17bdd4';
        html += `
            <tr class="report-ticket-row" onclick="openReportTicketDetails(${parseInt(ticket.id, 10)})">
                <td><strong>${escapeHtml(ticket.request_number || '')}</strong></td>
                <td><span class="badge bg-info">${escapeHtml(ticket.ticket_source_label || 'Customer Online Request')}</span></td>
                <td>${escapeHtml(ticket.full_name || '')}<br><small>${escapeHtml(ticket.city_name || '')}</small></td>
                <td>${escapeHtml(ticket.appliance_type || 'N/A')}<br><small>${escapeHtml(ticket.brand || 'N/A')}</small></td>
                <td><span class="badge" style="background:${escapeHtml(statusColor)};color:white;">${escapeHtml(ticket.status_name || 'N/A')}</span></td>
                <td>${escapeHtml(ticket.technician_names || 'No technician assigned')}</td>
                <td><span class="badge bg-info">${parseInt(ticket.notes_count || 0, 10)}</span></td>
                <td><small>${formatReportDuration(ticket.ticket_age_minutes)}</small></td>
                <td><small>${formatReportDate(ticket.last_updated_at || ticket.requested_at)}</small></td>
                <td><small>${formatReportDate(ticket.activity_date || ticket.requested_at)}</small></td>
            </tr>
        `;
    });

    html += `</tbody></table></div>`;
    $('#reportTicketListBody').html(html);
}

function openReportTicketDetails(requestId) {
    $('#reportTicketDetailsTitle').text('Ticket Details');
    $('#reportTicketDetailsBody').html('<div class="text-center py-5 report-loading"><i class="fas fa-circle-notch fa-spin me-2"></i>Loading details...</div>');
    $('#reportTicketDetailsModal').modal('show');

    $.ajax({
        url: 'ajax/get_report_ticket_details.php',
        method: 'GET',
        data: { request_id: requestId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                renderReportTicketDetails(response.request);
            } else {
                $('#reportTicketDetailsBody').html('<div class="alert alert-warning mb-0">' + escapeHtml(response.message || 'Unable to load ticket details.') + '</div>');
            }
        },
        error: function() {
            $('#reportTicketDetailsBody').html('<div class="alert alert-danger mb-0">Error loading ticket details.</div>');
        }
    });
}

function renderReportTicketDetails(request) {
    $('#reportTicketDetailsTitle').text((request.request_number || 'Ticket') + ' — ' + (request.full_name || 'Customer'));
    var statusColor = request.status_color || '#17bdd4';
    var html = `
        <div class="row g-3">
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-ticket-alt me-2"></i>Request Information</h6>
                    <table class="table table-sm mb-0">
                        <tr><th width="38%">Request #</th><td><strong>${escapeHtml(request.request_number || '')}</strong></td></tr>
                        <tr><th>Source</th><td><span class="badge bg-info">${escapeHtml(request.ticket_source_label || 'Customer Online Request')}</span></td></tr>
                        <tr><th>Status</th><td><span class="badge" style="background:${escapeHtml(statusColor)};color:white;">${escapeHtml(request.status_name || 'N/A')}</span></td></tr>
                        <tr><th>Urgency</th><td>${escapeHtml(request.urgency_name || 'N/A')}</td></tr>
                        <tr><th>Requested</th><td>${formatReportDate(request.requested_at)}</td></tr>
                        <tr><th>Ticket Age</th><td>${formatReportDuration(request.ticket_age_minutes)}</td></tr>
                        ${request.status_name === 'In Progress' || request.job_status_id == 3 ? `<tr><th>In Progress Timer</th><td>${formatReportDuration(request.in_progress_minutes)}</td></tr>` : ''}
                        <tr><th>Last Updated</th><td>${formatReportDate(request.last_updated_at || request.requested_at)}</td></tr>
                        <tr><th>Preferred</th><td>${escapeHtml(request.preferred_date || 'N/A')} ${escapeHtml(request.preferred_time || '')}</td></tr>
                    </table>
                </div>
            </div>
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-user me-2"></i>Customer Information</h6>
                    <table class="table table-sm mb-0">
                        <tr><th width="38%">Name</th><td><strong>${escapeHtml(request.full_name || '')}</strong></td></tr>
                        <tr><th>Phone</th><td>${escapeHtml(request.phone_number || 'N/A')}</td></tr>
                        <tr><th>Email</th><td>${escapeHtml(request.email || 'N/A')}</td></tr>
                        <tr><th>Address</th><td>${escapeHtml(request.service_address || 'N/A')}<br><small>${escapeHtml(request.city_name || '')} ${escapeHtml(request.zip_code || '')}</small></td></tr>
                    </table>
                </div>
            </div>
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-tools me-2"></i>Appliance / Issue</h6>
                    <table class="table table-sm mb-0">
                        <tr><th width="38%">Brand</th><td>${escapeHtml(request.brand || 'N/A')}</td></tr>
                        <tr><th>Appliance</th><td>${escapeHtml(request.appliance_type || 'N/A')}</td></tr>
                        <tr><th>Model</th><td>${escapeHtml(request.model_number || 'N/A')}</td></tr>
                        <tr><th>Serial</th><td>${escapeHtml(request.serial_number || 'N/A')}</td></tr>
                    </table>
                    <div class="mt-2"><strong>Issue:</strong><br>${escapeHtml(request.issue_description || 'No issue description.')}</div>
                    ${request.special_request ? '<div class="mt-2"><strong>Special Request:</strong><br>' + escapeHtml(request.special_request) + '</div>' : ''}
                </div>
            </div>
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-user-cog me-2"></i>Technician Assigned (${(request.all_assignments || []).length})</h6>
                    ${renderReportAssignments(request.all_assignments || [])}
                </div>
            </div>
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-history me-2"></i>Edit / Status History</h6>
                    ${renderReportHistory(request)}
                </div>
            </div>
            <div class="col-md-6">
                <div class="report-detail-card">
                    <h6><i class="fas fa-sticky-note me-2"></i>Notes (${(request.notes || []).length})</h6>
                    ${renderReportNotes(request.notes || [])}
                </div>
            </div>
        </div>
    `;
    $('#reportTicketDetailsBody').html(html);
}

function renderReportAssignments(assignments) {
    if (!assignments.length) {
        return '<div class="report-ticket-empty">No technician assigned.</div>';
    }
    var html = '<div class="table-responsive"><table class="table table-sm mb-0"><thead><tr><th>Role</th><th>Technician</th><th>Status</th><th>Assigned</th><th>Notes</th></tr></thead><tbody>';
    assignments.forEach(function(a) {
        html += `<tr>
            <td>${escapeHtml(a.role_display || a.assignment_type || 'Technician')}</td>
            <td><strong>${escapeHtml(a.technician_name || 'N/A')}</strong><br><small>${escapeHtml(a.technician_phone || '')}</small></td>
            <td>${escapeHtml((a.status || '').replace('_', ' '))}</td>
            <td><small>${formatReportDate(a.assigned_at)}</small></td>
            <td><small>${escapeHtml(a.csr_notes || a.technician_notes || '')}</small></td>
        </tr>`;
    });
    html += '</tbody></table></div>';
    return html;
}

function renderReportHistory(request) {
    var items = [];
    (request.status_history || []).forEach(function(h) {
        items.push({
            title: 'Status changed to ' + (h.status_name || 'N/A'),
            meta: (h.updated_by_name || 'CSR') + ' • ' + formatReportDate(h.changed_at),
            body: h.notes || ''
        });
    });
    (request.edit_logs || []).forEach(function(log) {
        items.push({
            title: log.action || 'Update',
            meta: (log.user_name || log.user_role || 'User') + ' • ' + formatReportDate(log.created_at),
            body: [log.notes, log.old_value ? 'Old: ' + log.old_value : '', log.new_value ? 'New: ' + log.new_value : ''].filter(Boolean).join(' | ')
        });
    });

    if (!items.length) {
        return '<div class="report-ticket-empty">No edit history found.</div>';
    }

    return items.map(function(item) {
        return `<div class="report-detail-timeline-item">
            <strong>${escapeHtml(item.title)}</strong><br>
            <small>${escapeHtml(item.meta)}</small>
            ${item.body ? '<div class="mt-1">' + escapeHtml(item.body) + '</div>' : ''}
        </div>`;
    }).join('');
}

function renderReportNotes(notes) {
    if (!notes.length) {
        return '<div class="report-ticket-empty">No notes found.</div>';
    }
    return notes.map(function(note) {
        return `<div class="report-detail-timeline-item">
            <strong>${escapeHtml(note.note_type_label || 'Note')}</strong> <small>by ${escapeHtml(note.created_by_name || 'CSR')}</small><br>
            <small>${formatReportDate(note.created_at)}</small>
            <div class="mt-1">${escapeHtml(note.note_content || '')}</div>
        </div>`;
    }).join('');
}

function formatReportDate(value) {
    if (!value) return 'N/A';
    var normalized = String(value).replace(' ', 'T');
    var date = new Date(normalized);
    if (isNaN(date.getTime())) {
        return value;
    }
    return date.toLocaleString();
}

function formatReportDuration(minutes) {
    var total = parseInt(minutes || 0, 10);
    if(total < 60) return (total <= 1 ? '1 minute' : total + ' minutes');
    var hours = Math.floor(total / 60);
    if(hours < 24) return (hours === 1 ? '1 hour' : hours + ' hours');
    var days = Math.floor(hours / 24);
    return (days === 1 ? '1 day' : days + ' days');
}

function showReportError(message) {
    $('#reportLoading').html('<i class="fas fa-exclamation-triangle me-2"></i>' + escapeHtml(message)).show();
}

function escapeHtml(value) {
    return $('<div>').text(value || '').html();
}
</script>

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