<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\RolePreset;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UtenteController extends Controller
{
    public function index(Request $request)
    {
        $query = User::query();

        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%')
                  ->orWhere('email', 'like', '%' . $request->search . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $utenti = $query->orderBy('name')->paginate(20);
        $rolePresets = RolePreset::all();

        return view('admin.utenti.index', compact('utenti', 'rolePresets'));
    }

    public function create()
    {
        $rolePresets = RolePreset::all();
        return view('admin.utenti.create', compact('rolePresets'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8|confirmed',
            'role_preset_id' => 'nullable|exists:role_presets,id',
            'is_admin' => 'boolean',
            'permissions' => 'nullable|array',
        ]);

        $user = new User();
        $user->name = $validated['name'];
        $user->email = $validated['email'];
        $user->password = Hash::make($validated['password']);
        $user->is_admin = $validated['is_admin'] ?? false;
        $user->status = User::STATUS_ACTIVE;

        if (!empty($validated['role_preset_id'])) {
            $preset = RolePreset::find($validated['role_preset_id']);
            $user->applyRolePreset($preset);
        } elseif (!empty($validated['permissions'])) {
            $user->setPermissions($validated['permissions']);
        }

        $user->save();

        ActivityLog::log('create', 'utenti', 'Creato utente: ' . $user->name, [
            'user_id' => $user->id,
            'email' => $user->email,
        ]);

        return redirect('/admin/utenti')->with('success', 'Utente creato.');
    }

    public function edit($id)
    {
        $user = User::findOrFail($id);
        $rolePresets = RolePreset::all();
        return view('admin.utenti.edit', compact('user', 'rolePresets'));
    }

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

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'password' => 'nullable|min:8|confirmed',
            'role_preset_id' => 'nullable|exists:role_presets,id',
            'is_admin' => 'boolean',
            'status' => 'required|in:active,suspended,pending',
            'permissions' => 'nullable|array',
        ]);

        $old = $user->toArray();

        $user->name = $validated['name'];
        $user->email = $validated['email'];
        $user->is_admin = $validated['is_admin'] ?? false;
        $user->status = $validated['status'];

        if (!empty($validated['password'])) {
            $user->password = Hash::make($validated['password']);
        }

        if (!empty($validated['role_preset_id'])) {
            $preset = RolePreset::find($validated['role_preset_id']);
            $user->applyRolePreset($preset);
        } elseif (isset($validated['permissions'])) {
            $user->setPermissions($validated['permissions']);
        }

        $user->save();

        ActivityLog::log('update', 'utenti', 'Modificato utente: ' . $user->name, [
            'user_id' => $user->id,
            'old' => $old,
            'new' => $user->toArray(),
        ]);

        return redirect('/admin/utenti')->with('success', 'Utente aggiornato.');
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);

        if ($user->id === auth()->id()) {
            return redirect('/admin/utenti')->with('error', 'Non puoi eliminare te stesso.');
        }

        if ($user->isSuperAdmin()) {
            $adminCount = User::where('is_admin', true)->count();
            if ($adminCount <= 1) {
                return redirect('/admin/utenti')->with('error', 'Impossibile eliminare l\'ultimo amministratore.');
            }
        }

        $userName = $user->name;

        ActivityLog::log('delete', 'utenti', 'Eliminato utente: ' . $userName, [
            'user_id' => $id,
            'deleted' => $user->toArray(),
        ]);

        $user->delete();

        return redirect('/admin/utenti')->with('success', 'Utente eliminato.');
    }
}