<?php

namespace App\Http\Controllers;

use App\Models\KitchenTicket;
use App\Models\Order;
use App\Models\OrderItem;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class KitchenController extends Controller
{
    public function tickets(Request $request): JsonResponse
    {
        $query = KitchenTicket::with(['order.table', 'order.user', 'acknowledgedBy', 'preparedBy'])
            ->where('branch_id', $request->user()->branch_id);

        // Filter by station if provided
        if ($request->has('station')) {
            $query->where('station', $request->station);
        }

        // Filter by status if provided
        if ($request->has('status')) {
            $query->where('status', $request->status);
        }

        // Filter by date if provided
        if ($request->has('date')) {
            $query->whereDate('created_at', $request->date);
        }

        // Default to active tickets (not completed) if no status filter
        if (!$request->has('status')) {
            $query->whereNotIn('status', ['completed']);
        }

        $tickets = $query->orderBy('created_at', 'asc')->get();

        return response()->json([
            'tickets' => $tickets->map(function ($ticket) {
                return [
                    'id' => $ticket->id,
                    'ticket_number' => $ticket->ticket_number,
                    'order_number' => $ticket->order->order_number,
                    'table_name' => $ticket->order->table?->name,
                    'station' => $ticket->station,
                    'priority' => $ticket->priority,
                    'status' => $ticket->status,
                    'items' => $ticket->items,
                    'special_instructions' => $ticket->special_instructions,
                    'estimated_time' => $ticket->estimated_time,
                    'elapsed_time' => $ticket->elapsed_time,
                    'preparation_time' => $ticket->preparation_time,
                    'priority_color' => $ticket->priority_color,
                    'status_color' => $ticket->status_color,
                    'completed_at' => $ticket->completed_at,
                    'acknowledged_by' => $ticket->preparedBy?->name,
                    'created_at' => $ticket->created_at,
                ];
            }),
        ]);
    }

    public function complete(Request $request, KitchenTicket $ticket): JsonResponse
    {
        if (!$ticket->canBeCompleted()) {
            return response()->json(['error' => 'Ticket cannot be completed'], 400);
        }

        $ticket->update([
            'status' => 'completed',
            'completed_at' => now(),
            'prepared_by' => $request->user()->id,
        ]);

        // Update order items status
        OrderItem::whereIn('id', collect($ticket->items)->pluck('order_item_id'))
            ->update(['status' => 'completed']);

        // Check if all items in the order are completed
        $order = $ticket->order;
        $allItemsCompleted = $order->items()->where('status', '!=', 'completed')->count() === 0;
        
        if ($allItemsCompleted) {
            $order->update([
                'status' => 'completed',
            ]);

            // Make table available if it's a dine-in order
            if ($order->type === 'dine_in' && $order->table) {
                $order->table->makeAvailable();
            }
        }

        return response()->json(['message' => 'Order completed successfully']);
    }

    public function updatePriority(Request $request, KitchenTicket $ticket): JsonResponse
    {
        $request->validate([
            'priority' => 'required|in:low,normal,high,urgent',
        ]);

        $ticket->update(['priority' => $request->priority]);

        return response()->json(['message' => 'Priority updated successfully']);
    }

    public function updateEstimatedTime(Request $request, KitchenTicket $ticket): JsonResponse
    {
        $request->validate([
            'estimated_time' => 'required|integer|min:1|max:180',
        ]);

        $ticket->update(['estimated_time' => $request->estimated_time]);

        return response()->json(['message' => 'Estimated time updated successfully']);
    }

    public function stats(Request $request): JsonResponse
    {
        $branchId = $request->user()->branch_id;
        $date = $request->has('date') ? $request->date : today()->toDateString();

        $stats = [
            'pending' => KitchenTicket::where('branch_id', $branchId)
                ->where('status', 'pending')
                ->whereDate('created_at', $date)
                ->count(),
            
            'completed_today' => KitchenTicket::where('branch_id', $branchId)
                ->where('status', 'completed')
                ->whereDate('completed_at', $date)
                ->count(),
        ];

        return response()->json($stats);
    }
}