<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager', 'cashier', 'kitchen_staff', 'waiter']);

$restaurantId = $auth->restaurantId();
$db = Database::getInstance();

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

switch ($reportType) {
    case 'sales':
        $data = $db->query("SELECT DATE(created_at) as date, COALESCE(SUM(grand_total),0) as total, COUNT(*) as 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();
        break;
    case 'items':
        $data = $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", [$restaurantId, $dateFrom, $dateTo])->fetchAll();
        break;
    default:
        $data = [];
}

jsonResponse(true, 'ok', ['data' => $data]);
