<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\TransactionItem;
use App\Models\Outlet;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
use Illuminate\Http\RedirectResponse;

class KdsController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user();
        $outlets = Outlet::select('id', 'name')->get();
        
        $outletFilter = $request->input('outlet_id');
        $outletId = $user->outlet_id 
            ? (int)$user->outlet_id 
            : ($outletFilter 
                ? (int)$outletFilter 
                : ($outlets->first() ? $outlets->first()->id : null));

        // Fetch active kitchen items (pending, cooking, ready)
        $activeItems = TransactionItem::with(['transaction.table', 'product', 'modifiers.modifier'])
            ->whereHas('transaction', function ($query) use ($outletId) {
                $query->whereIn('status', ['success', 'pending'])
                      ->when($outletId, fn($q) => $q->where('outlet_id', $outletId));
            })
            ->whereIn('kitchen_status', ['pending', 'cooking', 'ready'])
            ->orderBy('created_at', 'asc')
            ->get();

        // Fetch the 50 most recently served items for this outlet
        $servedItems = TransactionItem::with(['transaction.table', 'product', 'modifiers.modifier'])
            ->whereHas('transaction', function ($query) use ($outletId) {
                $query->whereIn('status', ['success', 'pending'])
                      ->when($outletId, fn($q) => $q->where('outlet_id', $outletId));
            })
            ->where('kitchen_status', 'served')
            ->orderBy('updated_at', 'desc')
            ->limit(50)
            ->get();

        // Merge active and served collections
        $items = $activeItems->merge($servedItems);

        return Inertia::render('CafePOS/Kds/Index', [
            'items' => $items,
            'outlets' => $outlets,
            'filters' => [
                'outlet_id' => $outletId ? (string)$outletId : null,
            ]
        ]);
    }

    public function updateStatus(Request $request, TransactionItem $item): RedirectResponse
    {
        $request->validate([
            'status' => ['required', 'string', 'in:pending,cooking,ready,served'],
        ]);

        $item->update(['kitchen_status' => $request->status]);

        return redirect()->back()->with('success', 'Kitchen status updated.');
    }
}
