<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\FoodCart;
use App\Models\FoodMenuItem;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class FoodMenuItemController extends Controller
{
    public function index(FoodCart $foodCart): View
    {
        $this->authorizeOwner($foodCart);

        $items = $foodCart->items()->with('creator')->latest()->get();

        return view('backend.food-menu-items.index', compact('foodCart', 'items'));
    }

    public function create(FoodCart $foodCart): View
    {
        $this->authorizeOwner($foodCart);

        return view('backend.food-menu-items.create', compact('foodCart'));
    }

    public function store(Request $request, FoodCart $foodCart): RedirectResponse
    {
        $this->authorizeOwner($foodCart);

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
            'price' => ['required', 'numeric', 'min:0'],
            'search_tags' => ['nullable', 'string', 'max:500'],
            'is_available' => ['nullable', 'boolean'],
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', 'max:2048'],
        ]);

        $payload = [
            'food_cart_id' => $foodCart->id,
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'price' => $validated['price'],
            'search_tags' => $this->normalizeTags((string) ($validated['search_tags'] ?? '')),
            'is_available' => (bool) ($validated['is_available'] ?? false),
            'created_by' => (int) Auth::id(),
        ];

        if ($request->hasFile('image')) {
            $payload['image'] = $request->file('image')->store('food-menu-items', 'public');
        }

        FoodMenuItem::create($payload);

        return redirect()->route('admin.food-carts.items.index', $foodCart)->with('success', 'Food item added.');
    }

    public function edit(FoodCart $foodCart, FoodMenuItem $item): View
    {
        $this->authorizeOwner($foodCart);
        $this->assertItemBelongsToCart($foodCart, $item);

        return view('backend.food-menu-items.edit', compact('foodCart', 'item'));
    }

    public function update(Request $request, FoodCart $foodCart, FoodMenuItem $item): RedirectResponse
    {
        $this->authorizeOwner($foodCart);
        $this->assertItemBelongsToCart($foodCart, $item);

        $validated = $request->validate([
            'title' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string', 'max:2000'],
            'price' => ['required', 'numeric', 'min:0'],
            'search_tags' => ['nullable', 'string', 'max:500'],
            'is_available' => ['nullable', 'boolean'],
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,webp', 'max:2048'],
        ]);

        $payload = [
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'price' => $validated['price'],
            'search_tags' => $this->normalizeTags((string) ($validated['search_tags'] ?? '')),
            'is_available' => (bool) ($validated['is_available'] ?? false),
        ];

        if ($request->hasFile('image')) {
            if ($item->image) {
                Storage::disk('public')->delete($item->image);
            }
            $payload['image'] = $request->file('image')->store('food-menu-items', 'public');
        }

        $item->update($payload);

        return redirect()->route('admin.food-carts.items.index', $foodCart)->with('success', 'Food item updated.');
    }

    public function destroy(FoodCart $foodCart, FoodMenuItem $item): RedirectResponse
    {
        $this->authorizeOwner($foodCart);
        $this->assertItemBelongsToCart($foodCart, $item);

        if ($item->image) {
            Storage::disk('public')->delete($item->image);
        }

        $item->delete();

        return redirect()->route('admin.food-carts.items.index', $foodCart)->with('success', 'Food item deleted.');
    }

    private function assertItemBelongsToCart(FoodCart $foodCart, FoodMenuItem $item): void
    {
        abort_unless((int) $item->food_cart_id === (int) $foodCart->id, 404);
    }

    private function authorizeOwner(FoodCart $foodCart): void
    {
        /** @var User|null $user */
        $user = Auth::user();

        abort_unless($user && ($user->hasRole('super-admin') || (int) $foodCart->created_by === (int) $user->id), 403);
    }

    private function normalizeTags(string $tags): array
    {
        return collect(explode(',', $tags))
            ->map(fn(string $tag) => trim($tag))
            ->filter()
            ->unique()
            ->values()
            ->all();
    }
}
