<?php

namespace App\Http\Controllers\Api\Biller;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\RestaurantTable;
use Illuminate\Http\JsonResponse;

class DashboardController extends Controller
{
    /**
     * Get performance overview statistics and trends for the active branch.
     */
    public function dashboard(): JsonResponse
    {
        $branchId = auth()->user()->active_branch_id;
        $today = now()->toDateString();
        $yesterday = now()->subDay()->toDateString();

        // 1. Today's settled sales
        $todaySales = (float) Order::where('branch_id', $branchId)
            ->whereDate('created_at', $today)
            ->where('status', 'settled')
            ->sum('grand_total');

        // 2. Yesterday's settled sales (for growth comparison)
        $yesterdaySales = (float) Order::where('branch_id', $branchId)
            ->whereDate('created_at', $yesterday)
            ->where('status', 'settled')
            ->sum('grand_total');

        // 3. Sales growth percentage calculation
        $changePercentage = 0.0;
        if ($yesterdaySales > 0) {
            $changePercentage = round((($todaySales - $yesterdaySales) / $yesterdaySales) * 100, 2);
        } elseif ($todaySales > 0) {
            $changePercentage = 100.0;
        }

        $changeFormatted = ($changePercentage >= 0 ? '+' : '') . number_format($changePercentage, 2) . '% vs yest.';

        // 4. Active orders (running KOTs)
        $activeOrders = Order::where('branch_id', $branchId)
            ->where('status', 'active')
            ->count();

        // 5. Total orders today (active + settled + held + etc.)
        $totalOrdersToday = Order::where('branch_id', $branchId)
            ->whereDate('created_at', $today)
            ->count();

        // 6. Occupied tables count
        $occupiedTables = RestaurantTable::where('branch_id', $branchId)
            ->where('status', 'occupied')
            ->count();

        // 7. Hourly sales trend for charts (database-agnostic, grouped in memory)
        $todaySettledOrders = Order::where('branch_id', $branchId)
            ->whereDate('created_at', $today)
            ->where('status', 'settled')
            ->select(['created_at', 'grand_total'])
            ->get();

        $hourlySalesData = array_fill(0, 24, 0.0);
        foreach ($todaySettledOrders as $order) {
            $hourNum = (int) $order->created_at->format('G'); // 'G' returns 0-23
            $hourlySalesData[$hourNum] += (float) $order->grand_total;
        }

        $hourlySales = [];
        for ($i = 0; $i < 24; $i++) {
            $hourString = str_pad($i, 2, '0', STR_PAD_LEFT) . ':00';
            $hourlySales[] = [
                'hour' => $hourString,
                'sales' => $hourlySalesData[$i],
            ];
        }

        return response()->json([
            'today_sales' => $todaySales,
            'yesterday_sales' => $yesterdaySales,
            'sales_change_percentage' => $changePercentage,
            'sales_change_formatted' => $changeFormatted,
            'active_orders' => $activeOrders,
            'total_orders_today' => $totalOrdersToday,
            'occupied_tables' => $occupiedTables,
            'hourly_sales' => $hourlySales,
        ]);
    }
}
