<?php

namespace App\Http\Controllers\Epelcon;

use App\Http\Controllers\Concerns\HandlesImageUploads;
use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\CateringPackage;
use App\Models\Chef;
use App\Models\Cuisine;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CateringAdminController extends Controller
{
    use HandlesImageUploads;

    public const UNITS = ['litre', 'portion', 'tray', 'whole', 'kg', 'pack'];
    public const CATEGORIES = ['Soups', 'Rice & Grains', 'Grills & BBQ', 'Proteins', 'Small Chops', 'Whole Animal', 'Other'];

    public function index(Request $request)
    {
        $packages = CateringPackage::with(['chef', 'cuisine'])
            ->when($request->filled('q'), fn ($q) => $q->where('name', 'like', '%' . $request->q . '%'))
            ->orderByDesc('featured')->orderBy('name')
            ->paginate(20)->withQueryString();

        $counts = [
            'total' => CateringPackage::count(),
            'available' => CateringPackage::where('available', true)->count(),
            'featured' => CateringPackage::where('featured', true)->count(),
        ];

        $chefs = Chef::where('status', 'active')->orderBy('name')->get(['id', 'name']);
        $cuisines = Cuisine::orderBy('name')->get(['id', 'name']);

        return view('epelcon.catering.index', compact('packages', 'counts', 'chefs', 'cuisines'))
            ->with(['units' => self::UNITS, 'categories' => self::CATEGORIES]);
    }

    public function store(Request $request)
    {
        $data = $this->validatePackage($request);
        $data['slug'] = Str::slug($data['name']) . '-' . Str::lower(Str::random(4));

        if ($image = $this->saveImage($request, 'image', 'catering')) {
            $data['image'] = $image;
        }

        CateringPackage::create($data);
        ActivityLog::record('created catering package', 'catering', $data['name']);

        return back()->with('success', "“{$data['name']}” added to catering.");
    }

    public function update(Request $request, CateringPackage $package)
    {
        $data = $this->validatePackage($request);

        if ($image = $this->saveImage($request, 'image', 'catering')) {
            $data['image'] = $image;
        }

        $package->update($data);

        return back()->with('success', 'Package updated.');
    }

    public function toggle(CateringPackage $package)
    {
        $package->update(['available' => ! $package->available]);

        return back()->with('success', $package->name . ($package->available ? ' is now available.' : ' hidden.'));
    }

    public function destroy(CateringPackage $package)
    {
        $name = $package->name;
        $package->delete();

        return back()->with('success', "“{$name}” removed.");
    }

    private function validatePackage(Request $request): array
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'chef_id' => 'nullable|exists:chefs,id',
            'cuisine_id' => 'nullable|exists:cuisines,id',
            'description' => 'nullable|string',
            'category' => 'nullable|string|max:30',
            'unit' => 'required|in:' . implode(',', self::UNITS),
            'price_per_unit' => 'required|numeric|min:0',
            'min_quantity' => 'required|numeric|min:0.5',
            'lead_time_hours' => 'nullable|integer|min:0|max:336',
            'available' => 'nullable|boolean',
            'featured' => 'nullable|boolean',
        ]);

        $data['lead_time_hours'] = $data['lead_time_hours'] ?? 24;
        $data['available'] = $request->boolean('available', true);
        $data['featured'] = $request->boolean('featured');

        return $data;
    }
}
