<?php

namespace App\Http\Controllers\Admin\Employee;

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

class DesignationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return Inertia::render('Employee/Designation');
    }

    /**
     * Return all designations (for DataTable).
     */
    public function view()
    {
        $designations = Designation::orderBy('id', 'desc')->get();

        return response()->json(['designations' => $designations]);
    }

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

        Designation::create([
            'name'        => $request->name,
            'description' => $request->description,
            'status'      => $request->status ?? '1',
        ]);

        $designations = Designation::orderBy('id', 'desc')->get();

        return response()->json([
            'success'       => 'Designation created successfully',
            'designations' => $designations,
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $designation = Designation::findOrFail($id);

        $request->validate([
            'name'        => 'required|string|max:255|unique:designations,name,' . $id,
            'description' => 'nullable|string',
            'status'      => 'nullable|string|in:0,1',
        ]);

        $designation->update($request->only([
            'name',
            'description',
            'status',
        ]));

        $designations = Designation::orderBy('id', 'desc')->get();

        return response()->json([
            'success'       => 'Designation updated successfully',
            'designations' => $designations,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        $designation = Designation::findOrFail($id);
        $designation->delete();

        $designations = Designation::orderBy('id', 'desc')->get();

        return response()->json([
            'success'       => 'Designation deleted successfully',
            'designations' => $designations,
        ]);
    }
}
