<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\PasswordResetTokens;
use App\Models\Patient;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;
    public function forgotPassword(Request $request)
    {


        $patient = Patient::where('email', $request->email)->first();

        if (!$patient) {
            return response()->json(['message' => 'The specified email cannot be located.'], 404);
        }
        $token = base64_encode(Str::random(60));
        $tokenData = PasswordResetTokens::where('email', $request->email)->first();
        if ($tokenData) {
            PasswordResetTokens::where('email', $request->email)->delete();
        }
        PasswordResetTokens::create([
            'email' => $request->email,
            'token' => $token,
            'created_at' => now()
        ]);

        // Send reset link email
        Mail::send('emails.password_reset', ['token' => $token], function ($message) use ($request) {
            $message->to($request->email);
            $message->subject('Password Reset Request');
        });

        return response()->json(['message' => 'Password reset link sent']);
    }

    public function resetPassword(Request $request)
    {

        $tokenData = PasswordResetTokens::where('token', $request->token)->first();

        if (!$tokenData || !$request->token == $tokenData->token) {
            return response()->json([
                'msg' => "Link Expired",
                'status' => 'error'
            ]);
        }

        $password = $request->get('password');
        $confPassword = $request->get('confirm');
        if ($confPassword != $password) {
            return response()->json([
                'msg' => "Password don no match",
                'status' => 'error'
            ]);
        }

        $user = Patient::where('email', $tokenData->email)->first();
        $user->password = bcrypt($password);
        $user->save();
        PasswordResetTokens::where('token', $request->token)->delete();
        return response()->json([
            'msg' => "Password updated"
        ]);
    }
}
