<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
class ForgetPasswordController extends Controller
{
    public function send_otp(Request $request)
    {

        $request->validate([
            'email' => 'required|email',
        ]);
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json([
                'status'  => 'error',
                'message' => 'User not found.',
                'code'    => 404,
            ], 404);
        }
        $otp                  = rand(100000, 999999);
        $encryptedOtp         = Crypt::encryptString($otp);
        $expiryTime           = Carbon::now()->addMinutes(10);
        $user->otp            = $encryptedOtp;
        $user->otp_expires_at = $expiryTime;
        $user->save();
        try {
            Mail::raw("Your OTP for password reset is: $otp", function ($message) use ($request) {
                $message->to($request->email)
                    ->subject('Password Reset OTP');
            });
            return response()->json([
                'status'  => 'success',
                'message' => 'OTP has been sent to your email.',
                'code'    => 200,
            ], 200);
        } catch (\Exception $e) {
            Log::error('Failed to send OTP:', ['errormessage' => $e->getMessage()]);
            return response()->json([
                'status'  => 'error',
                'message' => 'Failed to send OTP.',
                'code'    => 500,
            ], 500);
        }
    }
    public function verify_otp(Request $request)
    {
        $request->validate([
            'email'    => 'required|email',
            'send_otp' => 'required|string',
        ]);
        $user = User::where('email', $request->email)
            ->where('otp_expires_at', '>', Carbon::now())
            ->first();
        if (!$user) {
            return response()->json([
                'status'  => 'error',
                'message' => 'The OTP is invalid or has expired.',
                'code'    => 400,
            ], 400);
        }
        try {
            $decryptedOtp = Crypt::decryptString($user->otp);
        } catch (\Exception $e) {
            return response()->json([
                'status'  => 'error',
                'message' => 'The OTP is invalid or has expired.',
                'code'    => 400,
            ], 400);
        }
        if ($decryptedOtp === $request->send_otp) {
            return response()->json([
                'status'  => 'success',
                'message' => 'OTP verified successfully.',
                'code'    => 200,
            ], 200);
        } else {
            return response()->json([
                'status'  => 'error',
                'message' => 'The OTP is invalid or has expired.',
                'code'    => 400,
            ], 400);
        }
    }
    public function resetPassword(Request $request)
    {
        $validated = $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string|min:8|confirmed'
        ]);
        $user = User::where('email', $request->email)->first();
        if (!$user) {
            Log::error('User not found:', ['email' => $request->email]);
            return response()->json([
                'status'  => 'error',
                'message' => 'User not found.',
                'code'    => 404,
            ], 404);
        }
        $user->password = Hash::make($request->password);
        $user->save();
        Log::info('Password reset successfully for:', ['email' => $request->email]);
        return response()->json([
            'status'  => 'success',
            'message' => 'Password has been reset successfully.',
            'code'    => 200,
        ], 200);
    }
}
