<?php

declare(strict_types=1);

namespace App\Controllers;

final class DashboardController extends BaseController
{
    public function index(array $params = []): void
    {
        $this->requirePermission('dashboard.view');

        $db = $this->db;

        // ── Stats ─────────────────────────────────────────────────────────────

        $todayStart = date('Y-m-d 00:00:00');
        $todayEnd   = date('Y-m-d 23:59:59');

        $stats = [
            'orders_today'   => (int) $db->fetchValue(
                "SELECT COUNT(*) FROM orders WHERE placed_at BETWEEN ? AND ?",
                [$todayStart, $todayEnd]
            ),
            'revenue_today'  => (float) $db->fetchValue(
                "SELECT COALESCE(SUM(total_amount),0) FROM orders
                  WHERE status = 'delivered' AND placed_at BETWEEN ? AND ?",
                [$todayStart, $todayEnd]
            ),
            'pending_orders' => (int) $db->fetchValue(
                "SELECT COUNT(*) FROM orders WHERE status = 'pending'"
            ),
            'total_customers' => (int) $db->fetchValue(
                "SELECT COUNT(*) FROM customers"
            ),
            'total_items'    => (int) $db->fetchValue(
                "SELECT COUNT(*) FROM menu_items WHERE is_available = 1"
            ),
            'revenue_month'  => (float) $db->fetchValue(
                "SELECT COALESCE(SUM(total_amount),0) FROM orders
                  WHERE status = 'delivered'
                    AND MONTH(placed_at) = MONTH(NOW())
                    AND YEAR(placed_at)  = YEAR(NOW())"
            ),
        ];

        // ── Recent Orders (last 8) ────────────────────────────────────────────

        $recentOrders = $db->fetchAll(
            "SELECT o.id, o.order_number, o.status, o.total_amount, o.placed_at,
                    COALESCE(u.name, o.guest_name, 'Guest') AS customer_name
               FROM orders o
               LEFT JOIN customers c ON c.id = o.customer_id
               LEFT JOIN users u     ON u.id = c.user_id
              ORDER BY o.placed_at DESC
              LIMIT 8"
        );

        // ── Sales last 7 days (for mini chart) ────────────────────────────────

        $salesChart = $db->fetchAll(
            "SELECT DATE(placed_at) AS day,
                    COUNT(*)        AS total_orders,
                    COALESCE(SUM(total_amount), 0) AS revenue
               FROM orders
              WHERE placed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
                AND status != 'cancelled'
              GROUP BY DATE(placed_at)
              ORDER BY day ASC"
        );

        // ── Order status distribution ─────────────────────────────────────────

        $statusDist = $db->fetchAll(
            "SELECT status, COUNT(*) AS cnt
               FROM orders
              WHERE placed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
              GROUP BY status"
        );

        // ── Top selling items ─────────────────────────────────────────────────

        $topItems = $db->fetchAll(
            "SELECT mi.name, SUM(oi.quantity) AS total_qty,
                    SUM(oi.line_total) AS total_revenue
               FROM order_items oi
               JOIN menu_items mi ON mi.id = oi.menu_item_id
               JOIN orders o      ON o.id  = oi.order_id
              WHERE o.status = 'delivered'
                AND o.placed_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
              GROUP BY oi.menu_item_id
              ORDER BY total_qty DESC
              LIMIT 5"
        );

        $this->view('dashboard.index', [
            'pageTitle'    => 'Dashboard',
            'stats'        => $stats,
            'recentOrders' => $recentOrders,
            'salesChart'   => $salesChart,
            'statusDist'   => $statusDist,
            'topItems'     => $topItems,
        ]);
    }
}
