<?php
require_once __DIR__ . '/../includes/config.php';

if (!isLoggedIn()) {
    jsonResponse(['success' => false, 'error' => 'Unauthorized'], 401);
}

$today = date('Y-m-d');

// Today's revenue
$result = $db->query("
    SELECT SUM((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) - 
           COALESCE((SELECT (CASE WHEN d.type='percent' THEN ROUND((SELECT SUM(oi.price * oi.quantity) FROM order_items oi WHERE oi.order_id = o.id) * d.value / 100) ELSE d.value END) FROM discounts d WHERE d.id = o.discount_id), 0) + 
           (CASE WHEN o.delivery_enabled THEN o.delivery_price ELSE 0 END)) as today_revenue
    FROM orders o
    WHERE o.order_date = '$today'
");
$today_revenue = ($result->fetch_assoc()['today_revenue'] ?? 0);

// Today's orders
$result = $db->query("SELECT COUNT(*) as count FROM orders WHERE order_date = '$today'");
$today_orders = $result->fetch_assoc()['count'];

jsonResponse([
    'revenue' => number_format($today_revenue, 2, '.', ''),
    'orders' => $today_orders
]);
?>
