<?php

namespace App\Livewire\Auth;

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 Illuminate\Support\Str;
use Livewire\Component;

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

    public $loading = false;

    public $success = false;

    public $error_message = '';

    public function updatedPhone($value)
    {
        $this->resetErrorBag();
        $this->error_message = '';
    }

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

        $validator = Validator::make(
            ['phone' => $this->phone],
            [
                'phone' => ['required', 'string', new IsValidPhoneNumber, 'exists:users,phone'],
            ],
            [
                'phone.exists' => 'Ce numéro de téléphone n\'est pas enregistré dans notre système.',
            ]
        );

        if ($validator->fails()) {
            $this->addError('phone', $validator->errors()->first('phone'));
            $this->loading = false;

            return;
        }

        try {
            // Generate reset token
            $token = Str::random(64);

            // Store token in database
            DB::table('password_reset_tokens')->updateOrInsert(
                ['phone' => $this->phone],
                [
                    'token' => Hash::make($token),
                    'created_at' => now(),
                ]
            );

            // TODO: Send SMS with reset link
            // For now, we'll just show success
            // In production, you'd send an SMS with the reset link

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

        } catch (\Exception $e) {
            $this->error_message = 'Erreur lors de l\'envoi du lien de réinitialisation. 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');
    }
}
