<?php

declare(strict_types=1);

namespace App\Http\Controllers;

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

class PromoController extends Controller
{
    public function index(): Response
    {
        $promos = Promo::with(['product'])->latest()->get();
        $products = Product::select('id', 'name')->where('is_active', true)->get();

        return Inertia::render('CafePOS/Promos/Index', [
            'promos' => $promos,
            'products' => $products,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'in:percent,nominal,bogo'],
            'value' => ['required', 'numeric', 'min:0'],
            'min_purchase' => ['required', 'numeric', 'min:0'],
            'product_id' => ['nullable', 'integer', 'exists:products,id'],
            'is_active' => ['required', 'boolean'],
        ]);

        Promo::create($request->only(['name', 'type', 'value', 'min_purchase', 'product_id', 'is_active']));

        return redirect()->back()->with('success', 'Promo created successfully.');
    }

    public function update(Request $request, Promo $promo): RedirectResponse
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'in:percent,nominal,bogo'],
            'value' => ['required', 'numeric', 'min:0'],
            'min_purchase' => ['required', 'numeric', 'min:0'],
            'product_id' => ['nullable', 'integer', 'exists:products,id'],
            'is_active' => ['required', 'boolean'],
        ]);

        $promo->update($request->only(['name', 'type', 'value', 'min_purchase', 'product_id', 'is_active']));

        return redirect()->back()->with('success', 'Promo updated successfully.');
    }

    public function destroy(Promo $promo): RedirectResponse
    {
        $promo->delete();
        return redirect()->back()->with('success', 'Promo deleted successfully.');
    }
}
