<?php

namespace App\Http\Controllers;

use App\Models\Apparatus;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Support\Str;

class ApparatusController extends Controller
{
    // List
    public function index()
    {
        $apparatuses = Apparatus::with('category')->latest()->get();
        return view('apparatus.index', compact('apparatuses'));
    }

    // Create form
    public function create()
    {
        $categories = Category::all();
        return view('apparatus.create', compact('categories'));
    }

    // Store
    public function store(Request $request)
    {
        $request->validate([
            'name'        => ['required','string','max:255'],
            'category_id' => ['nullable','exists:categories,id'],
            'slug'        => ['nullable','string','max:50','regex:/^[a-z0-9-]+$/', 'unique:apparatuses,slug'],
        ]);

        // Derive slug if not provided
        $slug = $request->input('slug');
        if (!$slug) {
            // Drop trailing short-codes in parentheses, then slugify
            $base = preg_replace('/\s*\([^)]*\)\s*/', '', $request->name);
            $slug = Str::slug($base);
        }

        // Ensure uniqueness if empty after slugify or collision
        if (!$slug) {
            $slug = 'apparatus';
        }
        $original = $slug;
        $i = 1;
        while (Apparatus::where('slug', $slug)->exists()) {
            $slug = $original.'-'.$i++;
        }

        Apparatus::create([
            'name'        => $request->name,
            'category_id' => $request->category_id,
            'slug'        => $slug, // nullable in DB, but we provide one for consistency
        ]);

        return redirect()->route('apparatus.index')->with('success', 'Apparatus created successfully.');
    }

    // Edit form
    public function edit($id)
    {
        $apparatus  = Apparatus::findOrFail($id);
        $categories = Category::all();
        return view('apparatus.edit', compact('apparatus', 'categories'));
    }

    // Update
    public function update(Request $request, $id)
    {
        $apparatus = Apparatus::findOrFail($id);

        $request->validate([
            'name'        => ['required','string','max:255'],
            'category_id' => ['nullable','exists:categories,id'],
            'slug'        => [
                'nullable','string','max:50','regex:/^[a-z0-9-]+$/',
                Rule::unique('apparatuses','slug')->ignore($apparatus->id),
            ],
        ]);

        $slug = $request->input('slug');

        // If slug left blank, regenerate from (possibly new) name
        if ($slug === null || $slug === '') {
            $base = preg_replace('/\s*\([^)]*\)\s*/', '', $request->name);
            $slug = Str::slug($base) ?: 'apparatus';
        }

        // Keep uniqueness on update as well
        $original = $slug;
        $i = 1;
        while (
            Apparatus::where('slug', $slug)->where('id', '!=', $apparatus->id)->exists()
        ) {
            $slug = $original.'-'.$i++;
        }

        $apparatus->update([
            'name'        => $request->name,
            'category_id' => $request->category_id,
            'slug'        => $slug,
        ]);

        return redirect()->route('apparatus.index')->with('success', 'Apparatus updated successfully.');
    }

    // Delete
    public function destroy($id)
    {
        $apparatus = Apparatus::findOrFail($id);
        $apparatus->delete();

        return redirect()->route('apparatus.index')->with('success', 'Apparatus deleted successfully.');
    }
}
