<?php

namespace App\Http\Controllers;

use App\Models\Magasin;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class PersonnelController extends Controller
{
    public function index()
    {
        $personnel = User::query()
            ->with('magasin:id,nom')
            ->where(function ($q) {
                $q->whereNotNull('poste')
                    ->orWhereNotNull('telephone')
                    ->orWhereNotNull('magasin_id')
                    ->orWhereNotNull('matricule');
            })
            ->latest()
            ->paginate(10);

        $magasins = Magasin::query()
            ->whereDisabled(false)
            ->orderBy('nom')
            ->get(['id', 'nom']);

        return view('personnel.index', compact('personnel', 'magasins'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            // 'matricule' => ['nullable', 'string', 'max:255', 'unique:users,matricule'],
            'telephone' => ['required', 'string', 'min:8', 'max:50'],
            'poste' => ['nullable', 'string', 'max:100'],
            'magasin_id' => ['required', 'exists:magasins,id'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        $validated['password'] = Hash::make($validated['password']);

        $user = User::create($validated);

        // Assignation du rôle Gérant
        $user->assignRole('Gérant');




        return redirect()->route('personnel.index')->with('success', 'Gérant créé avec succès');
    }

    public function update(Request $request, string $id)
    {
        $user = User::query()->findOrFail($id);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'email', 'max:255', Rule::unique('users', 'email')->ignore($user->id)],
            'telephone' => ['required', 'string', 'min:8', 'max:50'],
            'poste' => ['nullable', 'string', 'max:100'],
            'magasin_id' => ['required', 'exists:magasins,id'],
            'password' => ['nullable', 'string', 'min:8'],
        ]);

        if (empty($validated['password'])) {
            unset($validated['password']);
        }

        $user->update($validated);

        return redirect()->route('personnel.index')->with('success', 'Modification effectuée avec succès');
    }

    public function destroy(string $id)
    {
        $user = User::query()->findOrFail($id);
        $user->delete();

        return redirect()->route('personnel.index')->with('success', 'Suppression effectuée avec succès');
    }
}