<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
     
    @hotelSettings
    <title>Advanced Reports Dashboard - {{ hotelName() }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta3/css/bootstrap-select.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/apexcharts@3.41.0/dist/apexcharts.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <style>
        :root {
            --primary-green: #1a936f;
            --secondary-green: #88d498;
            --dark-green: #114b5f;
            --room-color: #6610f2;
            --reservation-color: #20c9a6;
            --guest-color: #36b9cc;
            --frontdesk-color: #9b59b6;
            --service-color: #17a673;
            --housekeeping-color: #f6c23e;
            --maintenance-color: #6f42c1;
            --inventory-color: #e74a3b;
            --account-color: #3498db;
            --hr-color: #2e59d9;
            --document-color: #1cc88a;
            --survey-color: #e83e8c;
            --pos-color: #20c997;
        }
        
        body {
            background-color: #f4f7f9;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
        }
        
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
        }
        
        /* Print styles for portrait and landscape */
        @media print {
            body {
                background-color: white;
                padding: 10mm;
            }
            
            .no-print, .quick-filter-bar, .btn, .card-header .btn-group, .print-layout-btn {
                display: none !important;
            }
            
            .card {
                break-inside: avoid;
                page-break-inside: avoid;
                border: 1px solid #ddd !important;
                box-shadow: none !important;
            }
            
            .kpi-card {
                break-inside: avoid;
                page-break-inside: avoid;
            }
            
            .module-card {
                break-inside: avoid;
                page-break-inside: avoid;
            }
        }
        
        /* Portrait specific print */
        @media print and (orientation: portrait) {
            body {
                width: 210mm;
            }
        }
        
        /* Landscape specific print */
        @media print and (orientation: landscape) {
            body {
                width: 297mm;
            }
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 12px 12px 0 0 !important;
            padding: 15px 20px;
            border: none;
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .report-card {
            transition: transform 0.3s, box-shadow 0.3s;
            border: none;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.08);
        }
        
        .report-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
        }
        
        .kpi-card {
            background: linear-gradient(135deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            height: 100%;
            position: relative;
            overflow: hidden;
        }
        
        .kpi-card::after {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200px;
            height: 200px;
            background: rgba(255,255,255,0.1);
            border-radius: 50%;
        }
        
        .kpi-value {
            font-size: 2rem;
            font-weight: bold;
            margin-bottom: 5px;
            position: relative;
            z-index: 1;
        }
        
        .kpi-label {
            font-size: 0.9rem;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }
        
        .revenue-breakdown {
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            padding: 10px;
            margin-top: 10px;
        }
        
        .revenue-item {
            display: flex;
            justify-content: space-between;
            font-size: 0.85rem;
            margin-bottom: 5px;
        }
        
        .revenue-item:last-child {
            margin-bottom: 0;
        }
        
        .module-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-block;
        }
        
        .badge-room { background-color: rgba(102, 16, 242, 0.12); color: var(--room-color); }
        .badge-reservation { background-color: rgba(32, 201, 166, 0.12); color: var(--reservation-color); }
        .badge-guest { background-color: rgba(54, 185, 204, 0.12); color: var(--guest-color); }
        .badge-frontdesk { background-color: rgba(155, 89, 182, 0.12); color: var(--frontdesk-color); }
        .badge-service { background-color: rgba(23, 166, 115, 0.12); color: var(--service-color); }
        .badge-housekeeping { background-color: rgba(246, 194, 62, 0.12); color: var(--housekeeping-color); }
        .badge-maintenance { background-color: rgba(111, 66, 193, 0.12); color: var(--maintenance-color); }
        .badge-inventory { background-color: rgba(231, 74, 59, 0.12); color: var(--inventory-color); }
        .badge-account { background-color: rgba(52, 152, 219, 0.12); color: var(--account-color); }
        .badge-hr { background-color: rgba(46, 89, 217, 0.12); color: var(--hr-color); }
        .badge-document { background-color: rgba(28, 200, 138, 0.12); color: var(--document-color); }
        .badge-survey { background-color: rgba(232, 62, 140, 0.12); color: var(--survey-color); }
        .badge-pos { background-color: rgba(32, 201, 151, 0.12); color: var(--pos-color); }
        
        .module-card {
            border-left: 5px solid;
            transition: all 0.3s;
            height: 100%;
            border-radius: 12px;
            overflow: hidden;
        }
        
        .module-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.12);
        }
        
        .module-card-room { border-left-color: var(--room-color); }
        .module-card-reservation { border-left-color: var(--reservation-color); }
        .module-card-guest { border-left-color: var(--guest-color); }
        .module-card-frontdesk { border-left-color: var(--frontdesk-color); }
        .module-card-service { border-left-color: var(--service-color); }
        .module-card-housekeeping { border-left-color: var(--housekeeping-color); }
        .module-card-maintenance { border-left-color: var(--maintenance-color); }
        .module-card-inventory { border-left-color: var(--inventory-color); }
        .module-card-account { border-left-color: var(--account-color); }
        .module-card-hr { border-left-color: var(--hr-color); }
        .module-card-document { border-left-color: var(--document-color); }
        .module-card-survey { border-left-color: var(--survey-color); }
        .module-card-pos { border-left-color: var(--pos-color); }
        
        .page-header {
            background: linear-gradient(135deg, var(--dark-green) 0%, var(--primary-green) 100%);
            padding: 25px 30px;
            border-radius: 15px;
            margin-bottom: 30px;
            color: white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .report-list {
            list-style: none;
            padding: 0;
            margin: 0;
            max-height: 250px;
            overflow-y: auto;
        }
        
        .report-list li {
            padding: 8px 0;
            border-bottom: 1px solid #eef2f6;
        }
        
        .report-list li:last-child {
            border-bottom: none;
        }
        
        .report-list a {
            color: #2c3e50;
            font-size: 0.9rem;
            text-decoration: none;
            cursor: pointer;
        }
        
        .report-list a:hover {
            color: var(--primary-green);
        }
        
        .quick-filter-bar {
            border: none;
            border-radius: 12px;
            box-shadow: 0 3px 10px rgba(0,0,0,0.05);
        }
        
        .btn-outline-primary {
            border-color: var(--primary-green);
            color: var(--primary-green);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .progress {
            background-color: rgba(255,255,255,0.3);
            height: 6px;
            border-radius: 10px;
        }
        
        .progress-bar {
            background-color: white;
            border-radius: 10px;
        }
        
        .amount-badge {
            font-weight: 600;
            color: var(--primary-green);
            font-size: 0.8rem;
        }
        
        .money-icon {
            color: #28a745;
        }
        
        .print-layout-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 1000;
            border-radius: 50px;
            padding: 12px 25px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        .download-spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .layout-selector {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .layout-option {
            flex: 1;
            text-align: center;
            padding: 10px;
            border: 2px solid #dee2e6;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .layout-option:hover {
            border-color: var(--primary-green);
        }
        
        .layout-option.selected {
            border-color: var(--primary-green);
            background-color: rgba(26, 147, 111, 0.1);
        }
        
        .layout-option i {
            font-size: 1.5rem;
            display: block;
            margin-bottom: 5px;
        }
        
        @media (max-width: 768px) {
            .kpi-value {
                font-size: 1.5rem;
            }
            
            .print-layout-btn {
                bottom: 10px;
                right: 10px;
                padding: 8px 15px;
                font-size: 0.9rem;
            }
        }
    </style>
</head>
<body>
    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header no-print">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h1 class="h3 mb-2"><i class="fas fa-chart-line me-2"></i>Reports Dashboard</h1>
                    <p class="mb-0 opacity-75">Business intelligence, analytics, and performance insights for {{ hotelName() }}</p>
                </div>
                <div class="col-md-4 text-end">
                    <a href="/dashboard" class="btn btn-light">
                        <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                    </a>
                </div>
            </div>
        </div>

        <!-- Quick Filter Bar -->
        <div class="card quick-filter-bar mb-4 no-print">
            <div class="card-body">
                <div class="row g-3 align-items-end">
                    <div class="col-lg-3 col-md-6">
                        <label class="form-label fw-semibold">Date Range</label>
                        <select class="form-select" id="dateRangeSelect">
                            <option value="today">Today</option>
                            <option value="yesterday">Yesterday</option>
                            <option value="this_week" selected>This Week</option>
                            <option value="last_week">Last Week</option>
                            <option value="this_month">This Month</option>
                            <option value="last_month">Last Month</option>
                            <option value="this_quarter">This Quarter</option>
                            <option value="last_quarter">Last Quarter</option>
                            <option value="this_year">This Year</option>
                            <option value="last_year">Last Year</option>
                            <option value="custom">Custom Range</option>
                        </select>
                    </div>
                    <div class="col-lg-3 col-md-6" id="customDateRange" style="display: none;">
                        <div class="input-group">
                            <input type="text" class="form-control" id="dateRangePicker" placeholder="Select date range">
                        </div>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <label class="form-label fw-semibold">Module</label>
                        <select class="form-select selectpicker" id="moduleFilter" data-live-search="true">
                            <option value="all">All Modules</option>
                            <option value="room">Room Management</option>
                            <option value="reservation">Reservations</option>
                            <option value="guest">Guests</option>
                            <option value="frontdesk">FrontDesk</option>
                            <option value="service">Services</option>
                            <option value="pos">Point of Sale</option>
                            <option value="housekeeping">Housekeeping</option>
                            <option value="maintenance">Maintenance</option>
                            <option value="inventory">Inventory</option>
                            <option value="account">Accounts</option>
                            <option value="hr">Human Resource</option>
                            <option value="document">Documents</option>
                            <option value="survey">Surveys</option>
                        </select>
                    </div>
                    <div class="col-lg-3 col-md-6">
                        <div class="d-flex gap-2">
                            <button class="btn btn-primary flex-fill" onclick="applyFilters()">
                                <i class="fas fa-filter me-2"></i>Apply
                            </button>
                            <button class="btn btn-outline-secondary" onclick="clearFilters()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-10">
                        <div class="input-group">
                            <span class="input-group-text"><i class="fas fa-search"></i></span>
                            <input type="text" class="form-control" placeholder="Search reports by name or module..." id="reportSearch">
                            <button class="btn btn-outline-secondary" type="button" onclick="clearSearch()">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-success w-100" onclick="preparePrintLayout()">
                            <i class="fas fa-print me-2"></i>Print Reports
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- KPI Dashboard with Revenue Breakdown -->
        <div class="row mb-4" id="kpiDashboard">
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="kpi-card">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <div class="kpi-value" id="occupancyRate">{{ number_format($occupancyRate ?? 0, 1) }}%</div>
                            <div class="kpi-label">Occupancy Rate</div>
                        </div>
                        <div>
                            <span class="badge bg-white text-dark px-3 py-2">Today</span>
                        </div>
                    </div>
                    <div class="mt-3">
                        <div class="progress">
                            <div class="progress-bar" role="progressbar" style="width: {{ min($occupancyRate ?? 0, 100) }}%" id="occupancyProgress"></div>
                        </div>
                        <div class="d-flex justify-content-between mt-2 small">
                            <span>Rooms Sold: <strong id="roomsSold">{{ $roomsSold ?? 0 }}</strong>/<span id="totalRooms">{{ $totalRooms ?? 0 }}</span></span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="kpi-card">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <div class="kpi-value" id="currentGuests">{{ $currentGuests ?? 0 }}</div>
                            <div class="kpi-label">Current Guests</div>
                        </div>
                        <div>
                            <span class="badge bg-white text-dark px-3 py-2">In House</span>
                        </div>
                    </div>
                    <div class="mt-3">
                        <div class="d-flex justify-content-between small">
                            <span>Arrivals: <strong id="arrivalsCount">{{ $arrivalsCount ?? 0 }}</strong></span>
                            <span>Departures: <strong id="departuresCount">{{ $departuresCount ?? 0 }}</strong></span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="kpi-card">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <div class="kpi-value" id="totalRevenue">UGX {{ number_format($totalRevenue ?? 0, 0) }}</div>
                            <div class="kpi-label">Total Revenue</div>
                        </div>
                        <div>
                            <span class="badge bg-white text-dark px-3 py-2">Today</span>
                        </div>
                    </div>
                    <div class="revenue-breakdown">
                        <div class="revenue-item">
                            <span><i class="fas fa-hotel me-1"></i> Frontdesk (Check-ins):</span>
                            <span class="fw-bold" id="frontdeskRevenue">UGX {{ number_format($frontdeskRevenue ?? 0) }}</span>
                        </div>
                        <div class="revenue-item">
                            <span><i class="fas fa-utensils me-1"></i> Food & Beverage:</span>
                            <span class="fw-bold" id="fnbRevenue">UGX {{ number_format($fnbRevenue ?? 0) }}</span>
                        </div>
                        <div class="revenue-item">
                            <span><i class="fas fa-spa me-1"></i> Services:</span>
                            <span class="fw-bold" id="servicesRevenue">UGX {{ number_format($servicesRevenue ?? 0) }}</span>
                        </div>
                        <div class="revenue-item border-top border-light mt-1 pt-1">
                            <span>VAT (18%):</span>
                            <span class="fw-bold" id="vatAmount">UGX {{ number_format($vatAmount ?? 0) }}</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance Chart & Quick Generate -->
        <div class="row mb-4">
            <div class="col-lg-8">
                <div class="card report-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0"><i class="fas fa-chart-line me-2"></i>Revenue Trends by Source</h5>
                        <div class="btn-group no-print" role="group">
                            <button type="button" class="btn btn-sm btn-light active" onclick="updateChartPeriod('week')">Week</button>
                            <button type="button" class="btn btn-sm btn-light" onclick="updateChartPeriod('month')">Month</button>
                            <button type="button" class="btn btn-sm btn-light" onclick="updateChartPeriod('quarter')">Quarter</button>
                            <button type="button" class="btn btn-sm btn-light" onclick="updateChartPeriod('year')">Year</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="performanceChart" style="height: 320px;"></div>
                        <div id="chartNoData" class="text-center text-muted mt-3" style="display: none;">
                            <i class="fas fa-chart-line fa-2x mb-2"></i>
                            <p>No data available for selected period</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4">
                <div class="card report-card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-bolt me-2"></i>Quick Generate</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Report Type</label>
                            <select class="form-select" id="quickReportType">
                                <option value="daily_summary">Daily Summary Report</option>
                                <option value="revenue_analysis">Revenue Analysis</option>
                                <option value="occupancy_report">Occupancy Report</option>
                                <option value="financial_statement">Financial Statement</option>
                                <option value="pos_summary">POS Sales Summary</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Format</label>
                            <div class="btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="format" id="pdf" checked>
                                <label class="btn btn-outline-danger" for="pdf">
                                    <i class="fas fa-file-pdf me-1"></i>PDF
                                </label>
                                <input type="radio" class="btn-check" name="format" id="excel">
                                <label class="btn btn-outline-success" for="excel">
                                    <i class="fas fa-file-excel me-1"></i>Excel
                                </label>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label fw-semibold">Paper Orientation</label>
                            <div class="layout-selector">
                                <div class="layout-option selected" id="portraitOption" onclick="setLayout('portrait')">
                                    <i class="fas fa-phone"></i>
                                    <span>Portrait</span>
                                </div>
                                <div class="layout-option" id="landscapeOption" onclick="setLayout('landscape')">
                                    <i class="fas fa-tablet-alt"></i>
                                    <span>Landscape</span>
                                </div>
                            </div>
                            <input type="hidden" id="selectedLayout" value="portrait">
                        </div>
                        <button class="btn btn-primary w-100 py-2" onclick="generateQuickReport()" id="quickGenerateBtn">
                            <i class="fas fa-play-circle me-2"></i>Generate & Download
                        </button>
                        <div id="quickGenerateProgress" class="text-center mt-2" style="display: none;">
                            <span class="download-spinner"></span> Generating...
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Available Reports Section -->
        <div class="row">
            <div class="col-12">
                <div class="card report-card">
                    <div class="card-header">
                        <h5 class="mb-0"><i class="fas fa-layer-group me-2"></i>Available Reports by Module</h5>
                    </div>
                    <div class="card-body">
                        <div class="row" id="reportsGrid">
                            <!-- ==================== FRONT DESK & GUEST REPORTS ==================== -->
                            <!-- Room Management (Expanded with all new reports) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-room">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-room me-2">Room Management</span>
                                            <i class="fas fa-bed ms-auto" style="color: var(--room-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'occupancy', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Occupancy Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'occupancy', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'availability', event)">
                                                        <i class="fas fa-door-open text-primary me-2"></i>Room Availability
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'availability', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'revenue_by_room', event)">
                                                        <i class="fas fa-money-bill-wave text-primary me-2"></i>Revenue by Room
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'revenue_by_room', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <!-- NEW: Room Inventory Status -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'inventory_status', event)">
                                                        <i class="fas fa-boxes text-primary me-2"></i>Room Inventory Status
                                                        <small class="text-muted ms-1">(By Type)</small>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'inventory_status', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <!-- NEW: Room Amenities Report -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'amenities', event)">
                                                        <i class="fas fa-wifi text-primary me-2"></i>Room Amenities Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'amenities', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <!-- NEW: Room Type Performance -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('room', 'type_performance', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Room Type Performance
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('room', 'type_performance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- FrontDesk (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-frontdesk">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-frontdesk me-2">FrontDesk</span>
                                            <i class="fas fa-bell-concierge ms-auto" style="color: var(--frontdesk-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'daily_operations', event)">
                                                        <i class="fas fa-clipboard-list text-primary me-2"></i>Daily Operations Dashboard
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'daily_operations', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'guest_segmentation', event)">
                                                        <i class="fas fa-users text-primary me-2"></i>Guest Segmentation Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'guest_segmentation', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'checkin_checkout', event)">
                                                        <i class="fas fa-right-left text-primary me-2"></i>Check-in/Check-out Log
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'checkin_checkout', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'checkin_analytics', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Check-in/Check-out Analytics
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'checkin_analytics', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'overstay_report', event)">
                                                        <i class="fas fa-clock text-primary me-2"></i>Overstay & Extended Stay Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'overstay_report', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('frontdesk', 'payment_summary', event)">
                                                        <i class="fas fa-credit-card text-primary me-2"></i>Payment Summary
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('frontdesk', 'payment_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Reservations (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-reservation">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-reservation me-2">Reservations</span>
                                            <i class="fas fa-calendar-check ms-auto" style="color: var(--reservation-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'pipeline', event)">
                                                        <i class="fas fa-filter text-primary me-2"></i>Reservation Pipeline
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'pipeline', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'booking_source', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Booking Source Analysis
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'booking_source', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'booking_summary', event)">
                                                        <i class="fas fa-list-alt text-primary me-2"></i>Booking Summary
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'booking_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'future_occupancy', event)">
                                                        <i class="fas fa-calendar text-primary me-2"></i>Future Occupancy Forecast
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'future_occupancy', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'lead_time', event)">
                                                        <i class="fas fa-hourglass-half text-primary me-2"></i>Lead Time Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'lead_time', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('reservation', 'cancellation', event)">
                                                        <i class="fas fa-times-circle text-primary me-2"></i>Cancellation Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('reservation', 'cancellation', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Guests (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-guest">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-guest me-2">Guests</span>
                                            <i class="fas fa-users ms-auto" style="color: var(--guest-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('guest', 'segmentation', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Guest Segmentation
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('guest', 'segmentation', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('guest', 'demographics', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Guest Demographics
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('guest', 'demographics', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('guest', 'stay_history', event)">
                                                        <i class="fas fa-clock-rotate-left text-primary me-2"></i>Stay History
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('guest', 'stay_history', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('guest', 'spending_patterns', event)">
                                                        <i class="fas fa-money-bill-trend-up text-primary me-2"></i>Spending Patterns
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('guest', 'spending_patterns', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('guest', 'top_10', event)">
                                                        <i class="fas fa-crown text-primary me-2"></i>Top 10 Spending Guests
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('guest', 'top_10', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== ACCOUNTING & FINANCIAL REPORTS ==================== -->
                            <!-- Accounts (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-account">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-account me-2">Accounts</span>
                                            <i class="fas fa-coins ms-auto" style="color: var(--account-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'executive_summary', event)">
                                                        <i class="fas fa-chart-simple text-primary me-2"></i>Executive Financial Summary
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'executive_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'revenue_summary', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Revenue Summary
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'revenue_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'revenue_performance', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Revenue Performance Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'revenue_performance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'transaction_register', event)">
                                                        <i class="fas fa-book text-primary me-2"></i>Document & Transaction Register
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'transaction_register', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'balance_sheet', event)">
                                                        <i class="fas fa-scale-balanced text-primary me-2"></i>Balance Sheet
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'balance_sheet', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'profit_loss', event)">
                                                        <i class="fas fa-scale-balanced text-primary me-2"></i>Profit & Loss
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'profit_loss', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'cash_flow', event)">
                                                        <i class="fas fa-money-bill-wave text-primary me-2"></i>Cash Flow Statement
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'cash_flow', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'aging', event)">
                                                        <i class="fas fa-clock text-primary me-2"></i>Accounts Payable/Receivable Aging
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'aging', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'vat_report', event)">
                                                        <i class="fas fa-calculator text-primary me-2"></i>VAT Report
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'vat_report', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'forecast_vs_actual', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Forecast vs. Actual
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'forecast_vs_actual', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('account', 'year_over_year', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Year-over-Year Comparison
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('account', 'year_over_year', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== HOUSEKEEPING REPORTS ==================== -->
                            <!-- Housekeeping (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-housekeeping">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-housekeeping me-2">Housekeeping</span>
                                            <i class="fas fa-broom ms-auto" style="color: var(--housekeeping-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('housekeeping', 'productivity_dashboard', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Housekeeping Productivity Dashboard
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('housekeeping', 'productivity_dashboard', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('housekeeping', 'cleaning_status', event)">
                                                        <i class="fas fa-check-circle text-primary me-2"></i>Cleaning Status
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('housekeeping', 'cleaning_status', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('housekeeping', 'staff_productivity', event)">
                                                        <i class="fas fa-user-clock text-primary me-2"></i>Staff Productivity
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('housekeeping', 'staff_productivity', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('housekeeping', 'room_status', event)">
                                                        <i class="fas fa-door-open text-primary me-2"></i>Room Status Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('housekeeping', 'room_status', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Maintenance (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-maintenance">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-maintenance me-2">Maintenance</span>
                                            <i class="fas fa-tools ms-auto" style="color: var(--maintenance-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('maintenance', 'tracking_report', event)">
                                                        <i class="fas fa-clipboard-list text-primary me-2"></i>Maintenance Tracking Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('maintenance', 'tracking_report', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('maintenance', 'request_summary', event)">
                                                        <i class="fas fa-clipboard-list text-primary me-2"></i>Request Summary
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('maintenance', 'request_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('maintenance', 'response_time', event)">
                                                        <i class="fas fa-clock text-primary me-2"></i>Response Time Analysis
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('maintenance', 'response_time', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== POS & SERVICES REPORTS ==================== -->
                            <!-- Point of Sale (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-pos">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-pos me-2">Point of Sale</span>
                                            <i class="fas fa-cash-register ms-auto" style="color: var(--pos-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'daily_sales', event)">
                                                        <i class="fas fa-sun text-primary me-2"></i>Daily Sales Summary
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'daily_sales', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'sales_summary', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>POS Sales Summary
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'sales_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'menu_item_performance', event)">
                                                        <i class="fas fa-utensils text-primary me-2"></i>Menu Item Performance
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'menu_item_performance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'guest_spending_patterns', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Guest Spending Patterns
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'guest_spending_patterns', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'payment_methods', event)">
                                                        <i class="fas fa-credit-card text-primary me-2"></i>Payment Methods
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'payment_methods', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'hourly_sales', event)">
                                                        <i class="fas fa-clock text-primary me-2"></i>Hourly Sales Pattern
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'hourly_sales', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('pos', 'top_products', event)">
                                                        <i class="fas fa-crown text-primary me-2"></i>Top Selling Products
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('pos', 'top_products', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Services (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-service">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-service me-2">Services</span>
                                            <i class="fas fa-concierge-bell ms-auto" style="color: var(--service-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('service', 'request_analysis', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Service Request Analysis
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('service', 'request_analysis', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('service', 'usage', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Service Usage Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('service', 'usage', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('service', 'revenue', event)">
                                                        <i class="fas fa-money-bill-trend-up text-primary me-2"></i>Revenue by Service Category
                                                        <span class="amount-badge ms-2"><i class="fas fa-money-bill-wave money-icon"></i></span>
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('service', 'revenue', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== HUMAN RESOURCE REPORTS ==================== -->
                            <!-- HR (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-hr">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-hr me-2">Human Resource</span>
                                            <i class="fas fa-user-tie ms-auto" style="color: var(--hr-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('hr', 'staff_overview', event)">
                                                        <i class="fas fa-users text-primary me-2"></i>Staff Overview
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('hr', 'staff_overview', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('hr', 'staff_list', event)">
                                                        <i class="fas fa-users text-primary me-2"></i>Staff Directory
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('hr', 'staff_list', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('hr', 'leave_attendance', event)">
                                                        <i class="fas fa-calendar-alt text-primary me-2"></i>Leave & Attendance Report
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('hr', 'leave_attendance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('hr', 'attendance', event)">
                                                        <i class="fas fa-clock text-primary me-2"></i>Attendance Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('hr', 'attendance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('hr', 'department_stats', event)">
                                                        <i class="fas fa-building text-primary me-2"></i>Department Statistics
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('hr', 'department_stats', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== SURVEY & FEEDBACK REPORTS ==================== -->
                            <!-- Surveys (Expanded) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-survey">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-survey me-2">Surveys</span>
                                            <i class="fas fa-poll ms-auto" style="color: var(--survey-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('survey', 'satisfaction_dashboard', event)">
                                                        <i class="fas fa-chart-pie text-primary me-2"></i>Guest Satisfaction Dashboard
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('survey', 'satisfaction_dashboard', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('survey', 'feedback_summary', event)">
                                                        <i class="fas fa-comment-dots text-primary me-2"></i>Feedback Summary
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('survey', 'feedback_summary', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('survey', 'response_analysis', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Survey Response Analysis
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('survey', 'response_analysis', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('survey', 'satisfaction_trends', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Satisfaction Trends
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('survey', 'satisfaction_trends', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('survey', 'feedback_trends', event)">
                                                        <i class="fas fa-chart-line text-primary me-2"></i>Feedback Trends
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('survey', 'feedback_trends', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- ==================== CROSS-MODULE EXECUTIVE REPORTS ==================== -->
                            <!-- New Executive Reports Section -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-account">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-account me-2">Executive</span>
                                            <i class="fas fa-chart-line ms-auto" style="color: var(--account-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <!-- NEW: Daily Flash Report -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('executive', 'daily_flash', event)">
                                                        <i class="fas fa-bolt text-primary me-2"></i>Daily Flash Report
                                                        <span class="badge bg-danger ms-1">HOT</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('executive', 'daily_flash', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                                <small class="text-muted d-block">Combines front desk + accounting</small>
                                            </li>
                                            <!-- NEW: Monthly Performance Summary -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('executive', 'monthly_performance', event)">
                                                        <i class="fas fa-calendar-alt text-primary me-2"></i>Monthly Performance Summary
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('executive', 'monthly_performance', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                                <small class="text-muted d-block">All modules combined</small>
                                            </li>
                                            <!-- NEW: Top 10 Lists -->
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('executive', 'top_10_lists', event)">
                                                        <i class="fas fa-crown text-primary me-2"></i>Top 10 Lists
                                                        <span class="badge bg-success ms-1">NEW</span>
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('executive', 'top_10_lists', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                                <small class="text-muted d-block">Guests, Rooms, Menu Items</small>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Inventory (Unchanged) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-inventory">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-inventory me-2">Inventory</span>
                                            <i class="fas fa-boxes ms-auto" style="color: var(--inventory-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('inventory', 'stock_levels', event)">
                                                        <i class="fas fa-chart-bar text-primary me-2"></i>Stock Levels
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('inventory', 'stock_levels', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('inventory', 'reorder_report', event)">
                                                        <i class="fas fa-cart-plus text-primary me-2"></i>Reorder Report
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('inventory', 'reorder_report', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Documents (Unchanged) -->
                            <div class="col-xl-4 col-md-6 mb-4">
                                <div class="card module-card module-card-document">
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-3">
                                            <span class="module-badge badge-document me-2">Documents</span>
                                            <i class="fas fa-folder ms-auto" style="color: var(--document-color);"></i>
                                        </div>
                                        <ul class="report-list">
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('document', 'inventory', event)">
                                                        <i class="fas fa-folder-open text-primary me-2"></i>Document Inventory
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('document', 'inventory', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                            <li>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <a onclick="generateReport('document', 'access_log', event)">
                                                        <i class="fas fa-history text-primary me-2"></i>Access Log
                                                    </a>
                                                    <button class="btn btn-sm btn-outline-primary" onclick="generateReport('document', 'access_log', event)" title="Generate Report">
                                                        <i class="fas fa-download"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
        
    <!-- Print Layout Button -->
    <button class="btn btn-success print-layout-btn no-print" onclick="preparePrintLayout()">
        <i class="fas fa-print me-2"></i>Print Reports
    </button>

    <!-- Schedule Report Modal -->
    <div class="modal fade" id="scheduleReportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title"><i class="fas fa-clock me-2"></i>Schedule Report</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Schedule Name</label>
                        <input type="text" class="form-control" id="scheduleName" placeholder="e.g., Daily Revenue Report">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Frequency</label>
                        <select class="form-select" id="scheduleFrequency">
                            <option value="daily">Daily</option>
                            <option value="weekly">Weekly</option>
                            <option value="monthly">Monthly</option>
                            <option value="quarterly">Quarterly</option>
                        </select>
                    </div>
                    <div class="row mb-3">
                        <div class="col-6">
                            <label class="form-label fw-semibold">Time</label>
                            <input type="time" class="form-control" id="scheduleTime" value="08:00">
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-semibold">Start Date</label>
                            <input type="date" class="form-control" id="scheduleStartDate">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Format</label>
                        <select class="form-select" id="scheduleFormat">
                            <option value="pdf">PDF</option>
                            <option value="excel">Excel</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveSchedule()">Save Schedule</button>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta3/js/bootstrap-select.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts@3.41.0/dist/apexcharts.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

    <script>
    // Global variables
    let currentReportModule = '';
    let currentReportType = '';
    let performanceChart;
    let currentLayout = 'portrait';
    let refreshInterval = null;
    
    // Toastr configuration
    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: 'toast-top-right',
        timeOut: 3000,
        extendedTimeOut: 1000
    };

    // Initialize on page load
    $(document).ready(function() {
        console.log('Page loaded with PHP data:');
        console.log('Total Revenue: {{ $totalRevenue ?? 0 }}');
        console.log('Frontdesk Revenue: {{ $frontdeskRevenue ?? 0 }}');
        console.log('F&B Revenue: {{ $fnbRevenue ?? 0 }}');
        console.log('Services Revenue: {{ $servicesRevenue ?? 0 }}');
        
        initializeComponents();
        
        // Load real-time data once after a short delay
        setTimeout(() => {
            loadRealTimeData();
        }, 1000);
        
        startRealTimeUpdates();
        initializePerformanceChart();
        loadChartData('week');
        
        // Handle date range select change
        $('#dateRangeSelect').change(function() {
            if ($(this).val() === 'custom') {
                $('#customDateRange').show();
            } else {
                $('#customDateRange').hide();
            }
        });
    });
    
    // Initialize all components
    function initializeComponents() {
        // Initialize date picker
        flatpickr("#dateRangePicker", {
            mode: "range",
            dateFormat: "Y-m-d",
            defaultDate: [new Date(new Date().setDate(new Date().getDate() - 6)), new Date()]
        });
        
        // Initialize select pickers
        $('.selectpicker').selectpicker();
        
        // Setup search
        $('#reportSearch').on('input', function() {
            const searchTerm = $(this).val().toLowerCase();
            searchReports(searchTerm);
        });
        
        // Set default schedule date
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        $('#scheduleStartDate').val(tomorrow.toISOString().split('T')[0]);
    }
    
    // Set layout orientation
    function setLayout(layout) {
        currentLayout = layout;
        $('#selectedLayout').val(layout);
        
        // Update UI
        if (layout === 'portrait') {
            $('#portraitOption').addClass('selected');
            $('#landscapeOption').removeClass('selected');
        } else {
            $('#landscapeOption').addClass('selected');
            $('#portraitOption').removeClass('selected');
        }
    }
    
    // Initialize performance chart
    function initializePerformanceChart() {
        try {
            const options = {
                series: [{
                    name: 'Frontdesk (Check-ins)',
                    type: 'column',
                    data: []
                }, {
                    name: 'Food & Beverage',
                    type: 'column',
                    data: []
                }, {
                    name: 'Services',
                    type: 'column', 
                    data: []
                }],
                chart: {
                    height: 320,
                    type: 'line',
                    stacked: true,
                    toolbar: {
                        show: true
                    },
                    zoom: {
                        enabled: true
                    },
                    animations: {
                        enabled: true,
                        speed: 800
                    },
                    // Add error handling
                    events: {
                        error: function(err) {
                            console.error('Chart error:', err);
                        }
                    }
                },
                colors: ['#9b59b6', '#20c997', '#36b9cc'],
                stroke: {
                    width: [0, 0, 0],
                    curve: 'smooth'
                },
                plotOptions: {
                    bar: {
                        columnWidth: '60%',
                        borderRadius: 4
                    }
                },
                fill: {
                    opacity: [0.85, 0.85, 0.85],
                },
                labels: [],
                xaxis: {
                    type: 'category'
                },
                yaxis: {
                    title: {
                        text: 'Revenue (UGX)',
                    },
                    labels: {
                        formatter: function(val) {
                            if (val >= 1000000) {
                                return (val / 1000000).toFixed(1) + 'M';
                            } else if (val >= 1000) {
                                return (val / 1000).toFixed(0) + 'K';
                            } else if (val && val > 0) {
                                return val.toFixed(0);
                            }
                            return '0';
                        }
                    },
                    min: 0
                },
                tooltip: {
                    shared: true,
                    intersect: false,
                    y: {
                        formatter: function(val) {
                            if (!val && val !== 0) return 'UGX 0';
                            return 'UGX ' + val.toLocaleString();
                        }
                    }
                },
                legend: {
                    position: 'bottom',
                    horizontalAlign: 'center',
                    offsetY: 0
                },
                noData: {
                    text: 'Loading data...',
                    align: 'center',
                    verticalAlign: 'middle',
                    offsetX: 0,
                    offsetY: 0,
                    style: {
                        color: '#666',
                        fontSize: '14px',
                        fontFamily: 'Segoe UI'
                    }
                }
            };

            performanceChart = new ApexCharts(document.querySelector("#performanceChart"), options);
            performanceChart.render();
        } catch (error) {
            console.error('Error initializing chart:', error);
        }
    }
    
    // Load chart data function
    async function loadChartData(period) {
        try {
           const response = await fetch('/api/reports/performance-data?period=' + period + '&_=' + Date.now(),  {
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json'
                }
            });
            const data = await response.json();
            
            if (data.success) {
                performanceChart.updateOptions({
                    labels: data.labels
                });
                performanceChart.updateSeries([
                    { name: 'Frontdesk (Check-ins)', type: 'column', data: data.frontdesk_revenue },
                    { name: 'Food & Beverage', type: 'column', data: data.fnb_revenue },
                    { name: 'Services', type: 'column', data: data.services_revenue }
                ]);
                $('#chartNoData').hide();
            } else {
                $('#chartNoData').show();
            }
        } catch (error) {
            console.error('Chart data error:', error);
            $('#chartNoData').show();
        }
    }
    
    // Helper function to set empty chart data
    function setEmptyChartData() {
        const today = new Date();
        const labels = [];
        for (let i = 6; i >= 0; i--) {
            const d = new Date(today);
            d.setDate(d.getDate() - i);
            labels.push(d.toLocaleDateString('en-US', { weekday: 'short' }));
        }
        
        performanceChart.updateOptions({
            labels: labels
        });
        
        performanceChart.updateSeries([
            { name: 'Frontdesk (Check-ins)', type: 'column', data: [0, 0, 0, 0, 0, 0, 0] },
            { name: 'Food & Beverage', type: 'column', data: [0, 0, 0, 0, 0, 0, 0] },
            { name: 'Services', type: 'column', data: [0, 0, 0, 0, 0, 0, 0] }
        ]);
    }
    
    // Update chart period
    function updateChartPeriod(period) {
        $('.btn-group button').removeClass('active');
        $(event.target).addClass('active');
        loadChartData(period);
    }
    
    // Prepare print layout
    function preparePrintLayout() {
        // Set orientation for printing
        const style = document.createElement('style');
        style.innerHTML = `
            @page {
                size: ${currentLayout === 'portrait' ? 'A4 portrait' : 'A4 landscape'};
                margin: 1cm;
            }
        `;
        document.head.appendChild(style);
        window.print();
    }

    // ==================== REPORT GENERATION FUNCTIONS ====================

    // Generate report with auto-download
   // Generate report with auto-download
async function generateReport(module, reportType, event) {
    if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    
    const button = event.currentTarget;
    const originalHtml = button.innerHTML;
    button.innerHTML = '<span class="download-spinner"></span>';
    button.disabled = true;
    
    try {
        const format = $('input[name="format"]:checked').attr('id') || 'pdf';
        const dateRangeType = $('#dateRangeSelect').val();
        let dateFrom = null;
        let dateTo = null;
        
        if (dateRangeType === 'custom') {
            const customRange = $('#dateRangePicker').val();
            if (customRange) {
                const dates = customRange.split(' to ');
                dateFrom = dates[0];
                dateTo = dates[1] || dates[0];
            }
        }
        
        const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
        
        const response = await fetch('/reports/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify({
                module: module,
                report_type: reportType,
                date_range: dateRangeType,
                date_from: dateFrom,
                date_to: dateTo,
                format: format,
                layout: currentLayout
            })
        });
        
        const contentType = response.headers.get('content-type');
        
        if (contentType && contentType.includes('application/json')) {
            const data = await response.json();
            
            if (data.success && data.download_url) {
                // Try the original download URL
                const downloadResponse = await fetch(data.download_url, { method: 'HEAD' });
                
                if (downloadResponse.ok) {
                    // If file is accessible, use the original URL
                    const link = document.createElement('a');
                    link.href = data.download_url;
                    link.download = data.file_name || `report.${format}`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    toastr.success('Report generated successfully!');
                } else {
                    // If file not accessible, use temporary download
                    const filename = data.download_url.split('/').pop();
                    const tempUrl = `/reports/temp-download/${filename}`;
                    
                    const link = document.createElement('a');
                    link.href = tempUrl;
                    link.download = data.file_name || `report.${format}`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    toastr.success('Report downloaded via fallback method!');
                }
            } else {
                if (data.message && data.message.includes('No data')) {
                    toastr.warning('No data available for this report. Try a different date range.');
                } else {
                    toastr.error(data.message || 'Failed to generate report');
                }
            }
        } else {
            // If not JSON, it might be a file directly - get blob
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            
            const disposition = response.headers.get('content-disposition');
            let filename = `${module}_${reportType}.${format}`;
            if (disposition && disposition.includes('filename=')) {
                filename = disposition.split('filename=')[1].replace(/"/g, '');
            }
            
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            toastr.success('Download started!');
        }
    } catch (error) {
        console.error('Error generating report:', error);
        toastr.error('Failed to generate report. Please try again.');
    } finally {
        button.innerHTML = originalHtml;
        button.disabled = false;
    }
}
    // Alternative direct download (opens in new tab)
    function downloadReportDirect(module, reportType) {
        const dateRangeType = $('#dateRangeSelect').val();
        let dateFrom = '', dateTo = '';
        
        if (dateRangeType === 'custom') {
            const customRange = $('#dateRangePicker').val();
            if (customRange) {
                const dates = customRange.split(' to ');
                dateFrom = dates[0];
                dateTo = dates[1] || dates[0];
            }
        }
        
        const format = $('input[name="format"]:checked').attr('id') || 'pdf';
        const url = `/reports/download-direct?module=${module}&report_type=${reportType}&date_range=${dateRangeType}&date_from=${dateFrom}&date_to=${dateTo}&format=${format}&layout=${currentLayout}`;
        
        window.open(url, '_blank');
    }

    // Generate quick report
    async function generateQuickReport() {
        const button = document.getElementById('quickGenerateBtn');
        const progressDiv = document.getElementById('quickGenerateProgress');
        const originalHtml = button.innerHTML;
        
        button.style.display = 'none';
        progressDiv.style.display = 'block';
        
        try {
            const reportType = $('#quickReportType').val();
            const format = $('input[name="format"]:checked').attr('id') || 'pdf';
            
            const reportMap = {
                'daily_summary': { module: 'frontdesk', type: 'daily_operations' },
                'revenue_analysis': { module: 'account', type: 'revenue_summary' },
                'occupancy_report': { module: 'room', type: 'occupancy' },
                'financial_statement': { module: 'account', type: 'profit_loss' },
                'pos_summary': { module: 'pos', type: 'sales_summary' }
            };
            
            const mapped = reportMap[reportType] || { module: 'account', type: 'revenue_summary' };
            
            const dateRangeType = $('#dateRangeSelect').val();
            let dateFrom = null;
            let dateTo = null;
            
            if (dateRangeType === 'custom') {
                const customRange = $('#dateRangePicker').val();
                if (customRange) {
                    const dates = customRange.split(' to ');
                    dateFrom = dates[0];
                    dateTo = dates[1] || dates[0];
                }
            }
            
            const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            
            const response = await fetch('/reports/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({
                    module: mapped.module,
                    report_type: mapped.type,
                    date_range: dateRangeType,
                    date_from: dateFrom,
                    date_to: dateTo,
                    format: format,
                    layout: currentLayout,
                    quick: true
                })
            });
            
            const contentType = response.headers.get('content-type');
            
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();
                if (data.success && data.download_url) {
                    const link = document.createElement('a');
                    link.href = data.download_url;
                    link.download = data.file_name || `quick-report.${format}`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    toastr.success('Quick report ready!');
                } else {
                    toastr.error(data.message || 'Failed to generate report');
                }
            } else {
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.href = url;
                
                const disposition = response.headers.get('content-disposition');
                let filename = `quick-report.${format}`;
                if (disposition && disposition.includes('filename=')) {
                    filename = disposition.split('filename=')[1].replace(/"/g, '');
                }
                
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url);
                toastr.success('Download started!');
            }
        } catch (error) {
            console.error('Error:', error);
            toastr.error('Failed to generate quick report');
        } finally {
            button.style.display = 'block';
            progressDiv.style.display = 'none';
        }
    }
    
    // Load real-time KPI data
    async function loadRealTimeData() {
        try {
            const response = await fetch('/reports/refresh-kpi?_=' + Date.now(), {
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Cache-Control': 'no-cache, no-store, must-revalidate',
                    'Pragma': 'no-cache',
                    'Expires': '0'
                },
                cache: 'no-store'
            });
            
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            
            const data = await response.json();
            
            if (data.success) {
                console.log('Refresh KPI data:', data);
                
                $('#occupancyRate').text(data.occupancyRate + '%');
                $('#occupancyProgress').css('width', data.occupancyRate + '%');
                $('#roomsSold').text(data.roomsSold);
                $('#totalRooms').text(data.totalRooms);
                
                $('#currentGuests').text(data.currentGuests);
                $('#arrivalsCount').text(data.arrivalsCount);
                $('#departuresCount').text(data.departuresCount);
                
                // Update revenue breakdown with correct sources
                $('#totalRevenue').text('UGX ' + numberFormat(data.totalRevenue));
                $('#frontdeskRevenue').text('UGX ' + numberFormat(data.frontdeskRevenue));
                $('#servicesRevenue').text('UGX ' + numberFormat(data.servicesRevenue));
                $('#fnbRevenue').text('UGX ' + numberFormat(data.fnbRevenue));
                $('#vatAmount').text('UGX ' + numberFormat(data.vatAmount));
            }
        } catch (error) {
            console.error('KPI refresh failed:', error);
        }
    }
    
    // Number formatting helper
    function numberFormat(num) {
        if (!num && num !== 0) return '0';
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }
    
    // Start real-time updates
    function startRealTimeUpdates() {
        // Clear any existing interval
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        
        // Update every 30 seconds
        refreshInterval = setInterval(loadRealTimeData, 30000);
    }
    
    // Stop real-time updates (call when leaving page)
    function stopRealTimeUpdates() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
            refreshInterval = null;
        }
    }
    
    // Search reports
    function searchReports(term) {
        if (!term || term.length < 2) {
            $('.module-card').closest('.col-xl-4').show();
            return;
        }
        
        let visibleCount = 0;
        $('.module-card').each(function() {
            const card = $(this);
            const found = card.text().toLowerCase().includes(term.toLowerCase());
            card.closest('.col-xl-4').toggle(found);
            if (found) visibleCount++;
        });
        
        if (visibleCount === 0) {
            toastr.info('No reports match your search');
        }
    }
    
    function clearSearch() {
        $('#reportSearch').val('');
        searchReports('');
    }
    
    // Filter functions
    function applyFilters() {
        const module = $('#moduleFilter').val();
        if (module === 'all') {
            $('.module-card').closest('.col-xl-4').show();
        } else {
            $('.module-card').each(function() {
                const card = $(this);
                const showCard = card.hasClass(`module-card-${module}`);
                card.closest('.col-xl-4').toggle(showCard);
            });
        }
        toastr.success('Filters applied');
    }
    
    function clearFilters() {
        $('#dateRangeSelect').val('this_week');
        $('#customDateRange').hide();
        $('#moduleFilter').val('all').selectpicker('refresh');
        $('#reportSearch').val('');
        $('.module-card').closest('.col-xl-4').show();
        toastr.info('Filters cleared');
    }
    
    // Schedule report
    function scheduleReport(module, reportType, event) {
        if (event) {
            event.preventDefault();
            event.stopPropagation();
        }
        
        currentReportModule = module;
        currentReportType = reportType;
        
        const reportName = $(event.currentTarget).closest('li').find('a').text().trim() || `${module} - ${reportType}`;
        $('#scheduleName').val(reportName);
        
        const modal = new bootstrap.Modal(document.getElementById('scheduleReportModal'));
        modal.show();
    }
    
    // Save schedule
    async function saveSchedule() {
        const data = {
            name: $('#scheduleName').val(),
            module: currentReportModule,
            report_type: currentReportType,
            frequency: $('#scheduleFrequency').val(),
            time: $('#scheduleTime').val(),
            start_date: $('#scheduleStartDate').val(),
            format: $('#scheduleFormat').val(),
            layout: currentLayout
        };
        
        if (!data.name) {
            toastr.error('Please enter a schedule name');
            return;
        }
        
        try {
            const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            
            const response = await fetch('/reports/schedule', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken,
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(data)
            });
            
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            
            const result = await response.json();
            
            if (result.success) {
                bootstrap.Modal.getInstance(document.getElementById('scheduleReportModal')).hide();
                toastr.success('Report scheduled successfully!');
                $('#scheduleName').val('');
            } else {
                toastr.error(result.message || 'Scheduling failed');
            }
        } catch (error) {
            console.error('Error:', error);
            toastr.error('Scheduling failed');
        }
    }

    // Clean up on page unload
    window.addEventListener('beforeunload', function() {
        stopRealTimeUpdates();
    });
    </script>
    
<script src="{{ asset('js/theme-applier.js') }}"></script>
</body> 
</html>
