<?php

namespace App\Http\Controllers;

use App\Models\Magasin;
use App\Models\User;
use Illuminate\Http\Request;

class PersonnelController extends Controller
{
    /**
     * Liste du personnel (utilisateurs avec magasin).
     */
    public function index()
    {
        $personnel = User::with(['magasin', 'roles'])->latest()->paginate(10);
        $magasins = Magasin::orderBy('nom')->get(['id', 'nom']);
        $roles = ['Administrateur', 'Vendeur'];

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

    /**
     * Enregistrement d'un nouvel employé.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255|unique:users,email',
            'telephone' => 'required|string|max:50',
            'magasin_id' => 'required|exists:magasins,id',
            'role' => 'required|in:Administrateur,Vendeur',
            'password' => 'required|string|min:8',
        ]);

        $role = $validated['role'];
        unset($validated['role']);

        $user = User::create($validated);
        $user->assignRole($role);

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

    /**
     * Mise à jour d'un employé.
     */
    public function update(Request $request, string $id)
    {
        $user = User::findOrFail($id);

        $rules = [
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255|unique:users,email,' . $user->id,
            'telephone' => 'required|string|max:50',
            'magasin_id' => 'required|exists:magasins,id',
            'role' => 'required|in:Administrateur,Vendeur',
        ];

        if ($request->filled('password')) {
            $rules['password'] = 'min:8';
        }

        $validated = $request->validate($rules);

        if ($request->filled('password')) {
            $validated['password'] = $request->password;
        }

        $role = $validated['role'];
        unset($validated['role']);

        $user->update($validated);
        $user->syncRoles([$role]);

        return redirect()->route('personnel.index')->with('success', 'Vendeur mis à jour avec succès.');
    }

    /**
     * Désactiver ou réactiver le compte d'un employé.
     */
    public function toggleActive(string $id)
    {
        $user = User::findOrFail($id);
        $user->update(['is_active' => !$user->is_active]);
        $message = $user->is_active ? 'Compte réactivé.' : 'Compte désactivé.';

        return redirect()->route('personnel.index')->with('success', $message);
    }

    /**
     * Suppression d'un employé.
     */
    public function destroy(string $id)
    {
        $user = User::findOrFail($id);
        $user->delete();

        return redirect()->route('personnel.index')->with('success', 'Vendeur supprimé.');
    }
}