<?php

use Livewire\Component;
use Livewire\Attributes\Layout;

new #[Layout('layouts::auth', ['title' => 'Admin Login'])] class extends Component {
    public string $email = '';
    public string $password = '';

    protected function rules(): array
    {
        return [
            'email' => 'required|email',
            'password' => 'required|string',
        ];
    }

    protected function messages(): array
    {
        return [
            'email.required' => 'We need your email to sign you in.',
            'email.email' => 'That doesn’t look like a valid email address.',
            'password.required' => 'Please enter your password to continue.',
        ];
    }

    public function loginAdmin()
    {
        $this->validate();

        $key = Str::lower($this->email) . '|' . request()->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            $this->addError('email', 'Too many login attempts. Please try again later.');
            return;
        }

        if (
            !Auth::guard('admin')->attempt([
                'email' => $this->email,
                'password' => $this->password,
            ])
        ) {
            RateLimiter::hit($key, 60);
            $this->addError('email', 'These credentials do not match our records.');
            return;
        }

        RateLimiter::clear($key);

        session()->regenerate();

        Auth::guard('admin')
            ->user()
            ->update([
                'last_login_at' => now(),
            ]);

        return redirect()->route('admin.dashboard');
    }
};
?>

<div class="flex flex-col gap-6">
    <x-auth-header :title="__('Access Admin Dashboard')" :description="__('Enter your email and password below to log in')" />

    <!-- Session Status -->
    <x-auth-session-status class="text-center" :status="session('status')" />

    <form wire:submit.prevent="loginAdmin" class="flex flex-col gap-6">

        <!-- Email Address -->
        <flux:input icon="envelope" wire:model.defer="email" :label="__('Email address')" :value="old('email')"
            type="email" required autofocus autocomplete="email" placeholder="email@example.com" />

        <!-- Password -->
        <div class="relative">
            <flux:input icon="key" wire:model.defer="password" :label="__('Password')" type="password" required
                autocomplete="current-password" :placeholder="__('Password')" viewable />
        </div>

        <div class="flex items-center justify-end">
            <flux:button variant="primary" type="submit" color="emerald" class="w-full" data-test="login-button">
                {{ __('Login Dashboard') }}
            </flux:button>
        </div>

        <p class="text-center text-gray-400 text-sm mt-4">
            &copy; {{ date('Y') }} {{ config('app.name') }}. All rights reserved.
        </p>
    </form>
</div>
