<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Mail\PasswordResetMail;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Http\Response;

class ForgotPasswordController extends Controller
{

    public function sendResetLinkEmail(Request $request)
    {
        $request->validate(['email' => 'required|email']);
        $email = $request->input('email');

        $user = User::where('email', $email)->first();
        if (! $user) {
            return response()->json(['error' => "Lo sentimos, verifica tu correo."], 500);
        }
        $plainToken = bin2hex(random_bytes(64));

        DB::table('password_reset_tokens')->updateOrInsert(
            ['email' => $email],
            [
                'token'      => Hash::make($plainToken),
                'created_at' => Carbon::now(),
            ]
        );

        Mail::to($email)->send(new PasswordResetMail($plainToken, $email));

        return response()->json([
            'message' => "Te hemos enviado un enlace de restablecimiento por correo.",
        ], Response::HTTP_OK);
    }
}
