<?php
session_start();
require_once('../includes/admin-security.php');
include_once('includes/config.php');

// Dashboard Counts
$ret = mysqli_query($con, "select count(id) as totalorders,
count(if((orderStatus='' || orderStatus is null),0,null)) as neworders,
count(if(orderStatus='Packed', 0,null)) as packedorders,
count(if(orderStatus='Dispatched',  0,null)) as dispatchedorders,
count(if(orderStatus='In Transit',  0,null)) as intransitorders,
count(if(orderStatus='Out For Delivery', 0,null)) as outfdorders,
count(if(orderStatus='Delivered', 0,null)) as deliveredorders,
count(if(orderStatus='Cancelled', 0,null)) as cancelledorders
from orders;");
$results = mysqli_fetch_array($ret);
$torders = $results['totalorders'];
$norders = $results['neworders'];
$porders = $results['packedorders'];
$dtorders = $results['dispatchedorders'];
$intorders = $results['intransitorders'];
$otforders = $results['outfdorders'];
$deliveredorders = $results['deliveredorders'];
$cancelledorders = $results['cancelledorders'];

// Registered users
$ret1 = mysqli_query($con, "select count(id) as totalusers from users;");
$results1 = mysqli_fetch_array($ret1);
$tregusers = $results1['totalusers'];

// Today's revenue
$today = date('Y-m-d');
$todayRevQuery = mysqli_query($con, "SELECT COALESCE(SUM(totalAmount), 0) as todayRev FROM orders WHERE DATE(orderDate) = '$today'");
$todayRevResult = mysqli_fetch_array($todayRevQuery);
$todayRevenue = $todayRevResult['todayRev'];

// This month's revenue
$thisMonth = date('Y-m');
$monthRevQuery = mysqli_query($con, "SELECT COALESCE(SUM(totalAmount), 0) as monthRev FROM orders WHERE DATE_FORMAT(orderDate, '%Y-%m') = '$thisMonth'");
$monthRevResult = mysqli_fetch_array($monthRevQuery);
$monthRevenue = $monthRevResult['monthRev'];

// Total revenue
$totalRevQuery = mysqli_query($con, "SELECT COALESCE(SUM(totalAmount), 0) as totalRev FROM orders WHERE orderStatus = 'Delivered'");
$totalRevResult = mysqli_fetch_array($totalRevQuery);
$totalRevenue = $totalRevResult['totalRev'];

// Today's orders count
$todayOrdersQuery = mysqli_query($con, "SELECT COUNT(id) as todayCount FROM orders WHERE DATE(orderDate) = '$today'");
$todayOrdersResult = mysqli_fetch_array($todayOrdersQuery);
$todayOrdersCount = $todayOrdersResult['todayCount'];

// Last 7 days sales data for chart
$last7DaysData = [];
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $dayQuery = mysqli_query($con, "SELECT COALESCE(SUM(totalAmount), 0) as dayRev FROM orders WHERE DATE(orderDate) = '$date'");
    $dayResult = mysqli_fetch_array($dayQuery);
    $last7DaysData[] = [
        'date' => date('M d', strtotime($date)),
        'revenue' => $dayResult['dayRev']
    ];
}

// Top 5 products
$topProductsQuery = mysqli_query($con, "SELECT p.productName, COUNT(o.id) as orderCount, SUM(o.quantity) as totalQty 
    FROM orders o 
    JOIN products p ON o.productId = p.id 
    GROUP BY o.productId 
    ORDER BY orderCount DESC 
    LIMIT 5");
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <meta name="description" content="Admin Dashboard - Awesome Mall" />
    <meta name="author" content="" />
    <title>Awesome Mall | Admin Dashboard</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="css/styles.css" rel="stylesheet" />
    <link href="css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>

    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <!-- Page Header -->
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-tachometer-alt me-2"></i> Dashboard</h1>
                            <p>Welcome back! Here's what's happening today</p>
                        </div>
                        <div>
                            <span class="badge bg-primary fs-6">
                                <i class="fas fa-calendar me-1"></i><?php echo date('l, M d, Y'); ?>
                            </span>
                        </div>
                    </div>

                    <!-- Revenue Metrics -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon success">
                                    <i class="fas fa-dollar-sign"></i>
                                </div>
                                <div class="stat-value">$<?php echo number_format($todayRevenue, 2); ?></div>
                                <div class="stat-label">Today's Revenue</div>
                                <div class="stat-trend">
                                    <small class="text-success"><i class="fas fa-arrow-up"></i>
                                        <?php echo $todayOrdersCount; ?> orders</small>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon primary">
                                    <i class="fas fa-chart-line"></i>
                                </div>
                                <div class="stat-value">$<?php echo number_format($monthRevenue, 2); ?></div>
                                <div class="stat-label">This Month</div>
                                <div class="stat-trend">
                                    <small class="text-muted"><?php echo date('F Y'); ?></small>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon info">
                                    <i class="fas fa-shopping-bag"></i>
                                </div>
                                <div class="stat-value"><?php echo $torders; ?></div>
                                <div class="stat-label">Total Orders</div>
                                <a class="stat-link" href="all-orders.php">View All →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon warning">
                                    <i class="fas fa-clock"></i>
                                </div>
                                <div class="stat-value"><?php echo $norders; ?></div>
                                <div class="stat-label">Pending Orders</div>
                                <a class="stat-link" href="pending-orders.php">Process Now →</a>
                            </div>
                        </div>
                    </div>

                    <!-- Charts Row -->
                    <div class="row mb-4">
                        <!-- Sales Chart -->
                        <div class="col-xl-8 mb-4">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-chart-area me-2"></i>Sales Overview (Last 7 Days)
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="salesChart" height="80"></canvas>
                                </div>
                            </div>
                        </div>

                        <!-- Order Status Breakdown -->
                        <div class="col-xl-4 mb-4">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-chart-pie me-2"></i>Order Status</h5>
                                </div>
                                <div class="card-body">
                                    <canvas id="statusChart" height="160"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Order Status Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon orange">
                                    <i class="fas fa-box"></i>
                                </div>
                                <div class="stat-value"><?php echo $porders; ?></div>
                                <div class="stat-label">Packed</div>
                                <a class="stat-link" href="packed-orders.php">View →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon purple">
                                    <i class="fas fa-shipping-fast"></i>
                                </div>
                                <div class="stat-value"><?php echo $dtorders; ?></div>
                                <div class="stat-label">Dispatched</div>
                                <a class="stat-link" href="dispatched-orders.php">View →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon blue">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <div class="stat-value"><?php echo $deliveredorders; ?></div>
                                <div class="stat-label">Delivered</div>
                                <a class="stat-link" href="delivered-orders.php">View →</a>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stat-card">
                                <div class="stat-icon green">
                                    <i class="fas fa-users"></i>
                                </div>
                                <div class="stat-value"><?php echo $tregusers; ?></div>
                                <div class="stat-label">Total Users</div>
                                <a class="stat-link" href="manage-users.php">View →</a>
                            </div>
                        </div>
                    </div>

                    <!-- Tables Row -->
                    <div class="row">
                        <!-- Recent Orders -->
                        <div class="col-xl-8 mb-4">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Recent Orders</h5>
                                </div>
                                <div class="card-body">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Order #</th>
                                                <th>Customer</th>
                                                <th>Amount</th>
                                                <th>Status</th>
                                                <th>Date</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            $recentOrders = mysqli_query($con, "SELECT o.id, o.orderNumber, o.totalAmount, o.orderStatus, o.orderDate, u.email, ud.name 
                                                FROM orders o 
                                                JOIN users u ON o.userId = u.id 
                                                LEFT JOIN user_details ud ON ud.user_id = u.id 
                                                ORDER BY o.orderDate DESC 
                                                LIMIT 8");
                                            while ($order = mysqli_fetch_array($recentOrders)) {
                                                $statusClass = '';
                                                switch (strtolower($order['orderStatus'])) {
                                                    case 'pending':
                                                        $statusClass = 'pending';
                                                        break;
                                                    case 'processing':
                                                        $statusClass = 'processing';
                                                        break;
                                                    case 'dispatched':
                                                        $statusClass = 'dispatched';
                                                        break;
                                                    case 'delivered':
                                                        $statusClass = 'delivered';
                                                        break;
                                                    case 'cancelled':
                                                        $statusClass = 'cancelled';
                                                        break;
                                                    default:
                                                        $statusClass = 'pending';
                                                }
                                                ?>
                                                <tr>
                                                    <td><strong><?php echo $order['orderNumber']; ?></strong></td>
                                                    <td><?php echo $order['name'] ? $order['name'] : $order['email']; ?>
                                                    </td>
                                                    <td><strong>$<?php echo number_format($order['totalAmount'], 2); ?></strong>
                                                    </td>
                                                    <td><span
                                                            class="status-badge <?php echo $statusClass; ?>"><?php echo $order['orderStatus'] ? $order['orderStatus'] : 'Pending'; ?></span>
                                                    </td>
                                                    <td><small><?php echo date('M d, h:i A', strtotime($order['orderDate'])); ?></small>
                                                    </td>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                    <div class="text-center mt-3">
                                        <a href="all-orders.php" class="btn btn-outline-primary">View All Orders</a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Top Products -->
                        <div class="col-xl-4 mb-4">
                            <div class="table-card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-star me-2"></i>Top Products</h5>
                                </div>
                                <div class="card-body">
                                    <div class="list-group list-group-flush">
                                        <?php
                                        $rank = 1;
                                        while ($product = mysqli_fetch_array($topProductsQuery)) {
                                            ?>
                                            <div class="list-group-item border-0 px-0">
                                                <div class="d-flex justify-content-between align-items-start">
                                                    <div>
                                                        <h6 class="mb-1"><?php echo $rank; ?>.
                                                            <?php echo htmlentities($product['productName']); ?></h6>
                                                        <small class="text-muted"><?php echo $product['orderCount']; ?>
                                                            orders • <?php echo $product['totalQty']; ?> sold</small>
                                                    </div>
                                                    <span class="badge bg-success">#<?php echo $rank; ?></span>
                                                </div>
                                            </div>
                                            <?php
                                            $rank++;
                                        }
                                        ?>
                                    </div>
                                    <div class="text-center mt-3">
                                        <a href="manage-products.php" class="btn btn-outline-primary btn-sm">View All
                                            Products</a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
        crossorigin="anonymous"></script>
    <script src="js/scripts.js"></script>

    <script>
        // Sales Chart (Last 7 Days)
        const salesCtx = document.getElementById('salesChart').getContext('2d');
        const salesData = <?php echo json_encode($last7DaysData); ?>;

        new Chart(salesCtx, {
            type: 'line',
            data: {
                labels: salesData.map(d => d.date),
                datasets: [{
                    label: 'Revenue ($)',
                    data: salesData.map(d => d.revenue),
                    backgroundColor: 'rgba(13, 110, 253, 0.1)',
                    borderColor: 'rgba(13, 110, 253, 1)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            callback: function (value) {
                                return '$' + value.toFixed(0);
                            }
                        }
                    }
                }
            }
        });

        // Status Pie Chart
        const statusCtx = document.getElementById('statusChart').getContext('2d');
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['New', 'Dispatched', 'Delivered', 'Cancelled', 'In Transit'],
                datasets: [{
                    data: [
                        <?php echo $norders; ?>,
                        <?php echo $dtorders; ?>,
                        <?php echo $deliveredorders; ?>,
                        <?php echo $cancelledorders; ?>,
                        <?php echo $intorders; ?>
                    ],
                    backgroundColor: [
                        'rgba(255, 193, 7, 0.8)',
                        'rgba(13, 202, 240, 0.8)',
                        'rgba(25, 135, 84, 0.8)',
                        'rgba(220, 53, 69, 0.8)',
                        'rgba(111, 66, 193, 0.8)'
                    ]
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                }
            }
        });
    </script>
</body>

</html>
