<?php

namespace App\Http\Controllers;

use App\Models\Designation;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Toastr;

class DesignationController extends Controller
{
    public function index()
    {
        // Fetching all designations and departments
        $designations = Designation::all();
        $departments = Department::all();
        return view('employees.designations', compact('designations', 'departments'));
    }

    public function create()
    {
        // Fetching departments for the create form
        $departments = Department::all();
        return view('employees.create_designation', compact('departments'));
    }

    public function store(Request $request)
    {
        // Validating the incoming request
        $request->validate([
            'designation' => 'required|string|max:255',
            'department' => 'required|string|max:255',
        ]);

        // Creating a new designation
        $designation = new Designation();
        $designation->designation = $request->designation;
        $designation->department = $request->department;
        $designation->save();

        // Returning with success message
        return redirect()->route('form/designations/page')->with('success', 'Designation successfully added!');
    }

    public function edit($id)
    {
        // Fetching the specific designation and departments for editing
        $designation = Designation::findOrFail($id);
        $departments = Department::all();
        return view('employees.edit_designation', compact('designation', 'departments'));
    }

    public function update(Request $request, $id)
    {
 
       
        $request->validate([
            'designation' => 'required|string|max:255',
            'department' => 'required|string|max:255',
        ]);
     
        // Find the designation by its ID
        $designation = Designation::find($id);
     
        if (!$designation) {
            return redirect()->back()->with('error', 'Designation not found!');
        }
     
        // Update the designation details
        $designation->designation = $request->input('designation');
        $designation->department = $request->input('department');
        $designation->save();
     
        return redirect()->route('form/designations/page')->with('success', 'Designation updated successfully!');
    }


    public function destroy($id)
    {
        // Deleting the designation
        $designation = Designation::findOrFail($id);
        $designation->delete();

        // Returning with success message
        return redirect()->route('form/designations/page')->with('success', 'Designation deleted successfully!');
    }
}
