<?php
session_start();
require_once 'config/db_config.php'; // Include PDO database connection

// Ensure user is logged in and is an admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php"); // Redirect to login if not authenticated
    exit();
}

// Fetch statistics
try {
    // Total Orders (across all branches)
    $stmt = $pdo->query("SELECT COUNT(*) as total_orders FROM orders");
    $total_orders = $stmt->fetch()['total_orders'];

    // Total Revenue (across all branches)
    $stmt = $pdo->query("SELECT SUM(total_amount) as total_revenue FROM orders");
    $total_revenue = $stmt->fetch()['total_revenue'] ?? 0;

    // Current Day Revenue (across all branches)
    $stmt = $pdo->query("SELECT SUM(total_amount) as today_revenue FROM orders WHERE DATE(order_date) = CURDATE()");
    $today_revenue = $stmt->fetch()['today_revenue'] ?? 0;

    // Total Food Items (across all branches)
    $stmt = $pdo->query("SELECT COUNT(*) as total_foods FROM foods");
    $total_foods = $stmt->fetch()['total_foods'];

    // Pending Orders (across all branches)
    $stmt = $pdo->query("SELECT COUNT(*) as pending_orders FROM orders WHERE status = 'pending'");
    $pending_orders = $stmt->fetch()['pending_orders'];

    // Total Branches
    $stmt = $pdo->query("SELECT COUNT(*) as total_branches FROM branches");
    $total_branches = $stmt->fetch()['total_branches'];

    // Last 30 days orders (across all branches)
    $stmt = $pdo->query("SELECT COUNT(*) as last_30_days_orders FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
    $last_30_days_orders = $stmt->fetch()['last_30_days_orders'];

    // Last 30 days revenue (across all branches)
    $stmt = $pdo->query("SELECT SUM(total_amount) as last_30_days_revenue FROM orders WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
    $last_30_days_revenue = $stmt->fetch()['last_30_days_revenue'] ?? 0;

    // Total Categories (across all branches)
    $stmt = $pdo->query("SELECT COUNT(*) as total_categories FROM food_categories");
    $total_categories = $stmt->fetch()['total_categories'];

    // Data for Order Statistics Chart (last 30 days, grouped by day)
    $stmt = $pdo->query("
        SELECT DATE(order_date) as order_day, SUM(total_amount) as daily_revenue
        FROM orders
        WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
        GROUP BY DATE(order_date)
        ORDER BY order_day
    ");
    $chart_data = $stmt->fetchAll();
    $chart_labels = [];
    $chart_revenues = [];
    foreach ($chart_data as $data) {
        $chart_labels[] = date('d M', strtotime($data['order_day']));
        $chart_revenues[] = $data['daily_revenue'];
    }
    $chart_labels_json = json_encode($chart_labels);
    $chart_revenues_json = json_encode($chart_revenues);
} catch (PDOException $e) {
    die("Error fetching statistics: " . $e->getMessage());
}

// Include chart script (ApexCharts for visualization)
$script = '
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    var options = {
        chart: {
            type: "line",
            height: 200,
            toolbar: { show: false }
        },
        series: [{
            name: "Revenue",
            data: ' . $chart_revenues_json . '
        }],
        xaxis: {
            categories: ' . $chart_labels_json . ',
            labels: { style: { fontSize: "10px" } }
        },
        yaxis: {
            title: { text: "Revenue (₹)" },
            labels: { formatter: function(val) { return "₹" + val.toFixed(2); } }
        },
        stroke: { curve: "smooth", width: 2 },
        colors: ["#1BD1AF"],
        tooltip: {
            y: { formatter: function(val) { return "₹" + val.toFixed(2); } }
        }
    };
    var chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();
});
</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); }
.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; }
@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">Admin Dashboard</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">Admin</li>
        </ul>
    </div>

    <!-- Statistics Cards -->
    <div class="row row-cols-xxxl-5 row-cols-lg-3 row-cols-sm-2 row-cols-1 gy-3">
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-1 h-100 small-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">
                <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">
                <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 Revenue</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:calendar" 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($today_revenue, 2); ?>
                        </span>
                        Current day
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-4 h-100 small-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">Pending Orders</p>
                            <h6 class="mb-0 text-lg important-text-4"><?php echo number_format($pending_orders); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-success-main rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:clock-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 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($pending_orders); ?>
                        </span>
                        Current pending
                    </p>
                </div>
            </div>
        </div>
        <div class="col">
            <div class="card shadow-none border bg-gradient-start-5 h-100 small-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 Branches</p>
                            <h6 class="mb-0 text-lg important-text-1"><?php echo number_format($total_branches); ?></h6>
                        </div>
                        <div class="w-40-px h-40-px bg-red rounded-circle d-flex justify-content-center align-items-center">
                            <iconify-icon icon="mdi:store" 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> +0
                        </span>
                        Last 30 days
                    </p>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Branches List -->
    <div class="card mb-16 mt-5">
        <div class="card-body compact-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between mb-12">
                <h6 class="text-md mb-0 fw-semibold important-text-1">All Branches</h6>
                <a href="create_branch.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 text-sm">
                    Add Branch
                    <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
                </a>
            </div>
            <div class="table-responsive scroll-sm">
                <table class="table bordered-table sm-table small-table mb-0">
                    <thead>
                        <tr>
                            <th scope="col">Branch Name</th>
                            <th scope="col">Address</th>
                            <th scope="col">City</th>
                            <th scope="col">Image</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        try {
                            $stmt = $pdo->query("SELECT branch_name, address, city, image_url FROM branches ORDER BY branch_name LIMIT 5");
                            $branches = $stmt->fetchAll();
                            foreach ($branches as $branch) {
                                echo '<tr>';
                                echo '<td>' . htmlspecialchars($branch['branch_name']) . '</td>';
                                echo '<td>' . htmlspecialchars($branch['address']) . '</td>';
                                echo '<td>' . htmlspecialchars($branch['city']) . '</td>';
                                echo '<td>';
                                if ($branch['image_url']) {
                                    echo '<img src="' . htmlspecialchars($branch['image_url']) . '" alt="Branch Image" class="w-32-px h-32-px rounded">';
                                }
                                echo '</td>';
                                echo '</tr>';
                            }
                        } catch (PDOException $e) {
                            echo '<tr><td colspan="4">Error loading branches: ' . $e->getMessage() . '</td></tr>';
                        }
                        ?>
                    </tbody>
                </table>
            </div>
            <a href="branches.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 mt-2 text-sm">
                View All Branches
                <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
            </a>
        </div>
    </div>

    <div class="row gy-3 mt-1">
        <!-- Order Statistics -->
        <div class="col-xxl-6 col-xl-12">
            <div class="card h-100">
                <div class="card-header compact-header">
                    <div class="d-flex flex-wrap align-items-center justify-content-between">
                        <h6 class="text-md mb-0 fw-semibold important-text-2">Order Statistics (All Branches)</h6>
                        <select class="form-select bg-base form-select-sm w-auto" style="font-size: 0.85rem;">
                            <option>Yearly</option>
                            <option selected>Monthly</option>
                            <option>Weekly</option>
                            <option>Today</option>
                        </select>
                    </div>
                    <div class="d-flex flex-wrap align-items-center gap-2 mt-2">
                        <h6 class="mb-0 text-sm">₹<?php echo number_format($total_revenue, 2); ?></h6>
                        <span class="text-xs fw-semibold rounded-pill bg-success-focus text-success-main border br-success px-2 py-1 line-height-1 d-flex align-items-center gap-1 small-badge">
                            10% <iconify-icon icon="bxs:up-arrow" class="text-xs"></iconify-icon>
                        </span>
                        <span class="text-xs fw-medium">+ ₹<?php echo number_format($last_30_days_revenue / 30, 2); ?> Per Day</span>
                    </div>
                </div>
                <div class="card-body compact-body">
                    <div id="chart" class="pt-4 apexcharts-tooltip-style-1" style="min-height: 200px;"></div>
                </div>
            </div>
        </div>

        <!-- Food Categories Summary -->
        <div class="col-xxl-3 col-xl-6">
            <div class="card h-100 radius-8 border">
                <div class="card-header compact-header">
                    <h6 class="mb-0 fw-semibold text-md important-text-3">Food Categories</h6>
                </div>
                <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 Categories</p>
                            <h6 class="mb-0 text-lg"><?php echo number_format($total_categories); ?></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="mdi:food-variant" class="text-white small-icon mb-0"></iconify-icon>
                        </div>
                    </div>
                    <a href="categories.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 mt-2 text-sm">
                        Manage Categories
                        <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
                    </a>
                </div>
            </div>
        </div>

        <!-- Recent Orders (All Branches) -->
        <div class="col-xxl-9 col-xl-12">
            <div class="card h-100">
                <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 (All Branches)</h6>
                        <a href="orders.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 text-sm">
                            View All
                            <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">Total Amount</th>
                                    <th scope="col" class="text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $stmt = $pdo->query("
                                        SELECT o.order_id, o.customer_name, o.customer_contact, o.order_date, o.total_amount, o.status, b.branch_name
                                        FROM orders o
                                        JOIN branches b ON o.branch_id = b.branch_id
                                        ORDER BY o.order_date DESC LIMIT 5
                                    ");
                                    $orders = $stmt->fetchAll();
                                    foreach ($orders as $order) {
                                        echo '<tr>';
                                        echo '<td>' . htmlspecialchars($order['branch_name']) . '</td>';
                                        echo '<td>';
                                        echo '<div class="flex-grow-1">';
                                        echo '<h6 class="text-sm mb-0 fw-medium">' . htmlspecialchars($order['customer_name']) . '</h6>';
                                        echo '<span class="text-xs text-secondary-light fw-medium">' . htmlspecialchars($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">₹' . 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' : 'bg-danger-focus text-danger-main');
                                        echo '<span class="' . $status_class . ' px-15 py-1 rounded-pill fw-medium text-xs small-badge">' . ucfirst($order['status']) . '</span>';
                                        echo '</td>';
                                        echo '</tr>';
                                    }
                                } catch (PDOException $e) {
                                    echo '<tr><td colspan="5">Error loading orders: ' . $e->getMessage() . '</td></tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Tax Rates Summary -->
        <div class="col-xxl-3 col-xl-6">
            <div class="card h-100 radius-8 border">
                <div class="card-header compact-header">
                    <h6 class="mb-0 fw-semibold text-md important-text-1">Tax Rates (Latest)</h6>
                </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" class="text-sm">Tax Type</th>
                                    <th scope="col" class="text-sm">Rate</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                try {
                                    $stmt = $pdo->query("
                                        SELECT t.cgst_rate, t.sgst_rate
                                        FROM taxes t
                                        WHERE t.effective_date = (
                                            SELECT MAX(effective_date)
                                            FROM taxes
                                        )
                                        LIMIT 1
                                    ");
                                    $tax = $stmt->fetch();
                                    if ($tax) {
                                        echo '<tr><td class="text-sm">CGST</td><td class="text-sm">' . number_format($tax['cgst_rate'], 2) . '%</td></tr>';
                                        echo '<tr><td class="text-sm">SGST</td><td class="text-sm">' . number_format($tax['sgst_rate'], 2) . '%</td></tr>';
                                    } else {
                                        echo '<tr><td colspan="2" class="text-sm">No tax rates defined</td></tr>';
                                    }
                                } catch (PDOException $e) {
                                    echo '<tr><td colspan="2" class="text-sm">Error loading tax rates: ' . $e->getMessage() . '</td></tr>';
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                    <a href="taxes.php" class="text-primary-600 hover-text-primary d-flex align-items-center gap-1 mt-2 text-sm">
                        Manage Taxes
                        <iconify-icon icon="solar:alt-arrow-right-linear" class="icon small-icon"></iconify-icon>
                    </a>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include './partials/layouts/layoutBottom.php' ?>
<script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
<script>
// Admin Revenue Chart
document.addEventListener("DOMContentLoaded", function() {
    // Check if admin chart container exists
    if (document.querySelector("#adminRevenueChart")) {
        var options = {
            chart: {
                type: "line",
                height: 200,
                toolbar: { show: false }
            },
            series: [{
                name: "Revenue",
                data: <?php echo $chart_revenues_json; ?>
            }],
            xaxis: {
                categories: <?php echo $chart_labels_json; ?>,
                labels: { 
                    style: { 
                        fontSize: "10px" 
                    },
                    rotate: -45
                }
            },
            yaxis: {
                title: { text: "Revenue (₹)" },
                labels: { 
                    formatter: function(val) { 
                        return "₹" + val.toFixed(2); 
                    } 
                }
            },
            stroke: { 
                curve: "smooth", 
                width: 2 
            },
            colors: ["#1BD1AF"],
            tooltip: {
                y: { 
                    formatter: function(val) { 
                        return "₹" + val.toFixed(2); 
                    } 
                }
            },
            dataLabels: {
                enabled: false
            }
        };
        
        var chart = new ApexCharts(document.querySelector("#adminRevenueChart"), options);
        chart.render();
    }
});
</script>