<?php

namespace App\Livewire;

use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Validate;
use Livewire\Component;

class LoginForm extends Component
{
    #[Validate('required|string')]
    public string $login = '';

    #[Validate('required|string')]
    public string $password = '';

    #[Validate('boolean')]
    public bool $remember = false;


    /**
     * Attempt to authenticate the request's credentials.
     */
    public function doLogin()
    {
        $this->validate();

        // Find user by email, phone, student_id, or username
        $user = User::where('email', $this->login)
            ->orWhere('phone', $this->login)
            ->orWhere('student_id', $this->login)
            ->orWhere('username', $this->login)
            ->first();

        // Check if user exists and password is correct
        if (!$user || !Hash::check($this->password, $user->password)) {
            throw ValidationException::withMessages([
                'login' => 'Hello! Please check again, it seems your login details are incorrect.',
            ]);
        }

        // Check if user account is active
        if (!$user->active) {
            throw ValidationException::withMessages([
                'login' => 'Your account has been blocked. Please contact the administrator for assistance.',
            ]);
        }

        // Log the user in
        Auth::login($user, $this->remember);

        // Regenerate session for security
        session()->regenerate();

        // Redirect to dashboard with full page reload
        return $this->redirect(route('dashboard'));
    }

    public function render()
    {
        return view('livewire.login-form');
    }
}
