<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Reports & Analytics - Granny Restaurant Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">
    <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/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="manager-styles.css">

    <title>Reports & Analytics - Granny Restaurant</title>

    <style>
        .main-content {
            padding: 30px 30px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .page-header h1 {
            color: #1e3c72;
            font-size: 28px;
        }



        .controls {
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
            align-items: flex-end;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .control-group label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
        }

        .control-group input,
        .control-group select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(42, 82, 152, 0.3);
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }

        .stat-title {
            font-size: 12px;
            color: #666;
            text-transform: uppercase;
            margin-bottom: 10px;
            font-weight: 600;
            letter-spacing: 0.5px;
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            color: #1e3c72;
            margin-bottom: 5px;
        }

        .stat-change {
            font-size: 12px;
            color: #28a745;
        }

        /* Reports Grid */
        .reports-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .report-card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .report-header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            padding: 20px;
            font-weight: 600;
        }

        .report-body {
            padding: 20px;
            overflow-x: auto;
        }

        .report-table {
            width: 100%;
            min-width: 500px;
        }

        .report-table thead {
            background: #f8f9fa;
            border-bottom: 2px solid #ddd;
        }

        .report-table th {
            padding: 10px;
            text-align: left;
            font-weight: 600;
            font-size: 12px;
            color: #333;
            text-transform: uppercase;
            white-space: nowrap;
        }

        .report-table td {
            padding: 10px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
            white-space: nowrap;
        }

        .report-table tbody tr:hover {
            background: #f8f9fa;
        }

        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 32px;
            margin-bottom: 10px;
            opacity: 0.5;
        }

        .export-btn {
            background: #6c757d;
            color: white;
        }

        .export-btn:hover {
            background: #5a6268;
        }

        /* Responsive Grids */
        @media (max-width: 1440px) and (min-width: 1025px) {
            .stats-grid {
                grid-template-columns: repeat(3, 1fr);
            }

            .reports-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 1024px) and (min-width: 769px) {
            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
            }

            .reports-grid {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .control-group input,
            .control-group select {
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: 1fr;
            }

            .reports-grid {
                grid-template-columns: 1fr;
            }

            .report-body {
                padding: 15px;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .report-table {
                font-size: 12px;
                min-width: 100%;
            }

            .report-table th,
            .report-table td {
                padding: 8px 6px;
                white-space: nowrap;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .page-header h1 {
                font-size: 22px;
            }

            .main-content {
                padding: 15px 15px;
            }

            .container {
                padding: 0;
            }
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }

        .chart-container {
            height: 300px;
            margin-top: 20px;
        }

        @media (max-width: 480px) {
            .page-header {
                padding: 15px;
            }

            .page-header h1 {
                font-size: 18px;
            }

            .controls {
                padding: 15px;
                gap: 10px;
            }

            .btn {
                font-size: 12px;
                padding: 8px 12px;
            }

            .stat-value {
                font-size: 24px;
            }

            .report-body {
                padding: 10px;
            }

            .report-table th,
            .report-table td {
                padding: 6px 4px;
                font-size: 11px;
            }

            .report-header {
                padding: 15px;
                font-size: 14px;
            }
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>
        <div class="main-content">
            <div class="container">
                <div class="page-header">
            <h1><i class="fas fa-chart-bar"></i> Reports & Analytics</h1>
        </div>

        <!-- Controls -->
        <div class="controls">
            <div class="control-group">
                <label>Start Date</label>
                <input type="date" id="startDate" onchange="loadReports()">
            </div>

            <div class="control-group">
                <label>End Date</label>
                <input type="date" id="endDate" onchange="loadReports()">
            </div>

            <div class="control-group">
                <label>&nbsp;</label>
                <button class="btn btn-primary" onclick="loadReports()">
                    <i class="fas fa-sync"></i> Load Reports
                </button>
                <button class="btn export-btn" onclick="exportReports()">
                    <i class="fas fa-download"></i> Export
                </button>
            </div>
        </div>

        <!-- Statistics -->
        <div class="stats-grid" id="statsContainer">
            <div class="loading">
                <i class="fas fa-spinner fa-spin"></i> Loading...
            </div>
        </div>

        <!-- Reports -->
        <div class="reports-grid" id="reportsContainer">
            <div class="loading">
                <i class="fas fa-spinner fa-spin"></i> Loading reports...
            </div>
        </div>            </div>
        </div>    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        $(document).ready(function() {
            checkAuthentication();
            setDateRange();
            loadReports();
        });

        function checkAuthentication() {
            if (!localStorage.getItem('manager_id')) {
                window.location.href = 'login.php';
            }
        }

        function setDateRange() {
            const today = new Date();
            const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

            $('#endDate').val(today.toISOString().split('T')[0]);
            $('#startDate').val(startOfMonth.toISOString().split('T')[0]);
        }

        function loadReports() {
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();

            // Load stats
            loadDailySummary();
            loadRevenueReport(startDate, endDate);
            loadPaymentReport(startDate, endDate);
            loadServerPerformance(startDate, endDate);
            loadTableUtilization();
        }

        function loadDailySummary() {
            const today = new Date().toISOString().split('T')[0];
            const managerId = localStorage.getItem('manager_id');

            $.ajax({
                url: `../backend/manager_reports_api.php?action=daily_summary&date=${today}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayStats(response.data);
                    }
                }
            });
        }

        function displayStats(data) {
            const html = `
                <div class="stat-card success">
                    <div class="stat-title">Today's Revenue</div>
                    <div class="stat-value">₹${parseFloat(data.total_revenue).toFixed(2)}</div>
                    <div class="stat-change">From ${data.total_bills} bills</div>
                </div>

                <div class="stat-card info">
                    <div class="stat-title">Tables Served</div>
                    <div class="stat-value">${data.tables_served}</div>
                    <div class="stat-change">Today</div>
                </div>

                <div class="stat-card warning">
                    <div class="stat-title">Average Bill</div>
                    <div class="stat-value">₹${parseFloat(data.average_bill).toFixed(2)}</div>
                    <div class="stat-change">${data.total_items} items sold</div>
                </div>

                <div class="stat-card">
                    <div class="stat-title">Payment Methods</div>
                    <div class="stat-value">${data.payment_breakdown.length}</div>
                    <div class="stat-change">Different methods used</div>
                </div>
            `;

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

        function loadRevenueReport(startDate, endDate) {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_reports_api.php?action=revenue_report&start_date=${startDate}&end_date=${endDate}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayRevenueReport(response.data);
                    }
                }
            });
        }

        function displayRevenueReport(data) {
            let tableHtml = '<table class="report-table"><thead><tr><th>Date</th><th>Revenue</th><th>Bills</th><th>Tables</th><th>Avg Bill</th></tr></thead><tbody>';

            data.daily_data.forEach(row => {
                tableHtml += `
                    <tr>
                        <td>${new Date(row.date).toLocaleDateString()}</td>
                        <td>₹${parseFloat(row.revenue).toFixed(2)}</td>
                        <td>${row.bills}</td>
                        <td>${row.tables}</td>
                        <td>₹${parseFloat(row.avg_bill).toFixed(2)}</td>
                    </tr>
                `;
            });

            tableHtml += `</tbody></table>
                <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee;"+>
                    <strong>Total Revenue:</strong> ₹${parseFloat(data.total_revenue).toFixed(2)}
                </div>
            `;

            addReportCard('Revenue Report', tableHtml);
        }

        function loadPaymentReport(startDate, endDate) {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_reports_api.php?action=payment_methods&start_date=${startDate}&end_date=${endDate}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayPaymentReport(response.data);
                    }
                }
            });
        }

        function displayPaymentReport(data) {
            let tableHtml = '<table class="report-table"><thead><tr><th>Payment Method</th><th>Count</th><th>Amount</th><th>Status</th></tr></thead><tbody>';

            data.forEach(row => {
                tableHtml += `
                    <tr>
                        <td>${row.payment_method || 'Pending'}</td>
                        <td>${row.transaction_count}</td>
                        <td>₹${parseFloat(row.total_amount).toFixed(2)}</td>
                        <td>${row.completed} completed</td>
                    </tr>
                `;
            });

            tableHtml += '</tbody></table>';

            addReportCard('Payment Methods', tableHtml);
        }

        function loadServerPerformance(startDate, endDate) {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_reports_api.php?action=server_performance&start_date=${startDate}&end_date=${endDate}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayServerPerformance(response.data);
                    }
                }
            });
        }

        function displayServerPerformance(data) {
            let tableHtml = '<table class="report-table"><thead><tr><th>Server</th><th>Tables</th><th>Rating</th><th>Revenue</th></tr></thead><tbody>';

            data.forEach(server => {
                tableHtml += `
                    <tr>
                        <td>${server.name}</td>
                        <td>${server.tables_served}</td>
                        <td>${parseFloat(server.avg_rating).toFixed(1)}</td>
                        <td>₹${parseFloat(server.total_revenue_generated || 0).toFixed(2)}</td>
                    </tr>
                `;
            });

            tableHtml += '</tbody></table>';

            addReportCard('Server Performance', tableHtml);
        }

        function loadTableUtilization() {
            const today = new Date().toISOString().split('T')[0];
            const managerId = localStorage.getItem('manager_id');

            $.ajax({
                url: `../backend/manager_reports_api.php?action=table_utilization&date=${today}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        displayTableUtilization(response.data);
                    }
                }
            });
        }

        function displayTableUtilization(data) {
            let tableHtml = '<table class="report-table"><thead><tr><th>Table</th><th>Capacity</th><th>Times Used</th><th>Completed</th></tr></thead><tbody>';

            data.forEach(table => {
                tableHtml += `
                    <tr>
                        <td>T-${table.table_number}</td>
                        <td>${table.base_capacity}</td>
                        <td>${table.times_used || 0}</td>
                        <td>${table.completed_usage || 0}</td>
                    </tr>
                `;
            });

            tableHtml += '</tbody></table>';

            addReportCard('Table Utilization', tableHtml);
        }

        function addReportCard(title, html) {
            const reportHtml = `
                <div class="report-card">
                    <div class="report-header">
                        <i class="fas fa-chart-bar"></i> ${title}
                    </div>
                    <div class="report-body">
                        ${html}
                    </div>
                </div>
            `;

            $('#reportsContainer').append(reportHtml);
        }

        function exportReports() {
            const startDate = $('#startDate').val();
            const endDate = $('#endDate').val();

            Swal.fire({
                title: 'Export Format',
                input: 'select',
                inputOptions: {
                    'csv': 'CSV File',
                    'pdf': 'PDF Document'
                },
                showCancelButton: true,
                confirmButtonText: 'Export'
            }).then((result) => {
                if (result.isConfirmed) {
                    Swal.fire('Success', `Report will be exported as ${result.value.toUpperCase()}`, 'success');
                    // Implement actual export functionality
                }
            });
        }

        // Refresh reports every 5 minutes
        setInterval(loadReports, 300000);
    </script>

    <!-- Manager Sidebar Script -->
    <script src="manager-sidebar.js"></script>
</body>

</html>
