<?php

namespace App\Http\Controllers;

use App\Models\CateringPackage;
use App\Models\Chef;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CateringController extends Controller
{
    public function index(Request $request)
    {
        $packages = CateringPackage::with(['chef', 'cuisine'])
            ->where('available', true)
            ->when($request->filled('chef'), fn ($q) => $q->where('chef_id', $request->chef))
            ->when($request->filled('category'), fn ($q) => $q->where('category', $request->category))
            ->orderByDesc('featured')->orderBy('name')
            ->get();

        $chefs = Chef::where('status', 'active')->whereHas('cateringPackages')->get();
        $categories = CateringPackage::where('available', true)->whereNotNull('category')->distinct()->pluck('category');

        return view('site.catering.index', compact('packages', 'chefs', 'categories'));
    }

    public function order(Request $request)
    {
        $data = $request->validate([
            'package_id' => 'required|exists:catering_packages,id',
            'name' => 'required|string|max:120',
            'phone' => 'required|string|max:40',
            'email' => 'nullable|email|max:120',
            'quantity' => 'required|numeric|min:0.5',
            'event_date' => 'required|date|after:today',
            'address' => 'nullable|string|max:255',
            'notes' => 'nullable|string|max:1000',
        ]);

        $package = CateringPackage::where('available', true)->findOrFail($data['package_id']);

        if ((float) $data['quantity'] < (float) $package->min_quantity) {
            return back()->with('error', "Minimum order for {$package->name} is {$package->min_quantity} {$package->unit}(s).")->withInput();
        }

        $total = round((float) $data['quantity'] * (float) $package->price_per_unit, 2);
        $eventDate = \Carbon\Carbon::parse($data['event_date'])->format('D j M Y');

        $order = Order::create([
            'code' => 'CTR-' . strtoupper(Str::random(6)),
            'customer_name' => $data['name'],
            'type' => 'catering',
            'location' => $data['address'] ?? null,
            'status' => 'pending',
            'payment_status' => 'unpaid',
            'subtotal' => $total,
            'total' => $total,
            'notes' => "Catering: {$data['quantity']} {$package->unit}(s) of {$package->name} for {$eventDate}."
                . (! empty($data['notes']) ? ' ' . $data['notes'] : '') . " Contact: {$data['phone']}"
                . (! empty($data['email']) ? ' / ' . $data['email'] : ''),
            'placed_at' => now(),
        ]);

        $order->items()->create([
            'name' => "{$data['quantity']} {$package->unit} — {$package->name}",
            'qty' => 1,
            'price' => $total,
            'total' => $total,
            'station' => 'kitchen',
            'status' => 'pending',
            'est_minutes' => 60,
        ]);

        return view('site.catering.confirmed', compact('order', 'package'));
    }
}
