<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

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

    public function login(Request $request): RedirectResponse
    {
        $datos = $request->validate([
            'usuario' => 'required|string|max:60',
            'password' => 'required|string',
        ]);

        $recordar = (bool) $request->boolean('recordar');
        $credenciales = [
            'usuario' => $datos['usuario'],
            'password' => $datos['password'],
            'activo' => 1,
        ];

        if (!Auth::attempt($credenciales, $recordar)) {
            throw ValidationException::withMessages([
                'usuario' => 'Credenciales inválidas o usuario inactivo.',
            ]);
        }

        $request->session()->regenerate();
        $u = Auth::user();
        $u->ultimo_acceso = now();
        $u->save();

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

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