<?php

namespace App\Livewire\Auth;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Livewire\Component;

class ResetPassword extends Component
{
    public string $token                = '';
    public string $email                = '';
    public string $password             = '';
    public string $password_confirmation = '';
    public string $error                = '';

    public function mount(string $token): void
    {
        $this->token = $token;
        $this->email = request()->query('email', '');
    }

    public function resetPassword()
    {
        $this->validate([
            'password' => 'required|min:8|confirmed',
        ]);

        $record = DB::table('password_reset_tokens')
            ->where('email', $this->email)
            ->first();

        if (!$record || !Hash::check($this->token, $record->token)) {
            $this->error = 'Ungültiger oder abgelaufener Link.';
            return;
        }

        if (Carbon::parse($record->created_at)->diffInMinutes(now()) > 60) {
            $this->error = 'Link abgelaufen. Bitte neu anfordern.';
            return;
        }

        User::where('email', $this->email)
            ->update(['password' => Hash::make($this->password)]);

        DB::table('password_reset_tokens')
            ->where('email', $this->email)
            ->delete();

        session()->flash('success', 'Passwort erfolgreich geändert.');
        $this->redirect('/login', navigate: true);
    }

    public function render()
    {
        return view('livewire.auth.reset-password')
            ->layout('layouts.blank');
    }
}
