<?php
/**
 * Daily Reports Page
 */

require_once 'config.php';
checkCashierAuth();

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

// الحصول على ملخص اليوم باستخدام الكاش
$cache_key = 'cashier_report_' . $date;
$summary = $cache->get($cache_key);
if (!$summary) {
    $summary = $conn->query("
        SELECT 
            COUNT(*) as total_orders,
            SUM(CASE WHEN status = 'delivered' THEN total ELSE 0 END) as total_sales,
            SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as completed_orders,
            SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) as cancelled_orders,
            AVG(CASE WHEN status = 'delivered' THEN total ELSE NULL END) as avg_order,
            COUNT(DISTINCT customer_id) as unique_customers
        FROM orders 
        WHERE DATE(created_at) = '$date'
    ")->fetch_assoc();
    $cache->set($cache_key, $summary, 300); // 5 دقائق كاش
}

// الحصول على الطلبات حسب الساعة
$hourly = $conn->query("
    SELECT 
        HOUR(created_at) as hour,
        COUNT(*) as orders,
        SUM(total) as revenue
    FROM orders 
    WHERE DATE(created_at) = '$date'
    GROUP BY HOUR(created_at)
    ORDER BY hour
");

// الحصول على أفضل الوجبات مبيعاً
$top_meals = $conn->query("
    SELECT 
        m.name,
        SUM(oi.quantity) as quantity,
        SUM(oi.quantity * oi.price) as revenue
    FROM order_items oi
    JOIN meals m ON oi.meal_id = m.id
    JOIN orders o ON oi.order_id = o.id
    WHERE DATE(o.created_at) = '$date'
    GROUP BY m.id, m.name
    ORDER BY quantity DESC
    LIMIT 10
");

$page_title = 'التقارير اليومية';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <div class="cashier-app">
        <div class="container-fluid px-4">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h4>
                    <i class="bi bi-graph-up text-primary me-2"></i>
                    التقارير اليومية
                </h4>
                <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-arrow-right"></i>
                    العودة للرئيسية
                </a>
            </div>

            <!-- محدد التاريخ -->
            <div class="report-header">
                <form method="GET" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label">اختر التاريخ</label>
                        <input type="date" name="date" class="form-control" value="<?php echo $date; ?>" max="<?php echo date('Y-m-d'); ?>">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">
                            <i class="bi bi-search"></i> عرض
                        </button>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-success w-100" onclick="window.print()">
                            <i class="bi bi-printer"></i> طباعة
                        </button>
                    </div>
                </form>
            </div>

            <!-- بطاقات الملخص -->
            <div class="report-stats">
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $summary['total_orders'] ?? 0; ?></div>
                    <div class="report-stat-label">إجمالي الطلبات</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo formatMoney($summary['total_sales'] ?? 0); ?></div>
                    <div class="report-stat-label">إجمالي المبيعات</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $summary['completed_orders'] ?? 0; ?></div>
                    <div class="report-stat-label">الطلبات المكتملة</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $summary['cancelled_orders'] ?? 0; ?></div>
                    <div class="report-stat-label">الطلبات الملغية</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo formatMoney($summary['avg_order'] ?? 0); ?></div>
                    <div class="report-stat-label">متوسط قيمة الطلب</div>
                </div>
                
                <div class="report-stat-card">
                    <div class="report-stat-value"><?php echo $summary['unique_customers'] ?? 0; ?></div>
                    <div class="report-stat-label">عدد العملاء</div>
                </div>
            </div>

            <!-- توزيع الطلبات حسب الساعة -->
            <div class="report-table-container mb-4">
                <h5 class="mb-3">توزيع الطلبات حسب الساعة</h5>
                <table class="report-table">
                    <thead>
                        <tr>
                            <th>الساعة</th>
                            <th>عدد الطلبات</th>
                            <th>الإيرادات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $hourly->data_seek(0);
                        while ($h = $hourly->fetch_assoc()): 
                        ?>
                        <tr>
                            <td><?php echo $h['hour'] . ':00 - ' . ($h['hour']+1) . ':00'; ?></td>
                            <td><?php echo $h['orders']; ?></td>
                            <td><?php echo formatMoney($h['revenue']); ?></td>
                        </tr>
                        <?php endwhile; ?>
                        <?php if ($hourly->num_rows == 0): ?>
                        <tr>
                            <td colspan="3" class="text-center py-4">لا توجد طلبات في هذا اليوم</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- أكثر الوجبات مبيعاً -->
            <div class="report-table-container">
                <h5 class="mb-3">أكثر الوجبات مبيعاً</h5>
                <table class="report-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>الوجبة</th>
                            <th>الكمية المباعة</th>
                            <th>الإيرادات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $i = 1;
                        $top_meals->data_seek(0);
                        while ($m = $top_meals->fetch_assoc()): 
                        ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <td><?php echo htmlspecialchars($m['name']); ?></td>
                            <td><?php echo $m['quantity']; ?></td>
                            <td><?php echo formatMoney($m['revenue']); ?></td>
                        </tr>
                        <?php endwhile; ?>
                        <?php if ($top_meals->num_rows == 0): ?>
                        <tr>
                            <td colspan="4" class="text-center py-4">لا توجد مبيعات في هذا اليوم</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>