<?php

namespace App\Http\Controllers;

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

class IdCardTypeController 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()
    {
        $idCardTypes = IdCardType::paginate(10);
        return view('backend.id-card-types.index', compact('idCardTypes'));
    }

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

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

        DB::table('id_card_types')->insert([
            'id_card_type' => $request->id_card_type
        ]);

        return redirect()->route('id-card-types.index')->with('success', 'ID Card type created successfully!');
    }

    public function edit(IdCardType $idCardType)
    {
        return view('backend.id-card-types.edit', compact('idCardType'));
    }

    public function update(Request $request, IdCardType $idCardType)
    {
        $request->validate([
            'id_card_type' => 'required|string|max:100|unique:id_card_types,id_card_type,' . $idCardType->id_card_type_id . ',id_card_type_id',
        ]);

        DB::table('id_card_types')
            ->where('id_card_type_id', $idCardType->id_card_type_id)
            ->update(['id_card_type' => $request->id_card_type]);

        return redirect()->route('id-card-types.index')->with('success', 'ID Card type updated successfully!');
    }

    public function destroy(IdCardType $idCardType)
    {
        // Check if id card type is being used
        $staffCount = DB::table('staff')->where('id_card_type', $idCardType->id_card_type_id)->count();
        
        if ($staffCount > 0) {
            return back()->with('error', 'Cannot delete ID Card type. It is being used by ' . $staffCount . ' staff member(s).');
        }

        DB::table('id_card_types')->where('id_card_type_id', $idCardType->id_card_type_id)->delete();
        
        return redirect()->route('id-card-types.index')->with('success', 'ID Card type deleted successfully!');
    }
} 