<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function showLoginForm()
    {
        return view('auth.login');
    }

    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        $user = User::where('email', $credentials['email'])->first();

        if ($user && $user->status === 'suspended') {
            throw ValidationException::withMessages([
                'email' => ['Questo account è sospeso. Contatta un amministratore.'],
            ]);
        }

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();

            ActivityLog::logLogin();

            return redirect()->intended('/dashboard');
        }

        throw ValidationException::withMessages([
            'email' => ['Le credenziali fornite non sono corrette.'],
        ]);
    }

    public function showRegisterForm()
    {
        return view('auth.register');
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $isFirstUser = User::count() === 0;

        $defaultPermissions = [
            'individui' => 1,
            'gruppi' => 1,
            'eventi' => 1,
            'documenti' => 1,
            'mailing' => 1,
            'viste' => 1,
            'report' => 0,
            'settings' => 0,
        ];

        if ($isFirstUser) {
            $defaultPermissions = [
                'individui' => 2,
                'gruppi' => 2,
                'eventi' => 2,
                'documenti' => 2,
            'mailing' => 2,
            'viste' => 2,
            'report' => 0,
            'settings' => 0,
        ];
        }

        $user = User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'is_admin' => $isFirstUser,
            'status' => User::STATUS_ACTIVE,
            'permissions' => $defaultPermissions,
        ]);

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

        Auth::login($user);

        return redirect('/dashboard');
    }

    public function logout(Request $request)
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();
        return redirect('/');
    }
}