<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\StaffType;
use Illuminate\Support\Facades\DB;

class StaffTypeController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view-staff')->only(['index', 'show']);
        $this->middleware('permission:create-staff')->only(['create', 'store']);
        $this->middleware('permission:edit-staff')->only(['edit', 'update']);
        $this->middleware('permission:delete-staff')->only(['destroy']);
    }

    public function index()
    {
        $staffTypes = StaffType::paginate(10);
        return view('backend.staff-types.index', compact('staffTypes'));
    }

    public function create()
    {
        return view('backend.staff-types.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'staff_type' => 'required|string|max:100|unique:staff_types,staff_type',
        ]);

        DB::table('staff_types')->insert([
            'staff_type' => $request->staff_type
        ]);

        return redirect()->route('staff-types.index')->with('success', 'Staff type created successfully!');
    }

    public function edit(StaffType $staffType)
    {
        return view('backend.staff-types.edit', compact('staffType'));
    }

    public function update(Request $request, StaffType $staffType)
    {
        $request->validate([
            'staff_type' => 'required|string|max:100|unique:staff_types,staff_type,' . $staffType->staff_type_id . ',staff_type_id',
        ]);

        DB::table('staff_types')
            ->where('staff_type_id', $staffType->staff_type_id)
            ->update(['staff_type' => $request->staff_type]);

        return redirect()->route('staff-types.index')->with('success', 'Staff type updated successfully!');
    }

    public function destroy(StaffType $staffType)
    {
        // Check if staff type is being used
        $staffCount = DB::table('staff')->where('staff_type_id', $staffType->staff_type_id)->count();
        
        if ($staffCount > 0) {
            return back()->with('error', 'Cannot delete staff type. It is being used by ' . $staffCount . ' staff member(s).');
        }

        DB::table('staff_types')->where('staff_type_id', $staffType->staff_type_id)->delete();
        
        return redirect()->route('staff-types.index')->with('success', 'Staff type deleted successfully!');
    }
} 