<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\Ingredient;
use App\Models\Modifier;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ModifierController extends Controller
{
    /**
     * Display a listing of the modifiers (add-ons).
     */
    public function index(Request $request): Response
    {
        $search = $request->input('search');

        $modifiers = Modifier::with(['ingredient', 'products'])
            ->when($search, function ($query, $search) {
                $query->where('name', 'like', "%{$search}%");
            })
            ->latest()
            ->paginate(10)
            ->withQueryString();

        $ingredients = Ingredient::select('id', 'name', 'unit')->get();
        $products = Product::select('id', 'name', 'price', 'category')->get();

        return Inertia::render('CafePOS/Modifiers/Index', [
            'modifiers' => $modifiers,
            'ingredients' => $ingredients,
            'products' => $products,
            'filters' => [
                'search' => $search,
            ],
        ]);
    }

    /**
     * Store a newly created modifier in storage.
     */
    public function store(Request $request): RedirectResponse
    {
        if (app()->environment('demo')) {
            return redirect()->back()->with('error', 'Mode Demo Aktif: Pembuatan add-on baru tidak diizinkan di mode demo.');
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:modifiers,name'],
            'price' => ['required', 'numeric', 'min:0'],
            'ingredient_id' => ['nullable', 'integer', 'exists:ingredients,id'],
            'usage_qty' => ['nullable', 'required_with:ingredient_id', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'product_ids' => ['nullable', 'array'],
            'product_ids.*' => ['integer', 'exists:products,id'],
        ]);

        $modifier = Modifier::create([
            'name' => $request->name,
            'price' => $request->price,
            'ingredient_id' => $request->ingredient_id,
            'usage_qty' => $request->ingredient_id ? $request->usage_qty : null,
            'is_active' => $request->is_active,
        ]);

        // Sync product relations
        if ($request->has('product_ids')) {
            $modifier->products()->sync($request->product_ids);
        }

        activity()
            ->performedOn($modifier)
            ->causedBy($request->user())
            ->log("Created add-on (modifier): {$modifier->name} with price Rp " . number_format((float)$modifier->price, 0, ',', '.'));

        return redirect()->back()->with('success', 'Add-on berhasil dibuat.');
    }

    /**
     * Update the specified modifier in storage.
     */
    public function update(Request $request, Modifier $modifier): RedirectResponse
    {
        if (app()->environment('demo')) {
            return redirect()->back()->with('error', 'Mode Demo Aktif: Pengubahan add-on tidak diizinkan di mode demo.');
        }

        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:modifiers,name,' . $modifier->id],
            'price' => ['required', 'numeric', 'min:0'],
            'ingredient_id' => ['nullable', 'integer', 'exists:ingredients,id'],
            'usage_qty' => ['nullable', 'required_with:ingredient_id', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'product_ids' => ['nullable', 'array'],
            'product_ids.*' => ['integer', 'exists:products,id'],
        ]);

        $modifier->update([
            'name' => $request->name,
            'price' => $request->price,
            'ingredient_id' => $request->ingredient_id,
            'usage_qty' => $request->ingredient_id ? $request->usage_qty : null,
            'is_active' => $request->is_active,
        ]);

        // Sync product relations
        if ($request->has('product_ids')) {
            $modifier->products()->sync($request->product_ids);
        } else {
            $modifier->products()->detach();
        }

        activity()
            ->performedOn($modifier)
            ->causedBy($request->user())
            ->log("Updated add-on (modifier): {$modifier->name}");

        return redirect()->back()->with('success', 'Add-on berhasil diperbarui.');
    }

    /**
     * Remove the specified modifier from storage.
     */
    public function destroy(Modifier $modifier): RedirectResponse
    {
        if (app()->environment('demo')) {
            return redirect()->back()->with('error', 'Mode Demo Aktif: Penghapusan add-on tidak diizinkan di mode demo.');
        }

        $name = $modifier->name;
        $modifier->products()->detach();
        $modifier->delete();

        activity()
            ->log("Deleted add-on (modifier): {$name}");

        return redirect()->back()->with('success', 'Add-on berhasil dihapus.');
    }
}
