<?php

namespace App\Http\Controllers\authentications;

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

class LoginBasic extends Controller
{
  public function index()
  {
    $pageConfigs = ['myLayout' => 'blank'];
    return view('content.authentications.auth-login-basic', ['pageConfigs' => $pageConfigs]);
  }

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

    $remember = $request->boolean('remember');

    if (!Auth::attempt($credentials, $remember)) {
      throw ValidationException::withMessages([
        'email' => 'Credenciales inválidas.',
      ]);
    }

    $request->session()->regenerate();

    if (!$request->user()->is_active) {
      Auth::logout();
      $request->session()->invalidate();
      $request->session()->regenerateToken();

      throw ValidationException::withMessages([
        'email' => 'Tu cuenta está desactivada.',
      ]);
    }

    $user = $request->user();

    if (in_array($user->role, User::adminRoles(), true)) {
      return redirect()->to(PermissionCatalog::firstAccessibleRouteFor($user));
    }

    return redirect()->intended(PermissionCatalog::firstAccessibleRouteFor($user));
  }

  public function logout(Request $request)
  {
    Auth::logout();

    $request->session()->invalidate();
    $request->session()->regenerateToken();

    return redirect()->route('login');
  }
}
