<?php

namespace App\Http\Controllers\Admin\Employee;

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

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

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

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

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

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

        $departments = Department::orderBy('id', 'desc')->get();

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

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

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

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

        $departments = Department::orderBy('id', 'desc')->get();

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

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

        $departments = Department::orderBy('id', 'desc')->get();

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


