<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\RequestType;
use Illuminate\Http\Request;
use Inertia\Inertia;

class RequestTypeController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $types = RequestType::query()
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return Inertia::render('settings/Types', [
            'types' => $types,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
        ]);

        RequestType::create([
            'name' => $request->name,
        ]);

        return back();
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        $type = RequestType::findOrFail($id);

        return Inertia::render('settings/Types', [
            'types' => RequestType::query()->latest()->paginate(10)->withQueryString(),
            'editingType' => $type,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:request_types,name,' . $id],
        ]);

        $type = RequestType::findOrFail($id);
        $type->update($request->only('name'));

        return redirect()->route('settings.types.index')
            ->with('success', 'Тип заявки успешно обновлён');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(RequestType $type)
    {
        $type->delete();

        return back();
    }
}
