<?php

namespace App\Http\Controllers\User;

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

class DesignationController extends Controller
{
    public function index(Request $request)
    {
        $query = Designation::where('user_id', auth()->id())
            ->latest();

        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . trim($request->search) . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $designations = $query->paginate(15)->withQueryString();

        return view('user.hr.designations.index', compact('designations'));
    }

    public function create()
    {
        return view('user.hr.designations.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name'   => ['required', 'string', 'max:255'],
            'status' => ['required', 'in:active,inactive'],
            'note'   => ['nullable', 'string'],
        ]);

        Designation::create([
            'user_id' => auth()->id(),
            'name'    => $validated['name'],
            'status'  => $validated['status'],
            'note'    => $validated['note'] ?? null,
        ]);

        return redirect()
            ->route('user.hr.designations.index')
            ->with('ok', __('Designation_Controller.designation_created_successfully'));
    }

    public function edit($id)
    {
        $designation = Designation::where('user_id', auth()->id())->findOrFail($id);

        return view('user.hr.designations.edit', compact('designation'));
    }

    public function update(Request $request, $id)
    {
        $designation = Designation::where('user_id', auth()->id())->findOrFail($id);

        $validated = $request->validate([
            'name'   => ['required', 'string', 'max:255'],
            'status' => ['required', 'in:active,inactive'],
            'note'   => ['nullable', 'string'],
        ]);

        $designation->update($validated);

        return redirect()
            ->route('user.hr.designations.index')
            ->with('ok', __('Designation_Controller.designation_updated_successfully'));
    }

    public function destroy($id)
    {
        $designation = Designation::where('user_id', auth()->id())->findOrFail($id);
        $designation->delete();

        return redirect()
            ->route('user.hr.designations.index')
            ->with('ok', __('Designation_Controller.designation_deleted_successfully'));
    }
}