<?php

class DashboardController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('dashboard', 'view');

        $db = Database::getConnection();

        $todaySales = $db->query(
            "SELECT COALESCE(SUM(total_amount),0) as total FROM orders
             WHERE DATE(created_at) = CURDATE() AND status != 'CANCELLED'"
        )->fetch()['total'];

        $todayOrderCount = $db->query(
            "SELECT COUNT(*) as cnt FROM orders WHERE DATE(created_at) = CURDATE() AND status != 'CANCELLED'"
        )->fetch()['cnt'];

        $yesterdaySales = $db->query(
            "SELECT COALESCE(SUM(total_amount),0) as total FROM orders
             WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY) AND status != 'CANCELLED'"
        )->fetch()['total'];

        $mtdSales = $db->query(
            "SELECT COALESCE(SUM(total_amount),0) as total FROM orders
             WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) AND status != 'CANCELLED'"
        )->fetch()['total'];

        $pendingOrders = $db->query(
            "SELECT COUNT(*) as cnt FROM orders WHERE status IN ('PENDING','CONFIRMED','PREPARING')"
        )->fetch()['cnt'];

        $outForDelivery = $db->query(
            "SELECT COUNT(*) as cnt FROM orders WHERE status = 'OUT_FOR_DELIVERY'"
        )->fetch()['cnt'];

        $outOfStockCount = $db->query(
            "SELECT COUNT(*) as cnt FROM raw_materials WHERE current_stock <= 0 AND is_active = 1"
        )->fetch()['cnt'];

        $lowStockCount = $db->query(
            "SELECT COUNT(*) as cnt FROM raw_materials WHERE current_stock > 0 AND current_stock <= reorder_level AND is_active = 1"
        )->fetch()['cnt'];

        $paymentModel = new Payment();
        $pendingPayments = $paymentModel->unpaidOrdersCount();

        $cashBalance = $db->query(
            "SELECT COALESCE(SUM(current_balance),0) as total FROM finance_accounts WHERE is_active = 1"
        )->fetch()['total'];

        $totalExpenses = $db->query(
            "SELECT COALESCE(SUM(amount),0) as total FROM expenses
             WHERE MONTH(expense_date) = MONTH(CURDATE()) AND YEAR(expense_date) = YEAR(CURDATE())"
        )->fetch()['total'];

        $supplierModel = new Supplier();
        $totalPayables = $supplierModel->totalDues();

        $netMtd = $mtdSales - $totalExpenses;

        // --- Smart Alerts ---
        $deliveryModel = new Delivery();
        $payrollModel = new PayrollRun();
        $delayedDeliveries = $deliveryModel->delayedCount(15);
        $payrollAwaiting = $payrollModel->awaitingPaymentCount();

        $alerts = [];
        if ($outOfStockCount > 0) {
            $alerts[] = ['icon' => 'fa-ban', 'color' => 'red', 'text' => "{$outOfStockCount} raw material(s) out of stock", 'link' => 'stock'];
        }
        if ($lowStockCount > 0) {
            $alerts[] = ['icon' => 'fa-arrow-down-wide-short', 'color' => 'gold', 'text' => "{$lowStockCount} item(s) at low stock — reorder soon", 'link' => 'stock'];
        }
        if ($pendingPayments > 0) {
            $alerts[] = ['icon' => 'fa-credit-card', 'color' => 'red', 'text' => "{$pendingPayments} unpaid order(s) awaiting payment", 'link' => 'payments'];
        }
        if ($delayedDeliveries > 0) {
            $alerts[] = ['icon' => 'fa-motorcycle', 'color' => 'gold', 'text' => "{$delayedDeliveries} delivery(ies) assigned 15+ min without pickup", 'link' => 'delivery'];
        }
        if ($totalPayables > 0) {
            $alerts[] = ['icon' => 'fa-truck', 'color' => 'gold', 'text' => formatMoney($totalPayables) . " owed to suppliers", 'link' => 'suppliers'];
        }
        if ($payrollAwaiting > 0) {
            $alerts[] = ['icon' => 'fa-users', 'color' => 'blue', 'text' => "{$payrollAwaiting} payroll run(s) finalized — awaiting payment", 'link' => 'payroll'];
        }

        // --- 7-day sales trend ---
        $trendRows = $db->query(
            "SELECT DATE(created_at) as d, COALESCE(SUM(total_amount),0) as revenue
             FROM orders WHERE status != 'CANCELLED' AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
             GROUP BY DATE(created_at) ORDER BY d ASC"
        )->fetchAll();
        $trendMap = [];
        foreach ($trendRows as $row) {
            $trendMap[$row['d']] = (float) $row['revenue'];
        }
        $salesTrendLabels = [];
        $salesTrendData = [];
        for ($i = 6; $i >= 0; $i--) {
            $d = date('Y-m-d', strtotime("-{$i} days"));
            $salesTrendLabels[] = date('D', strtotime($d));
            $salesTrendData[] = $trendMap[$d] ?? 0;
        }

        // --- Today's top items ---
        $reportModel = new Report();
        $topItemsToday = $reportModel->topItems(date('Y-m-d'), date('Y-m-d'), 5);

        // --- Recent orders & activity ---
        $orderModel = new Order();
        $recentOrders = $orderModel->recentOrders(6);

        $recentActivity = $db->query(
            "SELECT al.*, u.full_name FROM audit_log al
             LEFT JOIN users u ON u.id = al.user_id
             ORDER BY al.id DESC LIMIT 8"
        )->fetchAll();

        $customerModel = new Customer();
        $appCustomersOnline = $customerModel->onlineCount(5);
        $appCustomersTotal = $db->query("SELECT COUNT(*) as cnt FROM customers WHERE password_hash IS NOT NULL")->fetch()['cnt'];

        $this->view('dashboard.index', [
            'pageTitle'       => 'Dashboard',
            'todaySales'      => $todaySales,
            'todayOrderCount' => $todayOrderCount,
            'yesterdaySales'  => $yesterdaySales,
            'mtdSales'        => $mtdSales,
            'pendingOrders'   => $pendingOrders,
            'outForDelivery'  => $outForDelivery,
            'lowStockCount'   => $lowStockCount,
            'outOfStockCount' => $outOfStockCount,
            'pendingPayments' => $pendingPayments,
            'cashBalance'     => $cashBalance,
            'totalExpenses'   => $totalExpenses,
            'totalPayables'   => $totalPayables,
            'netMtd'          => $netMtd,
            'alerts'          => $alerts,
            'salesTrendLabels'=> $salesTrendLabels,
            'salesTrendData'  => $salesTrendData,
            'topItemsToday'   => $topItemsToday,
            'recentOrders'    => $recentOrders,
            'recentActivity'  => $recentActivity,
            'appCustomersOnline' => $appCustomersOnline,
            'appCustomersTotal'  => $appCustomersTotal,
        ]);
    }
}
