<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Kitchen\UpdateTicketStatusRequest;
use App\Http\Resources\KitchenTicketResource;
use App\Models\KitchenTicket;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

class KitchenTicketController extends ApiController
{
    public function index(Request $request): AnonymousResourceCollection
    {
        $branchId = $this->currentBranchId($request);
        if (!$branchId) {
            abort(400, 'Branch context is required for kitchen tickets.');
        }

        $tickets = KitchenTicket::query()
            ->with(['items', 'order'])
            ->where('branch_id', $branchId)
            ->whereIn('status', ['pending', 'preparing', 'ready'])
            ->orderBy('priority', 'desc')
            ->orderBy('created_at', 'asc')
            ->get();

        return KitchenTicketResource::collection($tickets);
    }

    public function show(Request $request, KitchenTicket $kitchenTicket): KitchenTicketResource
    {
        $this->ensureBranchScoped($kitchenTicket, $this->currentBranchId($request));
        
        return new KitchenTicketResource($kitchenTicket->load('items'));
    }

    public function update(UpdateTicketStatusRequest $request, KitchenTicket $kitchenTicket): KitchenTicketResource
    {
        $this->ensureBranchScoped($kitchenTicket, $this->currentBranchId($request));
        
        $status = $request->string('status')->toString();
        $updateData = ['status' => $status];

        if ($status === 'preparing' && !$kitchenTicket->started_at) {
            $updateData['started_at'] = now();
        } elseif ($status === 'ready' && !$kitchenTicket->ready_at) {
            $updateData['ready_at'] = now();
        } elseif ($status === 'served' && !$kitchenTicket->served_at) {
            $updateData['served_at'] = now();
        }

        $kitchenTicket->update($updateData);

        return new KitchenTicketResource($kitchenTicket->load('items'));
    }
}
