<?php

namespace App\Http\Controllers;

use App\Departments;
use App\Designations;
use App\Models\Designation;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;

class DesignationController extends Controller
{

    protected string $module = 'Designations';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
        $this->middleware("permission:$module view")->only(['show']);
        $this->middleware("permission:$module add")->only(['create', 'store']);
        $this->middleware("permission:$module edit")->only(['edit', 'update']);
        $this->middleware("permission:$module delete")->only(['destroy']);
    }

    public function index()
    {
        $designations = Designations::with('department', 'creator')->latest()->get();
        return view('designations.index', compact('designations'));
    }

    public function create()
    {
        $departments = Departments::where('status', 'active')->get();
        return view('designations.create', compact('departments'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'department_id' => 'nullable|exists:departments,id',
            'status' => 'required|in:active,inactive',
        ]);

        Designations::create([
            'title' => $request->title,
            'department_id' => $request->department_id,
            'status' => $request->status,
            'created_by' => Auth::id(),
        ]);

        return redirect()->route('designations.index')->with('success', 'Designation created successfully!');
    }

    public function edit($id)
    {
        $dec_id = Crypt::decrypt($id);
        $designation = Designations::findOrFail($dec_id);
        $departments = Departments::where('status', 'active')->get();
        return view('designations.edit', compact('designation', 'departments'));
    }

    public function update(Request $request, $id)
    {
        $dec_id = Crypt::decrypt($id);
        $designation = Designations::findOrFail($dec_id);

        $request->validate([
            'title' => 'required|string|max:255',
            'department_id' => 'nullable|exists:departments,id',
            'status' => 'required|in:active,inactive',
        ]);

        $designation->update([
            'title' => $request->title,
            'department_id' => $request->department_id,
            'status' => $request->status,
        ]);

        return redirect()->route('designations.index')->with('success', 'Designation updated successfully!');
    }

    public function destroy($id)
    {
        $id1 = Crypt::decrypt($id);
        Designations::findOrFail($id1)->delete();
        return redirect()->route('designations.index')->with('success', 'Designation deleted successfully!');
    }
}
