<?php

namespace App\Http\Controllers;

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

class BK_UserController extends Controller
{
    public function index()
    {
        //$utenti = User::with('azienda')->paginate(10);
        $utenti = User::all();
        return view('backend.users.index', compact('utenti'));
    }

    public function edit(User $user)
    {
        $utente = User::find($user)->firstOrFail();
        $aziende = Azienda::all();
        return view('backend.users.show', compact('utente', 'aziende'));
    }

    public function create()
    {
        $aziende = Azienda::all();
        return view('backend.users.create', compact('aziende'));
    }


    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'surname' => 'required|string|max:255',
            'piva' => 'required|string|max:11',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:6',
            'azienda_id' => 'nullable|exists:aziende,id',
        ]);

        // Genera codice personale
        $codicePersonale = $this->generaCodicePersonale($request->surname);

        User::create([
            'name' => $request->name,
            'surname' => $request->surname,
            'piva' => $request->piva,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'azienda_id' => $request->azienda_id,
            'codice_personale' => $codicePersonale,
        ]);

        return redirect()->route('backend.users.index')->with('success', 'Utente creato con successo.');
    }

    // Altri metodi: show, edit, update, destroy
    //update
    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'surname' => 'required|string|max:255',
            'piva' => 'required|string|max:11',
            'email' => 'required|email|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:6',
            'azienda_id' => 'nullable|exists:aziende,id',
        ]);

        $user->update($request->all());

        return redirect()->route('backend.users.index')->with('success', 'Utente aggiornato con successo.');
    }
}
