<?php

namespace App\Controllers;

use App\Models\PosOrderItemModel;
use App\Models\PosOrderModel;
use App\Models\RestaurantReservationModel;

/**
 * Unified Restaurant hub — new landing page tying together the F&B
 * screens that already existed as separate pages (POS orders, table
 * reservations, menu, kitchen display), matching a user-supplied
 * mockup. Real data throughout: "Covers Today" in the mockup implied a
 * diner headcount this app doesn't track per order — relabeled "Orders
 * Today" (a real count) rather than fabricated. Today's Sales Overview
 * buckets paid orders by the hour they were settled (updated_at, the
 * only timestamp available once an order flips to 'paid' — see
 * PosOrderModel).
 */
class RestaurantController extends BaseController
{
    public function index()
    {
        $orders = new PosOrderModel();
        $today  = date('Y-m-d');

        $paidToday = $orders->where('status', 'paid')->where('DATE(updated_at)', $today)->findAll();

        $revenueToday = '0.00';
        $hourly       = array_fill(6, 18, '0.00'); // 6am - 11pm buckets

        foreach ($paidToday as $order) {
            $itemTotal = (new PosOrderItemModel())->orderTotal($order->id);
            $revenueToday = money_add($revenueToday, $itemTotal);

            $hour = (int) date('G', strtotime($order->updated_at));

            if (isset($hourly[$hour])) {
                $hourly[$hour] = money_add($hourly[$hour], $itemTotal);
            }
        }

        $topItems = $this->topSellingItems();

        return view('restaurant/index', [
            'pageTitle'    => 'Restaurant',
            'pageSubtitle' => 'Manage restaurant operations and analytics.',
            'stats'        => [
                'revenueToday' => $revenueToday,
                'ordersToday'  => count($paidToday),
                'avgSpend'     => count($paidToday) > 0 ? money_divide($revenueToday, (string) count($paidToday)) : '0.00',
                'openOrders'   => count($orders->activeOrders()),
            ],
            'hourly'       => $hourly,
            'topItems'     => $topItems,
            'activeOrders' => array_slice($orders->activeOrders(), 0, 6),
            'reservationsToday' => (new RestaurantReservationModel())->forDate($today),
        ]);
    }

    /** @return list<object{item_name: string, qty: int, revenue: string}> */
    private function topSellingItems(int $limit = 5): array
    {
        return (new PosOrderItemModel())
            ->select('item_name, SUM(quantity) as qty, SUM(quantity * unit_price) as revenue')
            ->groupBy('item_name')
            ->orderBy('qty', 'desc')
            ->limit($limit)
            ->findAll();
    }
}
