<?php

namespace App\Http\Controllers;

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

class PersonnelController extends Controller
{
    public function index()
    {
        $personnel = User::query()
            ->with('magasin:id,nom')
            ->where(function ($q) {
                $q->whereNotNull('telephone')
                    ->orWhereNotNull('magasin_id');
            })
            ->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)
    {
        $request->merge(['email' => $request->input('email') ?: null]);

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

        User::create($validated);

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



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

        $request->merge(['email' => $request->input('email') ?: null]);

        $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'],
            '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', 'Vendeur mis à jour avec succès');
    }

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

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