<?php
$pageTitle = 'Dashboard';
require_once __DIR__ . '/includes/header.php';

$stmt = $db->query("SELECT COUNT(*) as total FROM orders WHERE restaurant_id = ? AND DATE(created_at) = CURDATE()", [$restaurantId]);
$ordersToday = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM orders WHERE restaurant_id = ? AND order_status = 'new'", [$restaurantId]);
$pendingOrders = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM orders WHERE restaurant_id = ? AND order_status = 'preparing'", [$restaurantId]);
$preparing = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM orders WHERE restaurant_id = ? AND DATE(created_at) = CURDATE() AND order_status = 'completed'", [$restaurantId]);
$completedToday = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE restaurant_id = ? AND DATE(created_at) = CURDATE() AND payment_status = 'paid'", [$restaurantId]);
$salesToday = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE restaurant_id = ? AND YEARWEEK(created_at, 1) = YEARWEEK(CURDATE(), 1) AND payment_status = 'paid'", [$restaurantId]);
$salesWeek = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE restaurant_id = ? AND MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) AND payment_status = 'paid'", [$restaurantId]);
$salesMonth = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM menu_items WHERE restaurant_id = ? AND is_available = 1", [$restaurantId]);
$activeItems = $stmt->fetch()['total'];

$stmt = $db->query("SELECT COUNT(*) as total FROM customers WHERE restaurant_id = ?", [$restaurantId]);
$totalCustomers = $stmt->fetch()['total'];

$dailySales = $db->query("
    SELECT DATE(created_at) as date, COALESCE(SUM(grand_total), 0) as total, COUNT(*) as order_count
    FROM orders WHERE restaurant_id = ? AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
    AND payment_status = 'paid'
    GROUP BY DATE(created_at) ORDER BY date ASC
", [$restaurantId])->fetchAll();

$ordersByType = $db->query("
    SELECT order_type, COUNT(*) as count FROM orders WHERE restaurant_id = ? AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY order_type
", [$restaurantId])->fetchAll();

$ordersByStatus = $db->query("
    SELECT order_status, COUNT(*) as count FROM orders WHERE restaurant_id = ? AND DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    GROUP BY order_status
", [$restaurantId])->fetchAll();

$topProducts = $db->query("
    SELECT mi.name, SUM(oi.quantity) as total_qty, SUM(oi.item_total) as total_revenue
    FROM order_items oi
    INNER JOIN orders o ON oi.order_id = o.id
    LEFT JOIN menu_items mi ON oi.menu_item_id = mi.id
    WHERE o.restaurant_id = ? AND DATE(o.created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
    GROUP BY oi.menu_item_id, mi.name
    ORDER BY total_qty DESC LIMIT 10
", [$restaurantId])->fetchAll();

$recentOrders = $db->query("
    SELECT o.*, t.table_number
    FROM orders o
    LEFT JOIN tables t ON o.table_id = t.id
    WHERE o.restaurant_id = ?
    ORDER BY o.created_at DESC LIMIT 10
", [$restaurantId])->fetchAll();

$activeOffers = $db->query("
    SELECT * FROM offers WHERE restaurant_id = ? AND is_active = 1
    AND (end_date IS NULL OR end_date >= CURDATE())
    ORDER BY created_at DESC LIMIT 5
", [$restaurantId])->fetchAll();
?>

<div class="row mb-3">
    <div class="col-md-6">
        <h6 class="mb-0 text-muted"><?php echo sanitize($restaurant['name']); ?> &mdash; Dashboard</h6>
    </div>
    <div class="col-md-6 text-end">
        <span class="text-muted small"><?php echo date('l, F j, Y'); ?></span>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#3b82f6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($ordersToday); ?></div>
                    <div class="stat-label">Orders Today</div>
                </div>
                <div class="stat-icon" style="background:#eff6ff;color:#3b82f6;"><i class="fas fa-receipt"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#f59e0b;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($pendingOrders); ?></div>
                    <div class="stat-label">Pending Orders</div>
                </div>
                <div class="stat-icon" style="background:#fffbeb;color:#f59e0b;"><i class="fas fa-clock"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#8b5cf6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($preparing); ?></div>
                    <div class="stat-label">Preparing</div>
                </div>
                <div class="stat-icon" style="background:#f5f3ff;color:#8b5cf6;"><i class="fas fa-fire"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#10b981;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($completedToday); ?></div>
                    <div class="stat-label">Completed Today</div>
                </div>
                <div class="stat-icon" style="background:#ecfdf5;color:#10b981;"><i class="fas fa-check-circle"></i></div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#14b8a6;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo formatCurrency($salesToday, $currency); ?></div>
                    <div class="stat-label">Sales Today</div>
                </div>
                <div class="stat-icon" style="background:#f0fdfa;color:#14b8a6;"><i class="fas fa-dollar-sign"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#0ea5e9;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo formatCurrency($salesWeek, $currency); ?></div>
                    <div class="stat-label">Sales This Week</div>
                </div>
                <div class="stat-icon" style="background:#f0f9ff;color:#0ea5e9;"><i class="fas fa-calendar-week"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#ec4899;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo formatCurrency($salesMonth, $currency); ?></div>
                    <div class="stat-label">Sales This Month</div>
                </div>
                <div class="stat-icon" style="background:#fdf2f8;color:#ec4899;"><i class="fas fa-calendar-alt"></i></div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6 mb-3">
        <div class="stat-card" style="border-left-color:#84cc16;">
            <div class="d-flex justify-content-between align-items-start">
                <div>
                    <div class="stat-value"><?php echo number_format($activeItems); ?> / <?php echo number_format($totalCustomers); ?></div>
                    <div class="stat-label">Items / Customers</div>
                </div>
                <div class="stat-icon" style="background:#f7fee7;color:#84cc16;"><i class="fas fa-users"></i></div>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-bar me-2"></i>Daily Sales (7 Days)</div>
            <canvas id="dailySalesChart" height="250"></canvas>
        </div>
    </div>
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-pie me-2"></i>Orders by Type (30 Days)</div>
            <div style="max-width:300px;margin:0 auto;">
                <canvas id="ordersByTypeChart" height="250"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-chart-bar me-2"></i>Orders by Status (7 Days)</div>
            <canvas id="ordersByStatusChart" height="250"></canvas>
        </div>
    </div>
    <div class="col-xl-6 mb-3">
        <div class="chart-card">
            <div class="card-title"><i class="fas fa-trophy me-2"></i>Top Products (30 Days)</div>
            <canvas id="topProductsChart" height="250"></canvas>
        </div>
    </div>
</div>

<div class="row mb-4">
    <div class="col-xl-8 mb-3">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-receipt me-2"></i>Recent Orders</span>
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/orders.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>Order #</th>
                                <th>Table</th>
                                <th>Type</th>
                                <th>Total</th>
                                <th>Status</th>
                                <th>Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($recentOrders)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-3">No orders yet</td></tr>
                            <?php else: ?>
                                <?php foreach ($recentOrders as $ord): ?>
                                <tr>
                                    <td><a href="<?php echo $baseUrl; ?>/restaurant-admin/order_detail.php?id=<?php echo $ord['id']; ?>" class="fw-bold"><?php echo sanitize($ord['order_number']); ?></a></td>
                                    <td><?php echo sanitize($ord['table_number'] ?? 'N/A'); ?></td>
                                    <td><span class="badge bg-secondary"><?php echo ucfirst(str_replace('_', ' ', $ord['order_type'])); ?></span></td>
                                    <td><?php echo formatCurrency($ord['grand_total'], $currency); ?></td>
                                    <td><span class="badge order-status-<?php echo $ord['order_status']; ?>"><?php echo ucfirst($ord['order_status']); ?></span></td>
                                    <td><?php echo timeAgo($ord['created_at']); ?></td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-4 mb-3">
        <div class="table-card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-tags me-2"></i>Active Offers</span>
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/offers.php" class="btn btn-sm btn-outline-primary">View All</a>
            </div>
            <div class="card-body">
                <?php if (empty($activeOffers)): ?>
                    <div class="text-center text-muted py-3">No active offers</div>
                <?php else: ?>
                    <?php foreach ($activeOffers as $off): ?>
                    <div class="d-flex justify-content-between align-items-center border-bottom py-2 px-3">
                        <div>
                            <strong class="small"><?php echo sanitize($off['title']); ?></strong>
                            <div class="text-muted" style="font-size:11px;"><?php echo ucfirst($off['offer_type']); ?> - <?php echo $off['offer_type'] === 'percentage' ? $off['discount_value'] . '%' : formatCurrency($off['discount_value'], $currency); ?></div>
                        </div>
                        <span class="badge bg-success">Active</span>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
var salesLabels = <?php echo json_encode(array_map(function($d) { return date('M d', strtotime($d['date'])); }, $dailySales)); ?>;
var salesData = <?php echo json_encode(array_map(function($d) { return (float)$d['total']; }, $dailySales)); ?>;
var typeLabels = <?php echo json_encode(array_map(function($t) { return ucfirst(str_replace('_', ' ', $t['order_type'])); }, $ordersByType)); ?>;
var typeData = <?php echo json_encode(array_map(function($t) { return (int)$t['count']; }, $ordersByType)); ?>;
var statusLabels = <?php echo json_encode(array_map(function($s) { return ucfirst($s['order_status']); }, $ordersByStatus)); ?>;
var statusData = <?php echo json_encode(array_map(function($s) { return (int)$s['count']; }, $ordersByStatus)); ?>;
var productLabels = <?php echo json_encode(array_map(function($p) { return $p['name'] ?? 'Unknown'; }, array_reverse($topProducts))); ?>;
var productData = <?php echo json_encode(array_map(function($p) { return (int)$p['total_qty']; }, array_reverse($topProducts))); ?>;

new Chart(document.getElementById('dailySalesChart'), {
    type: 'bar',
    data: {
        labels: salesLabels.length ? salesLabels : ['No Data'],
        datasets: [{label: 'Sales', data: salesData.length ? salesData : [0], backgroundColor: '#3b82f6', borderRadius: 6}]
    },
    options: {responsive: true, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true}}}
});

new Chart(document.getElementById('ordersByTypeChart'), {
    type: 'doughnut',
    data: {
        labels: typeLabels.length ? typeLabels : ['No Data'],
        datasets: [{data: typeData.length ? typeData : [1], backgroundColor: ['#3b82f6', '#f59e0b', '#10b981', '#8b5cf6']}]
    },
    options: {responsive: true, plugins: {legend: {position: 'bottom'}}}
});

new Chart(document.getElementById('ordersByStatusChart'), {
    type: 'bar',
    data: {
        labels: statusLabels.length ? statusLabels : ['No Data'],
        datasets: [{label: 'Orders', data: statusData.length ? statusData : [0], backgroundColor: ['#3b82f6','#10b981','#f59e0b','#8b5cf6','#6366f1','#14b8a6','#ef4444','#ef4444'], borderRadius: 6}]
    },
    options: {responsive: true, plugins: {legend: {display: false}}, scales: {y: {beginAtZero: true, ticks: {stepSize: 1}}}}
});

new Chart(document.getElementById('topProductsChart'), {
    type: 'bar',
    data: {
        labels: productLabels.length ? productLabels : ['No Data'],
        datasets: [{label: 'Qty Sold', data: productData.length ? productData : [0], backgroundColor: '#8b5cf6', borderRadius: 6}]
    },
    options: {indexAxis: 'y', responsive: true, plugins: {legend: {display: false}}, scales: {x: {beginAtZero: true, ticks: {stepSize: 1}}}}
});
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
