<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\PasswordReset;
use App\Mail\ResetPasswordMail;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;

class PasswordResetController extends Controller
{
    public function sendOtp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'   => false,
                'message'   => 'Validation failed',
                'errors'    => $validator->errors()
            ], 200);
        }

        // Generate 6-digit OTP
        $otp = rand(100000, 999999);

        // Store OTP in the password_resets table
        PasswordReset::updateOrInsert(
            ['email' => $request->email],
            ['token' => $otp, 'created_at' => Carbon::now()]
        );

        // Send OTP via email
        Mail::to($request->email)->send(new ResetPasswordMail($otp));

        return response()->json([
            'success' => true,
            'message' => 'OTP sent to your email.',
            'otp'     => $otp,
        ]);
    }

    /**
     * Verify OTP
     */
    public function verifyOtp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
            'otp' => 'required|digits:6',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'   => false,
                'message'   => 'Validation failed',
                'errors'    => $validator->errors()
            ], 200);
        }

        // Check if OTP exists and is valid
        $otpRecord = PasswordReset::where('email', $request->email)
            ->where('token', (integer)$request->otp)
            ->where('created_at', '>', Carbon::now()->subMinutes(10)) // OTP valid for 10 mins
            ->first();

        if ($otpRecord==null) {
            return response()->json([
                'success' => false,
                'message' => 'Invalid or expired OTP.',
                'time' => Carbon::now()->subMinutes(10)
            ], 200);
        }

        return response()->json([
            'success' => true,
            'message' => 'OTP verified successfully.'
        ],200);
    }

    /**
     * Reset password after OTP verification
     */
    public function resetPassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:6|confirmed',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'   => false,
                'message'   => 'Validation failed',
                'errors'    => $validator->errors()
            ], 200);
        }

        
        // Update user's password
        User::where('email', $request->email)->update([
            'password' => Hash::make($request->password),
        ]);

        // Delete OTP record
        PasswordReset::where('email', $request->email)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Password has been reset successfully.'
        ],200);
    }

    public function resendOtp(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users,email',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success'   => false,
                'message'   => 'Validation failed',
                'errors'    => $validator->errors()
            ], 200);
        }

        // Generate 6-digit OTP
        $otp = rand(100000, 999999);

        // Store OTP in the password_resets table
        PasswordReset::updateOrInsert(
            ['email' => $request->email],
            ['token' => $otp, 'created_at' => Carbon::now()]
        );

        // Send OTP via email
        Mail::to($request->email)->send(new ResetPasswordMail($otp));

        return response()->json([
            'success' => true,
            'message' => 'OTP Resend Successfully ',
        ]);
    }

}
