<?php
// reports.php
session_start();
require_once 'config/db_config.php'; // expects $pdo (PDO)

// ---- Initialize $script early to avoid undefined variable ----
$script = '';

// ---- Auth (admins and branch users) ----
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role'])) {
    header("Location: login.php");
    exit();
}

// ---- CSRF token ----
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];

// ---- Helpers ----
function h(string $v): string { return htmlspecialchars($v, ENT_QUOTES, 'UTF-8'); }

// ---- Determine filters ----
$selected_branch_id = $_SESSION['role'] === 'branch' ? $_SESSION['branch_id'] : ($_GET['branch_id'] ?? 'all');
$start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$status = $_GET['status'] ?? 'all';
$gst_filter = $_GET['gst_filter'] ?? 'all';

// Always exclude third-party branches
$where_clause = ["o.order_date BETWEEN :start_date AND :end_date", "b.third_party = 0"];
$params = ['start_date' => $start_date . ' 00:00:00', 'end_date' => $end_date . ' 23:59:59'];

if ($selected_branch_id !== 'all' && is_numeric($selected_branch_id)) {
    $where_clause[] = 'o.branch_id = :branch_id';
    $params['branch_id'] = $selected_branch_id;
}
if ($status !== 'all' && in_array($status, ['pending', 'processing', 'completed', 'cancelled'])) {
    $where_clause[] = 'o.status = :status';
    $params['status'] = $status;
}
if ($gst_filter !== 'all') {
    $where_clause[] = 'o.is_gst_active = :is_gst_active';
    $params['is_gst_active'] = $gst_filter === 'on' ? 1 : 0;
}

// ---- Handle CSV and JSON export ----
if (isset($_GET['export'])) {
    try {
        $query = "
            SELECT 
                o.order_id, 
                o.customer_name, 
                o.customer_contact, 
                o.order_date, 
                o.total_amount,
                o.taxable_amount,
                o.cgst_rate,
                o.sgst_rate,
                o.cgst_amount,
                o.sgst_amount,
                o.is_gst_active,
                o.status, 
                b.branch_name
            FROM orders o
            JOIN branches b ON o.branch_id = b.branch_id
            " . (!empty($where_clause) ? "WHERE " . implode(' AND ', $where_clause) : "") . "
            GROUP BY o.order_id
            ORDER BY o.order_date DESC
        ";
        $stmt = $pdo->prepare($query);
        $stmt->execute($params);
        $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Clear any previous output
        if (ob_get_length()) {
            ob_clean();
        }

        if ($_GET['export'] === 'excel') {
            // CSV Export with GST details
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment;filename="orders_export_' . date('Ymd_His') . '.csv"');
            header('Cache-Control: max-age=0');
            header('Pragma: no-cache');

            $output = fopen('php://output', 'w');
            fputs($output, "\xEF\xBB\xBF"); // UTF-8 BOM for Excel
            
            // Updated CSV headers with GST details
            fputcsv($output, [
                'S.No', 
                'Customer Name', 
                'Customer Contact', 
                'Order Date', 
                'Taxable Amount',
                'CGST Rate',
                'SGST Rate',
                'CGST Amount',
                'SGST Amount',
                'Total GST',
                'Total Amount', 
                'Status', 
                'GST Status',
                'Branch'
            ]);

            foreach ($orders as $index => $order) {
                $total_gst = $order['cgst_amount'] + $order['sgst_amount'];
                fputcsv($output, [
                    $index + 1,
                    $order['customer_name'] ?: 'Walk-in Customer',
                    $order['customer_contact'],
                    date('d M Y, H:i', strtotime($order['order_date'])),
                    number_format($order['taxable_amount'], 2),
                    $order['cgst_rate'] . '%',
                    $order['sgst_rate'] . '%',
                    number_format($order['cgst_amount'], 2),
                    number_format($order['sgst_amount'], 2),
                    number_format($total_gst, 2),
                    number_format($order['total_amount'], 2),
                    ucfirst($order['status']),
                    $order['is_gst_active'] ? 'GST On' : 'GST Off',
                    $order['branch_name']
                ]);
            }
            fclose($output);
            exit();
        } elseif ($_GET['export'] === 'json') {
            // JSON Export with GST details
            header('Content-Type: application/json; charset=utf-8');
            header('Content-Disposition: attachment;filename="orders_export_' . date('Ymd_His') . '.json"');
            header('Cache-Control: max-age=0');
            header('Pragma: no-cache');

            $json_data = [];
            foreach ($orders as $index => $order) {
                $total_gst = $order['cgst_amount'] + $order['sgst_amount'];
                $json_data[] = [
                    'S.No' => $index + 1,
                    'Customer Name' => $order['customer_name'] ?: 'Walk-in Customer',
                    'Customer Contact' => $order['customer_contact'],
                    'Order Date' => date('d M Y, H:i', strtotime($order['order_date'])),
                    'Taxable Amount' => number_format($order['taxable_amount'], 2),
                    'CGST Rate' => $order['cgst_rate'] . '%',
                    'SGST Rate' => $order['sgst_rate'] . '%',
                    'CGST Amount' => number_format($order['cgst_amount'], 2),
                    'SGST Amount' => number_format($order['sgst_amount'], 2),
                    'Total GST' => number_format($total_gst, 2),
                    'Total Amount' => number_format($order['total_amount'], 2),
                    'Status' => ucfirst($order['status']),
                    'GST Status' => $order['is_gst_active'] ? 'GST On' : 'GST Off',
                    'Branch' => $order['branch_name']
                ];
            }
            echo json_encode($json_data, JSON_PRETTY_PRINT);
            exit();
        }
    } catch (Exception $e) {
        $_SESSION['error'] = "Error exporting: " . h($e->getMessage());
        header("Location: reports.php");
        exit();
    }
}

// ---- Fetch branches for dropdown (excluding third-party) ----
try {
    $stmt = $pdo->query("SELECT branch_id, branch_name FROM branches WHERE third_party = 0 ORDER BY branch_name");
    $branches = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching branches: " . h($e->getMessage());
    $branches = [];
}

// ---- Fetch GST Statistics (excluding third-party branches) ----
try {
    // Total GST Collected
    $gst_where = array_merge($where_clause, ["o.is_gst_active = 1"]);
    $query = "
        SELECT 
            SUM(o.cgst_amount) as total_cgst,
            SUM(o.sgst_amount) as total_sgst,
            SUM(o.cgst_amount + o.sgst_amount) as total_gst,
            SUM(o.taxable_amount) as total_taxable_amount,
            SUM(o.total_amount) as total_gst_revenue
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($gst_where) ? "WHERE " . implode(' AND ', $gst_where) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $gst_stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $total_cgst = $gst_stats['total_cgst'] ?? 0;
    $total_sgst = $gst_stats['total_sgst'] ?? 0;
    $total_gst = $gst_stats['total_gst'] ?? 0;
    $total_taxable_amount = $gst_stats['total_taxable_amount'] ?? 0;
    $total_gst_revenue = $gst_stats['total_gst_revenue'] ?? 0;

    // Non-GST Revenue
    $non_gst_where = array_merge($where_clause, ["o.is_gst_active = 0"]);
    $query = "
        SELECT SUM(o.total_amount) as non_gst_revenue 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($non_gst_where) ? " WHERE " . implode(' AND ', $non_gst_where) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $non_gst_revenue = $stmt->fetch(PDO::FETCH_ASSOC)['non_gst_revenue'] ?? 0;

    // GST Orders Count
    $gst_orders_where = array_merge($where_clause, ["o.is_gst_active = 1"]);
    $query = "
        SELECT COUNT(DISTINCT o.order_id) as gst_orders 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($gst_orders_where) ? " WHERE " . implode(' AND ', $gst_orders_where) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $gst_orders = $stmt->fetch(PDO::FETCH_ASSOC)['gst_orders'] ?? 0;

    // Non-GST Orders Count
    $non_gst_orders_where = array_merge($where_clause, ["o.is_gst_active = 0"]);
    $query = "
        SELECT COUNT(DISTINCT o.order_id) as non_gst_orders 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($non_gst_orders_where) ? " WHERE " . implode(' AND ', $non_gst_orders_where) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $non_gst_orders = $stmt->fetch(PDO::FETCH_ASSOC)['non_gst_orders'] ?? 0;

} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching GST statistics: " . h($e->getMessage());
    $total_cgst = $total_sgst = $total_gst = $total_taxable_amount = $total_gst_revenue = $non_gst_revenue = $gst_orders = $non_gst_orders = 0;
}

// ---- Fetch statistics (excluding third-party branches) ----
try {
    // Total Orders
    $query = "
        SELECT COUNT(DISTINCT o.order_id) as total_orders 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? " WHERE " . implode(' AND ', $where_clause) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $total_orders = $stmt->fetch()['total_orders'] ?? 0;

    // Total Revenue
    $query = "
        SELECT SUM(o.total_amount) as total_revenue 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? " WHERE " . implode(' AND ', $where_clause) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $total_revenue = $stmt->fetch()['total_revenue'] ?? 0;

    // Today's Revenue
    $today_where = array_merge($where_clause, ["DATE(o.order_date) = CURDATE()"]);
    $today_params = $params;
    $query = "
        SELECT SUM(o.total_amount) as today_revenue 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($today_where) ? " WHERE " . implode(' AND ', $today_where) : "");
    $stmt = $pdo->prepare($query);
    $stmt->execute($today_params);
    $today_revenue = $stmt->fetch()['today_revenue'] ?? 0;

    // Total Food Items (excluding third-party branches)
    if ($_SESSION['role'] === 'branch') {
        $query = "
            SELECT COUNT(*) as total_foods 
            FROM foods f
            JOIN branch_foods bf ON f.food_id = bf.food_id
            JOIN branches b ON bf.branch_id = b.branch_id
            WHERE bf.branch_id = :branch_id AND b.third_party = 0
        ";
        $food_params = ['branch_id' => $_SESSION['branch_id']];
    } else {
        $query = "
            SELECT COUNT(*) as total_foods 
            FROM foods f
            JOIN branch_foods bf ON f.food_id = bf.food_id
            JOIN branches b ON bf.branch_id = b.branch_id
            WHERE b.third_party = 0
        ";
        $food_params = [];
    }
    $stmt = $pdo->prepare($query);
    $stmt->execute($food_params);
    $total_foods = $stmt->fetch()['total_foods'] ?? 0;

    // Pending Orders
    $query = "
        SELECT COUNT(DISTINCT o.order_id) as pending_orders 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? " WHERE " . implode(' AND ', $where_clause) . " AND o.status = 'pending'" : " WHERE o.status = 'pending' AND b.third_party = 0");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $pending_orders = $stmt->fetch()['pending_orders'] ?? 0;

    // Total Categories (excluding third-party branches)
    if ($_SESSION['role'] === 'branch') {
        $query = "
            SELECT COUNT(*) as total_categories 
            FROM food_categories fc
            JOIN branch_categories bc ON fc.category_id = bc.category_id
            JOIN branches b ON bc.branch_id = b.branch_id
            WHERE bc.branch_id = :branch_id AND b.third_party = 0
        ";
        $cat_params = ['branch_id' => $_SESSION['branch_id']];
    } else {
        $query = "
            SELECT COUNT(*) as total_categories 
            FROM food_categories fc
            JOIN branch_categories bc ON fc.category_id = bc.category_id
            JOIN branches b ON bc.branch_id = b.branch_id
            WHERE b.third_party = 0
        ";
        $cat_params = [];
    }
    $stmt = $pdo->prepare($query);
    $stmt->execute($cat_params);
    $total_categories = $stmt->fetch()['total_categories'] ?? 0;

    // Last 30 days orders
    $query = "
        SELECT COUNT(DISTINCT o.order_id) as last_30_days_orders 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? " WHERE " . implode(' AND ', $where_clause) . " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)" :
                                   " WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND b.third_party = 0");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $last_30_days_orders = $stmt->fetch()['last_30_days_orders'] ?? 0;

    // Last 30 days revenue
    $query = "
        SELECT SUM(o.total_amount) as last_30_days_revenue 
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? " WHERE " . implode(' AND ', $where_clause) . " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)" :
                                   " WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND b.third_party = 0");
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $last_30_days_revenue = $stmt->fetch()['last_30_days_revenue'] ?? 0;

} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching statistics: " . h($e->getMessage());
    $total_orders = 0;
    $total_revenue = 0;
    $today_revenue = 0;
    $total_foods = 0;
    $pending_orders = 0;
    $total_categories = 0;
    $last_30_days_orders = 0;
    $last_30_days_revenue = 0;
}

// ---- Fetch orders with GST details (excluding third-party branches) ----
try {
    $query = "
        SELECT 
            o.order_id, 
            o.customer_name, 
            o.customer_contact, 
            o.order_date, 
            o.total_amount,
            o.taxable_amount,
            o.cgst_rate,
            o.sgst_rate,
            o.cgst_amount,
            o.sgst_amount,
            o.is_gst_active,
            o.status, 
            b.branch_name
        FROM orders o
        JOIN branches b ON o.branch_id = b.branch_id
        " . (!empty($where_clause) ? "WHERE " . implode(' AND ', $where_clause) : "") . "
        GROUP BY o.order_id
        ORDER BY o.order_date DESC, o.order_id DESC
    ";
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching orders: " . h($e->getMessage());
    $orders = [];
}

// ---- Fetch order items for modals ----
$order_items = [];
try {
    foreach ($orders as $order) {
        $stmt = $pdo->prepare("
            SELECT oi.item_id, oi.quantity, oi.price, oi.subtotal, f.food_name, f.image_url
            FROM order_items oi
            JOIN foods f ON oi.food_id = f.food_id
            WHERE oi.order_id = :order_id
        ");
        $stmt->execute(['order_id' => $order['order_id']]);
        $order_items[$order['order_id']] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (PDOException $e) {
    $_SESSION['error'] = "Error fetching order items: " . h($e->getMessage());
}

// ---- DataTable init (prevent reinitialization) ----
$script .= '
<script>
document.addEventListener("DOMContentLoaded", function () {
    try {
        if (!$.fn.DataTable.isDataTable("#ordersTable")) {
            let table = new DataTable("#ordersTable", {
                responsive: true,
                pageLength: 10,
                language: {
                    search: "_INPUT_",
                    searchPlaceholder: "Search orders..."
                },
                columnDefs: [
                    { orderable: false, targets: [0, 2, 7, 8] } // checkbox, customer, status, actions
                ]
            });
        }
        const selectAllCheckbox = document.getElementById("selectAll");
        selectAllCheckbox.addEventListener("change", function() {
            const checkboxes = document.querySelectorAll("input[name=\"order_ids[]\"]");
            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
        });
    } catch (e) {
        console.error("DataTable init error:", e);
    }
});
</script>';

?>

<?php include './partials/layouts/layoutTop.php'; ?>

<style>
.important-text-1 { color: rgba(255, 85, 139, 0.9); }
.important-text-2 { color: rgba(27, 209, 175, 0.9); }
.important-text-3 { color: rgba(255, 153, 63, 0.9); }
.important-text-4 { color: rgba(16, 120, 211, 0.9); }
.important-text-5 { color: rgba(147, 51, 234, 0.9); }
.small-card { min-height: 120px; }
.small-table { font-size: 0.85rem; }
.small-table th, .small-table td { padding: 8px 12px; }
.small-icon { font-size: 1.2rem; }
.small-badge { font-size: 0.75rem; padding: 4px 8px; }
.compact-header { padding: 12px 16px; }
.compact-body { padding: 12px 16px; }
.gst-badge { font-size: 0.75rem; padding: 4px 8px; }
.taxable-amount { color: #198754; font-weight: 600; }
.gst-amount { color: #dc3545; font-weight: 600; }
.gst-rate-badge { font-size: 0.7rem; padding: 2px 6px; }
.stat-card { transition: all 0.3s ease; }
.stat-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }

@media (max-width: 768px) {
    .small-card { min-height: 100px; }
    .compact-body { padding: 8px 12px; }
    .small-table { font-size: 0.8rem; }
    .small-table th, .small-table td { padding: 6px 8px; }
}
</style>

<div class="dashboard-main-body">
    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 mb-16">
        <h6 class="fw-semibold mb-0 text-lg">Reports & Analytics</h6>
        <ul class="d-flex align-items-center gap-1 small">
            <li class="fw-medium">
                <a href="index.php" class="d-flex align-items-center gap-1 hover-text-primary text-sm">
                    <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-md"></iconify-icon>
                    Dashboard
                </a>
            </li>
            <li>-</li>
            <li class="fw-medium text-sm">Reports</li>
        </ul>
    </div>

    <!-- Filters -->
    <div class="card h-100 mb-24">
        <div class="card-header compact-header">
            <h6 class="section-title fw-semibold mb-0 text-md">Filter Reports</h6>
        </div>
        <div class="card-body compact-body">
            <div class="d-flex flex-wrap gap-3 align-items-center">
                <form method="GET" action="reports.php" class="d-flex gap-3 flex-wrap w-100">
                    <?php if ($_SESSION['role'] === 'admin'): ?>
                        <div class="flex-grow-1">
                            <select class="form-select form-select-sm" name="branch_id" onchange="this.form.submit()" style="font-size: 0.875rem; border-radius: 0.375rem;">
                                <option value="all" <?= $selected_branch_id === 'all' ? 'selected' : ''; ?>>All Branches</option>
                                <?php foreach ($branches as $branch): ?>
                                    <option value="<?= h($branch['branch_id']); ?>" <?= $selected_branch_id == $branch['branch_id'] ? 'selected' : ''; ?>>
                                        <?= h($branch['branch_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    <?php endif; ?>
                    <div class="flex-grow-1">
                        <input type="date" class="form-control form-control-sm" name="start_date" value="<?= h($start_date); ?>" onchange="this.form.submit()" style="font-size: 0.875rem; border-radius: 0.375rem;">
                    </div>
                    <div class="flex-grow-1">
                        <input type="date" class="form-control form-control-sm" name="end_date" value="<?= h($end_date); ?>" onchange="this.form.submit()" style="font-size: 0.875rem; border-radius: 0.375rem;">
                    </div>
                    <div class="flex-grow-1">
                        <select class="form-select form-select-sm" name="status" onchange="this.form.submit()" style="font-size: 0.875rem; border-radius: 0.375rem;">
                            <option value="all" <?= $status === 'all' ? 'selected' : ''; ?>>All Statuses</option>
                            <option value="pending" <?= $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                            <option value="processing" <?= $status === 'processing' ? 'selected' : ''; ?>>Processing</option>
                            <option value="completed" <?= $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                            <option value="cancelled" <?= $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</order>
                        </select>
                    </div>
                    <div class="flex-grow-1">
                        <select class="form-select form-select-sm" name="gst_filter" onchange="this.form.submit()" style="font-size: 0.875rem; border-radius: 0.375rem;">
                            <option value="all" <?= $gst_filter === 'all' ? 'selected' : ''; ?>>All GST Status</option>
                            <option value="on" <?= $gst_filter === 'on' ? 'selected' : ''; ?>>GST On</option>
                            <option value="off" <?= $gst_filter === 'off' ? 'selected' : ''; ?>>GST Off</option>
                        </select>
                    </div>
                    <div class="flex-grow-1">
                        <div class="dropdown">
                            <button class="btn btn-primary btn-sm w-100 d-flex align-items-center gap-1 dropdown-toggle" type="button" id="exportDropdown" data-bs-toggle="dropdown" aria-expanded="false" style="font-size: 0.875rem; border-radius: 0.375rem;">
                                <iconify-icon icon="mdi:file-export" class="icon"></iconify-icon>
                                Export
                            </button>
                            <ul class="dropdown-menu" aria-labelledby="exportDropdown">
                                <li><button type="submit" name="export" value="excel" class="dropdown-item">Export to Excel</button></li>
                                <li><button type="submit" name="export" value="json" class="dropdown-item">Export to JSON</button></li>
                            </ul>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if (!empty($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">
            <?= h($_SESSION['success']); unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    <?php if (!empty($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show mb-24" role="alert">
            <?= h($_SESSION['error']); unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['updated'])): ?>
        <div class="alert alert-success alert-dismissible fade show mb-24" role="alert">
            Order updated successfully!
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <!-- GST Breakdown Cards -->
    <div class="row row-cols-xxxl-4 row-cols-lg-3 row-cols-sm-2 row-cols-1 gy-3 mb-24">
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-1 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Total GST Collected</p>
                            <h6 class="mb-0 text-lg important-text-1">₹<?php echo number_format($total_gst, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-danger rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:tax" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0 d-flex align-items-center gap-1">
                        <span class="d-inline-flex align-items-center gap-1 text-success-main">
                            CGST: ₹<?php echo number_format($total_cgst, 2); ?>
                        </span>
                        |
                        <span class="text-info-main">
                            SGST: ₹<?php echo number_format($total_sgst, 2); ?>
                        </span>
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-2 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Taxable Amount</p>
                            <h6 class="mb-0 text-lg important-text-2">₹<?php echo number_format($total_taxable_amount, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-success rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:cash" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0">
                        Base amount before GST
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-3 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">GST Orders</p>
                            <h6 class="mb-0 text-lg important-text-3"><?php echo number_format($gst_orders); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-warning rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:receipt" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0">
                        <?php echo number_format($gst_orders); ?> orders with GST
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-4 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Non-GST Orders</p>
                            <h6 class="mb-0 text-lg important-text-4"><?php echo number_format($non_gst_orders); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-secondary rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:receipt-outline" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0">
                        <?php echo number_format($non_gst_orders); ?> orders without GST
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Statistics Cards -->
    <div class="row row-cols-xxxl-5 row-cols-lg-3 row-cols-sm-2 row-cols-1 gy-3 mb-24">
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-1 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Total Orders</p>
                            <h6 class="mb-0 text-lg important-text-1"><?php echo number_format($total_orders); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-cyan rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:cart" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0 d-flex align-items-center gap-1">
                        <span class="d-inline-flex align-items-center gap-1 text-success-main">
                            <iconify-icon icon="bxs:up-arrow" class="text-xs"></iconify-icon> +<?php echo number_format($last_30_days_orders); ?>
                        </span>
                        Last 30 days
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-2 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Total Revenue</p>
                            <h6 class="mb-0 text-lg important-text-2">₹<?php echo number_format($total_revenue, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-purple rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="solar:wallet-bold" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0 d-flex align-items-center gap-1">
                        <span class="d-inline-flex align-items-center gap-1 text-success-main">
                            <iconify-icon icon="bxs:up-arrow" class="text-xs"></iconify-icon> +₹<?php echo number_format($last_30_days_revenue, 2); ?>
                        </span>
                        Last 30 days
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-3 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Today's Income</p>
                            <h6 class="mb-0 text-lg important-text-3">₹<?php echo number_format($today_revenue, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-info rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="solar:wallet-money-bold" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0 d-flex align-items-center gap-1">
                        <span class="d-inline-flex align-items-center gap-1 text-success-main">
                            <iconify-icon icon="bxs:up-arrow" class="text-xs"></iconify-icon> Today
                        </span>
                        <?= date('d M Y'); ?>
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-4 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">GST Revenue</p>
                            <h6 class="mb-0 text-lg important-text-4">₹<?php echo number_format($total_gst_revenue, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-orange rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:currency-inr" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0">
                        Revenue from GST orders
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-5 h-100 small-card stat-card">
                <div class="card-body compact-body">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <p class="fw-medium text-primary-light mb-1 text-sm">Non-GST Revenue</p>
                            <h6 class="mb-0 text-lg important-text-5">₹<?php echo number_format($non_gst_revenue, 2); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-secondary rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:cash-remove" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <p class="fw-medium text-xs text-primary-light mt-8 mb-0">
                        Revenue from non-GST orders
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Orders -->
    <div class="card h-100 mt-5">
        <div class="card-header compact-header">
            <div class="d-flex flex-wrap align-items-center gap-1 justify-content-between">
                <h6 class="mb-0 fw-semibold text-md important-text-4">Recent Orders</h6>
                <a href="#all-orders" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 text-sm">
                    View All Orders
                    <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
                </a>
            </div>
        </div>
        <div class="card-body compact-body">
            <div class="table-responsive scroll-sm">
                <table class="table bordered-table sm-table small-table mb-0">
                    <thead>
                        <tr>
                            <th scope="col">Branch</th>
                            <th scope="col">Customer</th>
                            <th scope="col">Order Date</th>
                            <th scope="col">Taxable Amount</th>
                            <th scope="col">GST Amount</th>
                            <th scope="col">Total Amount</th>
                            <th scope="col" class="text-center">Status</th>
                            <th scope="col" class="text-center">GST</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        try {
                            $recent_query = "
                                SELECT 
                                    o.order_id, 
                                    o.customer_name, 
                                    o.customer_contact, 
                                    o.order_date, 
                                    o.total_amount,
                                    o.taxable_amount,
                                    o.cgst_amount,
                                    o.sgst_amount,
                                    o.is_gst_active,
                                    o.status, 
                                    b.branch_name
                                FROM orders o
                                JOIN branches b ON o.branch_id = b.branch_id
                                " . (!empty($where_clause) ? "WHERE " . implode(' AND ', $where_clause) : "") . "
                                GROUP BY o.order_id
                                ORDER BY o.order_date DESC LIMIT 5
                            ";
                            $stmt = $pdo->prepare($recent_query);
                            $stmt->execute($params);
                            $recent_orders = $stmt->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($recent_orders as $order) {
                                $total_gst = $order['cgst_amount'] + $order['sgst_amount'];
                                echo '<tr>';
                                echo '<td class="text-sm">' . h($order['branch_name']) . '</td>';
                                echo '<td>';
                                echo '<div class="flex-grow-1">';
                                echo '<h6 class="text-sm mb-0 fw-medium">' . h($order['customer_name'] ?: 'Walk-in Customer') . '</h6>';
                                echo '<span class="text-xs text-secondary-light fw-medium">' . h($order['customer_contact']) . '</span>';
                                echo '</div>';
                                echo '</td>';
                                echo '<td class="text-sm">' . date('d M Y', strtotime($order['order_date'])) . '</td>';
                                echo '<td class="text-sm taxable-amount">₹' . number_format($order['taxable_amount'], 2) . '</td>';
                                echo '<td class="text-sm gst-amount">₹' . number_format($total_gst, 2) . '</td>';
                                echo '<td class="text-sm fw-bold">₹' . number_format($order['total_amount'], 2) . '</td>';
                                echo '<td class="text-center">';
                                $status_class = $order['status'] === 'pending' ? 'bg-warning-focus text-warning-main' :
                                               ($order['status'] === 'completed' ? 'bg-success-focus text-success-main' :
                                               ($order['status'] === 'processing' ? 'bg-info-focus text-info-main' : 'bg-danger-focus text-danger-main'));
                                echo '<span class="' . $status_class . ' px-20 py-7 rounded-pill fw-medium text-xs small-badge">' . ucfirst(h($order['status'])) . '</span>';
                                echo '</td>';
                                echo '<td class="text-center">';
                                echo '<span class="badge ' . ($order['is_gst_active'] ? 'bg-success' : 'bg-secondary') . ' text-white gst-badge">';
                                echo $order['is_gst_active'] ? 'GST On' : 'GST Off';
                                echo '</span>';
                                echo '</td>';
                                echo '</tr>';
                            }
                        } catch (PDOException $e) {
                            echo '<tr><td colspan="8" class="text-sm">Error loading recent orders: ' . h($e->getMessage()) . '</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- All Orders -->
    <div class="card h-100 mt-5" id="all-orders">
        <div class="card-header compact-header">
            <div class="d-flex flex-wrap align-items-center justify-content-between">
                <h6 class="mb-0 fw-semibold text-md important-text-2">All Orders with GST Details</h6>
                <a href="orders_add.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 text-sm">
                    Create New Order
                    <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
                </a>
            </div>
        </div>
        <div class="card-body compact-body">
            <div class="table-responsive">
                <table class="table bordered-table sm-table small-table mb-0" id="ordersTable" data-page-length="10">
                    <thead>
                        <tr>
                            <th scope="col">
                                <div class="form-check style-check d-flex align-items-center">
                                    <input class="form-check-input" type="checkbox" id="selectAll">
                                    <label class="form-check-label">S.L</label>
                                </div>
                            </th>
                            <th scope="col">Branch</th>
                            <th scope="col">Customer</th>
                            <th scope="col">Order Date</th>
                            <th scope="col">Taxable Amount</th>
                            <th scope="col">GST Amount</th>
                            <th scope="col">Total Amount</th>
                            <th scope="col" class="text-center">Status</th>
                            <th scope="col" class="text-center">GST</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($orders)): ?>
                            <tr>
                                <td colspan="10" class="text-sm text-center">No orders found.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($orders as $index => $order): ?>
                                <?php 
                                $total_gst = $order['cgst_amount'] + $order['sgst_amount'];
                                $taxable_amount = $order['taxable_amount'];
                                ?>
                                <tr>
                                    <td>
                                        <div class="form-check style-check d-flex align-items-center">
                                            <input class="form-check-input" type="checkbox" name="order_ids[]" value="<?= h($order['order_id']); ?>">
                                            <label class="form-check-label"><?= sprintf('%02d', $index + 1); ?></label>
                                        </div>
                                    </td>
                                    <td class="text-sm"><?= h($order['branch_name'] ?? 'N/A'); ?></td>
                                    <td>
                                        <div class="flex-grow-1">
                                            <h6 class="text-sm mb-0 fw-medium">
                                                <a href="javascript:void(0)" class="text-primary-600" data-bs-toggle="modal" data-bs-target="#orderModal<?= (int)$order['order_id']; ?>">
                                                    <?= h($order['customer_name'] ?: 'Walk-in Customer'); ?>
                                                </a>
                                            </h6>
                                            <span class="text-xs text-secondary-light fw-medium"><?= h($order['customer_contact']); ?></span>
                                        </div>
                                    </td>
                                    <td class="text-sm"><?= date('d M Y, H:i', strtotime($order['order_date'])); ?></td>
                                    <td class="text-sm taxable-amount">₹<?= number_format($taxable_amount, 2); ?></td>
                                    <td class="text-sm gst-amount">
                                        ₹<?= number_format($total_gst, 2); ?>
                                        <?php if ($order['is_gst_active']): ?>
                                            <br>
                                            <small class="text-muted">
                                                CGST: <?= $order['cgst_rate']; ?>% (₹<?= number_format($order['cgst_amount'], 2); ?>)
                                                <br>
                                                SGST: <?= $order['sgst_rate']; ?>% (₹<?= number_format($order['sgst_amount'], 2); ?>)
                                            </small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-sm fw-bold">₹<?= number_format($order['total_amount'], 2); ?></td>
                                    <td class="text-center">
                                        <?php
                                        $status_class = $order['status'] === 'pending' ? 'bg-warning-focus text-warning-main' :
                                                        ($order['status'] === 'completed' ? 'bg-success-focus text-success-main' :
                                                        ($order['status'] === 'processing' ? 'bg-info-focus text-info-main' : 'bg-danger-focus text-danger-main'));
                                        ?>
                                        <span class="<?= $status_class; ?> px-20 py-1 rounded-pill fw-medium text-xs small-badge">
                                            <?= ucfirst(h($order['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge <?= $order['is_gst_active'] ? 'bg-success' : 'bg-secondary'; ?> text-white gst-badge">
                                            <?= $order['is_gst_active'] ? 'GST On' : 'GST Off'; ?>
                                        </span>
                                    </td>
                                    <td>
                                        <div class="d-flex gap-1">
                                            <a href="javascript:void(0)"
                                               class="w-32-px h-32-px bg-primary-light text-primary-600 rounded-circle d-inline-flex align-items-center justify-content-center"
                                               data-bs-toggle="modal"
                                               data-bs-target="#orderModal<?= (int)$order['order_id']; ?>">
                                                <iconify-icon icon="iconamoon:eye-light"></iconify-icon>
                                            </a>
                                            <a href="orders_edit.php?id=<?= (int)$order['order_id']; ?>"
                                               class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
                                                <iconify-icon icon="lucide:edit"></iconify-icon>
                                            </a>
                                            <form action="orders_delete.php" method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to delete this order?');">
                                                <input type="hidden" name="order_id" value="<?= (int)$order['order_id']; ?>">
                                                <input type="hidden" name="csrf" value="<?= h($csrf); ?>">
                                                <button type="submit" class="w-32-px h-32-px bg-danger-focus text-danger-main rounded-circle d-inline-flex align-items-center justify-content-center border-0 bg-none">
                                                    <iconify-icon icon="mingcute:delete-2-line"></iconify-icon>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Order Details Modals -->
    <?php foreach ($orders as $order): ?>
        <?php 
        $total_gst = $order['cgst_amount'] + $order['sgst_amount'];
        $taxable_amount = $order['taxable_amount'];
        ?>
        <div class="modal fade" id="orderModal<?= (int)$order['order_id']; ?>" tabindex="-1" aria-labelledby="orderModalLabel<?= (int)$order['order_id']; ?>" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h6 class="section-title modal-title" id="orderModalLabel<?= (int)$order['order_id']; ?>">
                            Order #<?= (int)$order['order_id']; ?>
                        </h6>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body" style="background-color: #ffffff;">
                        <div class="row">
                            <!-- Order Details -->
                            <div class="col-md-12">
                                <table class="table table-bordered table-sm">
                                    <tbody>
                                        <tr>
                                            <th scope="row" style="width: 30%;">Customer Name</th>
                                            <td><?= h($order['customer_name'] ?: 'Walk-in Customer'); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Contact</th>
                                            <td><?= h($order['customer_contact']); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Branch</th>
                                            <td><?= h($order['branch_name'] ?? 'N/A'); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Order Date</th>
                                            <td><?= date('d M Y, H:i', strtotime($order['order_date'])); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Taxable Amount</th>
                                            <td class="taxable-amount">₹<?= number_format($taxable_amount, 2); ?></td>
                                        </tr>
                                        <?php if ($order['is_gst_active']): ?>
                                            <tr>
                                                <th scope="row">CGST (<?= $order['cgst_rate']; ?>%)</th>
                                                <td class="gst-amount">₹<?= number_format($order['cgst_amount'], 2); ?></td>
                                            </tr>
                                            <tr>
                                                <th scope="row">SGST (<?= $order['sgst_rate']; ?>%)</th>
                                                <td class="gst-amount">₹<?= number_format($order['sgst_amount'], 2); ?></td>
                                            </tr>
                                            <tr>
                                                <th scope="row">Total GST</th>
                                                <td class="gst-amount">₹<?= number_format($total_gst, 2); ?></td>
                                            </tr>
                                        <?php endif; ?>
                                        <tr>
                                            <th scope="row">Total Amount</th>
                                            <td class="fw-bold">₹<?= number_format($order['total_amount'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">Status</th>
                                            <td><?= ucfirst(h($order['status'])); ?></td>
                                        </tr>
                                        <tr>
                                            <th scope="row">GST Status</th>
                                            <td><?= $order['is_gst_active'] ? 'On' : 'Off'; ?></td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                        <!-- Order Items -->
                        <h6 class="fw-bold mb-3">Order Items</h6>
                        <div class="table-responsive">
                            <table class="table bordered-table sm-table small-table mb-0">
                                <thead>
                                    <tr>
                                        <th>Food</th>
                                        <th>Quantity</th>
                                        <th>Price</th>
                                        <th>Subtotal</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($order_items[$order['order_id']] ?? [] as $item): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <img src="../<?= h($item['image_url'] ?? 'assets/images/food/default.png'); ?>" alt="" class="flex-shrink-0 me-2 radius-8" style="width: 40px; height: 40px;">
                                                    <span class="text-sm"><?= h($item['food_name']); ?></span>
                                                </div>
                                            </td>
                                            <td class="text-sm"><?= (int)$item['quantity']; ?></td>
                                            <td class="text-sm">₹<?= number_format($item['price'], 2); ?></td>
                                            <td class="text-sm">₹<?= number_format($item['subtotal'], 2); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-outline-success btn-sm" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php include './partials/layouts/layoutBottom.php'; ?>

<?php
// Echo $script to ensure it's included in the output
echo $script;
?>