<?php

namespace App\Http\Controllers\Settings;

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

class PriorityController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $priorities = Priority::query()
            ->latest()
            ->paginate(10)
            ->through(fn ($p) => [
                'id' => $p->id,
                'name' => $p->name,
            ]);

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

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

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

        Priority::create($data);

        return back()->with('success', 'Приоритет добавлен');
    }

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

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

        return Inertia::render('settings/Priorities', [
            'priorities' => Priority::query()->latest()->paginate(10)->withQueryString(),
            'editingPriority' => $priority,
        ]);
    }

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

        $priority = Priority::findOrFail($id);
        $priority->update($request->only('name'));

        return redirect()->route('settings.priorities.index')
            ->with('success', 'Приоритет успешно обновлён');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Priority $priority)
    {
        $priority->delete();
        return back();
    }
}
