<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$auth->requireRole('admin');

try {
    $db = new Database();

    // Default to the last 30 days
    $endDate = new DateTime();
    $startDate = (new DateTime())->sub(new DateInterval('P30D'));

    if (!empty($_GET['start_date']) && !empty($_GET['end_date'])) {
        $startDate = new DateTime($_GET['start_date']);
        $endDate = new DateTime($_GET['end_date']);
    }

    // Ensure the end date includes the full day
    $endDate->setTime(23, 59, 59);

    $sql = "
        SELECT
            DATE(created_at) as period,
            SUM(amount) as total_revenue,
            SUM(CASE WHEN source = 'delivery' THEN amount ELSE 0 END) as delivery_revenue,
            SUM(CASE WHEN source = 'order' THEN amount ELSE 0 END) as order_revenue
        FROM (
            -- Revenue from direct deliveries
            SELECT
                price as amount,
                created_at,
                'delivery' as source
            FROM deliveries
            WHERE status = 'delivered'

            UNION ALL

            -- Revenue from shop orders
            SELECT
                total_amount as amount,
                created_at,
                'order' as source
            FROM orders
            WHERE status = 'delivered'
        ) as revenue_data
        WHERE created_at BETWEEN :startDate AND :endDate
        GROUP BY DATE(created_at)
        ORDER BY period ASC;
    ";

    $stmt = $db->query($sql, [
        ':startDate' => $startDate->format('Y-m-d H:i:s'),
        ':endDate' => $endDate->format('Y-m-d H:i:s')
    ]);

    $revenue_breakdown = $stmt->fetchAll(PDO::FETCH_ASSOC);

    jsonResponse([
        'success' => true,
        'breakdown' => $revenue_breakdown,
        'query_period' => [
            'start' => $startDate->format('Y-m-d'),
            'end' => $endDate->format('Y-m-d')
        ]
    ]);

} catch (Exception $e) {
    jsonResponse([
        'success' => false,
        'message' => $e->getMessage()
    ], 500);
}
?>