<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use App\Models\User;


use App\Exceptions\GlobalException; 

use Illuminate\Validation\ValidationException;

class LoginController extends Controller
{
    
    public function login(Request $request)
    {
        try {
            if (!($request->method() === "POST")) {
                return view("login");
            }
    
            $credentials = $request->validate([
                "email" => ["required", "string"],
                "password" => ["required", "string"]
            ]);
    
            $remember = (bool)$request->filled("remember");
    
            // Agregar condición de active = 1
            if (Auth::attempt(array_merge($credentials, ['active' => 1]), $remember)) {
                $request->session()->regenerate();
                return redirect()->intended('/admin/dashboard');
            }else if (Auth::attempt(array_merge([
                "name" => $credentials['email'],
                "password" => $credentials['password']
            ], ['active' => 1]), $remember)) {
                $request->session()->regenerate();
                return redirect()->intended('/admin/dashboard');
            }
    
            // Verificar si el usuario existe pero está inactivo
            $user = User::where('email', $credentials['email'])->orWhere("name", $credentials['email'])->first();
            
            if ($user && $user->active == 0) {
                throw ValidationException::withMessages([
                    "inactive" => __("your account is inactive")
                ]);
            }
    
            throw ValidationException::withMessages([
                "invalid" => __("auth.failed")
            ]);
    
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }


    public function logout()
    {
        Session::flush();
        
        Auth::logout();

        return redirect('/admin/login');
    }
 
}
