<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;

class NewPasswordController extends Controller
{
    public function create(Request $request): View
    {
        return view('auth.reset-password', ['request' => $request]);
    }

    public function store(Request $request): RedirectResponse
    {
        $request->validate([
            'code' => ['required', 'digits:6'],
            'email' => ['required', 'email'],
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $email = mb_strtolower(trim($request->string('email')->toString()));
        $reset = DB::table('password_reset_tokens')->where('email', $email)->first();
        if (! $reset || ! $reset->created_at || now()->diffInMinutes($reset->created_at) > 15 || ! Hash::check($request->code, $reset->token)) {
            throw ValidationException::withMessages(['code' => 'El código es incorrecto o ya expiró. Solicita uno nuevo.']);
        }

        $user = User::where('email', $email)->firstOrFail();
        $user->forceFill([
            'password' => Hash::make($request->password),
            'remember_token' => Str::random(60),
        ])->save();
        DB::table('password_reset_tokens')->where('email', $email)->delete();
        event(new PasswordReset($user));

        return redirect()->route('login')->with('status', 'Contraseña restablecida correctamente.');
    }
}
