<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Staff;
use App\Models\StaffType;
use App\Models\Shift;
use App\Models\IdCardType;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Spatie\Permission\Models\Role;
use App\Models\User;

class StaffController 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()
    {
        $staff = Staff::with(['staffType', 'shift', 'idCardType'])->paginate(10);
        return view('backend.staff.index', compact('staff'));
    }

    public function create()
    {
        $staffTypes = StaffType::all();
        $shifts = Shift::all();
        $idCardTypes = IdCardType::all();
        $roles = Role::all();
        
        return view('backend.staff.create', compact('staffTypes', 'shifts', 'idCardTypes', 'roles'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'required|email|unique:staff,email',
            'contact_no' => 'required|string|max:20',
            'id_card_type' => 'required|exists:id_card_types,id_card_type_id',
            'id_card_no' => 'required|string|max:20',
            'address' => 'required|string|max:255',
            'staff_type_id' => 'required|exists:staff_types,staff_type_id',
            'role_id' => 'required|exists:roles,id',
            'shift_id' => 'required|exists:shifts,shift_id',
            'salary' => 'nullable|numeric|min:0',
            'username' => 'required|string|max:15|unique:users,name',
            'password' => 'required|string|min:6',
        ]);

        // Create staff member
        $staffId = DB::table('staff')->insertGetId([
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'email' => $request->email,
            'contact_no' => $request->contact_no,
            'id_card_type' => $request->id_card_type,
            'id_card_no' => $request->id_card_no,
            'address' => $request->address,
            'staff_type_id' => $request->staff_type_id,
            'role_id' => $request->role_id,
            'shift_id' => $request->shift_id,
            'salary' => $request->salary,
            'username' => $request->username,
            'password' => bcrypt($request->password),
        ]);

        // Create user entry
        $user = User::create([
            'name' => $request->username,
            'email' => $request->email,
            'username' => $request->username,
            'password' => bcrypt($request->password),
        ]);

        // Assign role using the simple method
        $selectedRole = Role::find($request->role_id);
        $user->assignRole($selectedRole->name);

        return redirect()->route('staff.index')->with('success', 'Staff member added successfully!');
    }

    public function show(Staff $staff)
    {
        $staff->load(['staffType', 'shift', 'idCardType']);
        return view('backend.staff.show', compact('staff'));
    }

    public function edit(Staff $staff)
    {
        $staffTypes = StaffType::all();
        $shifts = Shift::all();
        $idCardTypes = IdCardType::all();
        $roles = Role::all();
        
        return view('backend.staff.edit', compact('staff', 'staffTypes', 'shifts', 'idCardTypes', 'roles'));
    }

    public function update(Request $request, Staff $staff)
    {
        // dd($request->role_id);


        $request->validate([
            'first_name' => 'required|string|max:100',
            'last_name' => 'required|string|max:100',
            'email' => 'required|email|unique:staff,email,' . $staff->emp_id . ',emp_id',
            'contact_no' => 'required|string|max:20',
            'id_card_type' => 'required|exists:id_card_types,id_card_type_id',
            'id_card_no' => 'required|string|max:20',
            'address' => 'required|string|max:255',
            'staff_type_id' => 'required|exists:staff_types,staff_type_id',
            'role_id' => 'required|exists:roles,id',
            'shift_id' => 'required|exists:shifts,shift_id',
            'salary' => 'nullable|numeric|min:0',
            'username' => 'required|string|max:15',
            'password' => 'nullable|string|min:6',
        ]);

        // Update staff member
        DB::table('staff')
            ->where('emp_id', $staff->emp_id)
            ->update([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => $request->email,
                'contact_no' => $request->contact_no,
                'id_card_type' => $request->id_card_type,
                'id_card_no' => $request->id_card_no,
                'address' => $request->address,
                'staff_type_id' => $request->staff_type_id,
                'role_id' => $request->role_id,
                'shift_id' => $request->shift_id,
                'salary' => $request->salary,
                'password' => $request->password ? bcrypt($request->password) : $staff->password,
            ]);

        // Update user entry
        $user = User::where('email', $staff->email)->first();
        if ($user) {
            $userData = [
                'name' => $request->first_name, // Use username as name
                'email' => $request->email,
            ];

            if ($request->password) {
                $userData['password'] = bcrypt($request->password);
            }

            $user->update($userData);

            // Assign role using the new method
            $selectedRole = Role::find($request->role_id);
            $user->assignRole($selectedRole->name);
        }

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

    public function destroy(Staff $staff)
    {
        DB::table('staff')->where('emp_id', $staff->emp_id)->delete();
        return redirect()->route('staff.index')->with('success', 'Staff member deleted successfully!');
    }
}
