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

$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$tab = $_GET['tab'] ?? 'sales';

$totalSales = $db->query("SELECT COALESCE(SUM(grand_total), 0) as total FROM orders WHERE restaurant_id = ? AND DATE(created_at) BETWEEN ? AND ? AND payment_status = 'paid'", [$restaurantId, $dateFrom, $dateTo])->fetch()['total'];
$totalOrders = $db->query("SELECT COUNT(*) as total FROM orders WHERE restaurant_id = ? AND DATE(created_at) BETWEEN ? AND ?", [$restaurantId, $dateFrom, $dateTo])->fetch()['total'];
$avgOrderValue = $totalOrders > 0 ? $totalSales / $totalOrders : 0;

$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) BETWEEN ? AND ? AND payment_status = 'paid'
    GROUP BY DATE(created_at) ORDER BY date ASC
", [$restaurantId, $dateFrom, $dateTo])->fetchAll();

$itemSales = $db->query("
    SELECT mi.name, SUM(oi.quantity) as qty, SUM(oi.item_total) as 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) BETWEEN ? AND ? AND o.payment_status = 'paid'
    GROUP BY oi.menu_item_id, mi.name ORDER BY revenue DESC LIMIT 20
", [$restaurantId, $dateFrom, $dateTo])->fetchAll();

$categorySales = $db->query("
    SELECT c.name, SUM(oi.quantity) as qty, SUM(oi.item_total) as revenue
    FROM order_items oi
    INNER JOIN orders o ON oi.order_id = o.id
    INNER JOIN menu_items mi ON oi.menu_item_id = mi.id
    INNER JOIN categories c ON mi.category_id = c.id
    WHERE o.restaurant_id = ? AND DATE(o.created_at) BETWEEN ? AND ? AND o.payment_status = 'paid'
    GROUP BY c.id, c.name ORDER BY revenue DESC
", [$restaurantId, $dateFrom, $dateTo])->fetchAll();

$ordersByType = $db->query("
    SELECT order_type, COUNT(*) as count, COALESCE(SUM(grand_total), 0) as total
    FROM orders WHERE restaurant_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY order_type
", [$restaurantId, $dateFrom, $dateTo])->fetchAll();

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

$payments = $db->query("
    SELECT payment_method, payment_status, COUNT(*) as count, COALESCE(SUM(grand_total), 0) as total
    FROM orders WHERE restaurant_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY payment_method, payment_status
", [$restaurantId, $dateFrom, $dateTo])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Reports</h6>
        <small class="text-muted">Analyze your restaurant performance</small>
    </div>
</div>

<div class="table-card mb-3">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <input type="hidden" name="tab" value="<?php echo $tab; ?>">
            <div class="col-md-2">
                <label class="form-label small">From</label>
                <input type="date" class="form-control form-control-sm" name="date_from" value="<?php echo sanitize($dateFrom); ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label small">To</label>
                <input type="date" class="form-control form-control-sm" name="date_to" value="<?php echo sanitize($dateTo); ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-sm btn-primary w-100"><i class="fas fa-filter me-1"></i>Filter</button>
            </div>
        </form>
    </div>
</div>

<div class="row mb-3">
    <div class="col-md-4 mb-2">
        <div class="stat-card" style="border-left-color:#10b981;">
            <div class="stat-value"><?php echo formatCurrency($totalSales, $currency); ?></div>
            <div class="stat-label">Total Sales</div>
        </div>
    </div>
    <div class="col-md-4 mb-2">
        <div class="stat-card" style="border-left-color:#3b82f6;">
            <div class="stat-value"><?php echo number_format($totalOrders); ?></div>
            <div class="stat-label">Total Orders</div>
        </div>
    </div>
    <div class="col-md-4 mb-2">
        <div class="stat-card" style="border-left-color:#8b5cf6;">
            <div class="stat-value"><?php echo formatCurrency($avgOrderValue, $currency); ?></div>
            <div class="stat-label">Avg. Order Value</div>
        </div>
    </div>
</div>

<ul class="nav nav-tabs mb-3">
    <?php foreach (['sales'=>'Sales','items'=>'Items','categories'=>'Categories','orders'=>'Orders','payments'=>'Payments'] as $tKey => $tLabel): ?>
    <li class="nav-item">
        <a class="nav-link <?php echo $tab === $tKey ? 'active' : ''; ?>" href="?tab=<?php echo $tKey; ?>&date_from=<?php echo $dateFrom; ?>&date_to=<?php echo $dateTo; ?>"><?php echo $tLabel; ?></a>
    </li>
    <?php endforeach; ?>
</div>

<?php if ($tab === 'sales'): ?>
<div class="chart-card">
    <div class="card-title"><i class="fas fa-chart-line me-2"></i>Daily Sales</div>
    <canvas id="salesChart" height="300"></canvas>
</div>
<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light"><tr><th>Date</th><th>Orders</th><th>Sales</th></tr></thead>
                <tbody>
                    <?php foreach ($dailySales as $ds): ?>
                    <tr>
                        <td><?php echo formatDate($ds['date'], 'M d, Y'); ?></td>
                        <td><?php echo $ds['order_count']; ?></td>
                        <td><?php echo formatCurrency($ds['total'], $currency); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($dailySales)): ?>
                    <tr><td colspan="3" class="text-center text-muted">No data for this period</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<script>
new Chart(document.getElementById('salesChart'), {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_map(function($d){return date('M d', strtotime($d['date']));}, $dailySales)); ?>,
        datasets: [{label:'Sales', data:<?php echo json_encode(array_map(function($d){return (float)$d['total'];}, $dailySales)); ?>, borderColor:'#10b981', backgroundColor:'rgba(16,185,129,0.1)', fill:true, tension:0.4}]
    },
    options: {responsive:true, plugins:{legend:{display:false}}, scales:{y:{beginAtZero:true}}}
});
</script>
<?php endif; ?>

<?php if ($tab === 'items'): ?>
<div class="table-card">
    <div class="card-header"><i class="fas fa-utensils me-2"></i>Top Selling Items</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light"><tr><th>#</th><th>Item</th><th>Qty Sold</th><th>Revenue</th></tr></thead>
                <tbody>
                    <?php $rank = 0; foreach ($itemSales as $is): $rank++; ?>
                    <tr><td><?php echo $rank; ?></td><td><?php echo sanitize($is['name'] ?? 'Unknown'); ?></td><td><?php echo $is['qty']; ?></td><td><?php echo formatCurrency($is['revenue'], $currency); ?></td></tr>
                    <?php endforeach; ?>
                    <?php if (empty($itemSales)): ?><tr><td colspan="4" class="text-center text-muted">No data</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($tab === 'categories'): ?>
<div class="table-card">
    <div class="card-header"><i class="fas fa-layer-group me-2"></i>Category Performance</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light"><tr><th>Category</th><th>Qty Sold</th><th>Revenue</th></tr></thead>
                <tbody>
                    <?php foreach ($categorySales as $cs): ?>
                    <tr><td><?php echo sanitize($cs['name']); ?></td><td><?php echo $cs['qty']; ?></td><td><?php echo formatCurrency($cs['revenue'], $currency); ?></td></tr>
                    <?php endforeach; ?>
                    <?php if (empty($categorySales)): ?><tr><td colspan="3" class="text-center text-muted">No data</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if ($tab === 'orders'): ?>
<div class="row">
    <div class="col-md-6">
        <div class="chart-card"><div class="card-title">By Type</div>
            <canvas id="ordTypeChart" height="200"></canvas>
        </div>
    </div>
    <div class="col-md-6">
        <div class="chart-card"><div class="card-title">By Status</div>
            <canvas id="ordStatusChart" height="200"></canvas>
        </div>
    </div>
</div>
<script>
new Chart(document.getElementById('ordTypeChart'), {
    type:'doughnut',
    data:{labels:<?php echo json_encode(array_map(function($t){return ucfirst(str_replace('_',' ',$t['order_type']));}, $ordersByType)); ?>,
    datasets:[{data:<?php echo json_encode(array_map(function($t){return (int)$t['count'];}, $ordersByType)); ?>,backgroundColor:['#3b82f6','#f59e0b','#10b981']}]},
    options:{responsive:true,plugins:{legend:{position:'bottom'}}}
});
new Chart(document.getElementById('ordStatusChart'), {
    type:'bar',
    data:{labels:<?php echo json_encode(array_map(function($s){return ucfirst($s['order_status']);}, $ordersByStatus)); ?>,
    datasets:[{data:<?php echo json_encode(array_map(function($s){return (int)$s['count'];}, $ordersByStatus)); ?>,backgroundColor:'#6366f1',borderRadius:6}]},
    options:{responsive:true,plugins:{legend:{display:false}},scales:{y:{beginAtZero:true,ticks:{stepSize:1}}}}
});
</script>
<?php endif; ?>

<?php if ($tab === 'payments'): ?>
<div class="table-card">
    <div class="card-header"><i class="fas fa-credit-card me-2"></i>Payment Summary</div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="table-light"><tr><th>Method</th><th>Status</th><th>Count</th><th>Total</th></tr></thead>
                <tbody>
                    <?php foreach ($payments as $pm): ?>
                    <tr>
                        <td><?php echo sanitize(ucfirst($pm['payment_method'] ?? 'N/A')); ?></td>
                        <td><span class="badge bg-<?php echo $pm['payment_status'] === 'paid' ? 'success' : 'warning'; ?>"><?php echo ucfirst($pm['payment_status']); ?></span></td>
                        <td><?php echo $pm['count']; ?></td>
                        <td><?php echo formatCurrency($pm['total'], $currency); ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($payments)): ?><tr><td colspan="4" class="text-center text-muted">No data</td></tr><?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
<?php endif; ?>

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