<?php

namespace App\Livewire\Auth;

use App\Models\User;
use App\Rules\IsValidPhoneNumber;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;

class PasswordResetForm extends Component
{
    public $phone = '';

    public $password = '';

    public $password_confirmation = '';

    public $token = '';

    public $loading = false;

    public $success = false;

    public $error_message = '';

    public function mount($token)
    {
        $this->token = $token;
    }

    public function updated($propertyName)
    {
        $this->resetErrorBag();
        $this->error_message = '';
    }

    public function resetPassword()
    {
        $this->loading = true;
        $this->error_message = '';
        $this->success = false;

        $validator = Validator::make(
            [
                'phone' => $this->phone,
                'password' => $this->password,
                'password_confirmation' => $this->password_confirmation,
            ],
            [
                'phone' => ['required', 'string', new IsValidPhoneNumber, 'exists:users,phone'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
            ],
            [
                'phone.exists' => 'Ce numéro de téléphone n\'est pas enregistré dans notre système.',
                'password.confirmed' => 'La confirmation du mot de passe ne correspond pas.',
                'password.min' => 'Le mot de passe doit contenir au moins 8 caractères.',
            ]
        );

        if ($validator->fails()) {
            foreach ($validator->errors()->all() as $error) {
                $this->addError('form', $error);
            }
            $this->loading = false;

            return;
        }

        try {
            // Check if token exists and is valid
            $resetRecord = DB::table('password_reset_tokens')
                ->where('phone', $this->phone)
                ->first();

            if (! $resetRecord || ! Hash::check($this->token, $resetRecord->token)) {
                $this->error_message = 'Le token de réinitialisation est invalide ou a expiré.';
                $this->loading = false;

                return;
            }

            // Check if token is not expired (1 hour)
            if (now()->diffInMinutes($resetRecord->created_at) > 60) {
                DB::table('password_reset_tokens')->where('phone', $this->phone)->delete();
                $this->error_message = 'Le token de réinitialisation a expiré.';
                $this->loading = false;

                return;
            }

            // Update user password
            $user = User::where('phone', $this->phone)->first();
            $user->update([
                'password' => Hash::make($this->password),
                'failed_login_attempts' => 0, // Reset failed attempts
                'locked_until' => null, // Unlock account
            ]);

            // Delete the reset token
            DB::table('password_reset_tokens')->where('phone', $this->phone)->delete();

            $this->success = true;
            $this->loading = false;

            // Redirect to login after 3 seconds
            $this->dispatch('redirect-to-login');

        } catch (\Exception $e) {
            $this->error_message = 'Erreur lors de la réinitialisation du mot de passe. Veuillez réessayer.';
            $this->loading = false;
        }
    }

    public function logout(): void
    {
        Auth::logout();
        session()->invalidate();
        session()->regenerateToken();

        $this->redirectRoute('login', navigate: true);
    }

    public function render()
    {
        return view('livewire.auth.password-reset-form');
    }
}
