<?php
require_once('php/conn.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    if (isset($input['email']) && !isset($input['otp']) && !isset($input['new_password'])) {
        // Send OTP
        $email = $input['email'];

        // Check if email exists
        $stmt = $conn->prepare("SELECT * FROM info WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            // Generate OTP
            $otp = rand(100000, 999999);

            // Update OTP in DB
            $update = $conn->prepare("UPDATE info SET otp = ? WHERE email = ?");
            $update->bind_param("is", $otp, $email);
            $update->execute();

            // Send email
            $subject = "Password Reset Verification Code";
            $message = "Your verification code is: $otp";
            $headers = "From: no-reply@yourdomain.com";

            if (mail($email, $subject, $message, $headers)) {
                echo json_encode(['success' => true, 'message' => 'Verification code sent', 'debug_otp' => $otp]);
                exit;
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to send email']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Email not found']);
        }
        exit;
    } elseif (isset($input['email']) && isset($input['otp'])) {
        // Verify OTP
        $email = $input['email'];
        $otp = $input['otp'];

        $stmt = $conn->prepare("SELECT otp FROM info WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows > 0) {
            $row = $result->fetch_assoc();
            if ($row['otp'] == $otp) {
                echo json_encode(['success' => true, 'message' => 'Code verified']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Invalid verification code']);
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Email not found']);
        }
        exit;
        
    } elseif (isset($input['email']) && isset($input['new_password'])) {
        // Reset password
        $email = $input['email'];
        $new_pass = $input['new_password'];
        // Hash password
        $hashed = password_hash($new_pass, PASSWORD_DEFAULT);
        $hashed = strtolower($new_pass);
        $update = $conn->prepare("UPDATE info SET pass = ?, otp = NULL WHERE email = ?");
        $update->bind_param("ss", $hashed, $email);

        if ($update->execute()) {
            echo json_encode(['success' => true, 'message' => 'Password updated successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to update password']);
        }
        exit;
    }

    exit;
}
?>

<!DOCTYPE html>
<html lang="en">

    <style>
        /* Password Reset Page Specific Styles */
        .reset-hero {
            background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
            color: #fff;
            padding: 100px 0 60px;
            position: relative;
            overflow: hidden;
        }
        .reset-hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: url('assets/img/bg/slide2.jpg') center/cover no-repeat;
            opacity: 0.2;
            z-index: 1;
        }
        .reset-hero .container {
            position: relative;
            z-index: 2;
        }
        .reset-hero h1 {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 15px;
            color: #fff;
        }
        .reset-hero p {
            font-size: 1.1rem;
            max-width: 700px;
            margin: 0 auto;
            opacity: 0.9;
        }
        .breadcrumb {
            background: transparent;
            justify-content: center;
            margin-bottom: 30px;
        }
        .breadcrumb-item a {
            color: #f7921a;
            text-decoration: none;
        }
        .breadcrumb-item.active {
            color: #fff;
        }
        .breadcrumb-item+.breadcrumb-item::before {
            color: #fff;
        }

        /* Reset Content Section */
        .reset-content {
            padding: 80px 0;
            background: #f9f9f9;
        }
        .reset-container {
            background: #fff;
            border-radius: 12px;
            padding: 50px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            max-width: 500px;
            margin: 0 auto;
        }
        .reset-header {
            text-align: center;
            margin-bottom: 40px;
        }
        .reset-header h2 {
            font-size: 2rem;
            font-weight: 700;
            color: #333;
            margin-bottom: 10px;
        }
        .reset-header p {
            color: #666;
            font-size: 1rem;
            line-height: 1.6;
        }
        .reset-icon {
            font-size: 3rem;
            color: #f7921a;
            margin-bottom: 20px;
        }
        .form-group {
            margin-bottom: 25px;
        }
        .form-label {
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            display: block;
        }
        .form-control {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
        }
        .form-control:focus {
            border-color: #f7921a;
            box-shadow: 0 0 0 2px rgba(247, 146, 26, 0.2);
            outline: none;
        }
        .password-input-container {
            position: relative;
        }
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #777;
            cursor: pointer;
        }
        .password-strength {
            margin-top: 8px;
            height: 4px;
            background: #eee;
            border-radius: 2px;
            overflow: hidden;
        }
        .password-strength-bar {
            height: 100%;
            width: 0%;
            transition: all 0.3s ease;
        }
        .password-strength.weak .password-strength-bar {
            background: #e74c3c;
            width: 33%;
        }
        .password-strength.medium .password-strength-bar {
            background: #f39c12;
            width: 66%;
        }
        .password-strength.strong .password-strength-bar {
            background: #2ecc71;
            width: 100%;
        }
        .password-requirements {
            margin-top: 10px;
            font-size: 0.85rem;
            color: #666;
        }
        .requirement {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
        }
        .requirement i {
            margin-right: 8px;
            font-size: 0.8rem;
        }
        .requirement.met {
            color: #2ecc71;
        }
        .requirement.unmet {
            color: #e74c3c;
        }
        .reset-btn {
            width: 100%;
            padding: 14px;
            background: #f7921a;
            color: #fff;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 25px;
        }
        .reset-btn:hover {
            background: #e07b00;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(247, 146, 26, 0.3);
        }
        .reset-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .back-to-login {
            text-align: center;
            margin-top: 20px;
        }
        .back-to-login a {
            color: #f7921a;
            text-decoration: none;
            font-weight: 600;
        }
        .back-to-login a:hover {
            text-decoration: underline;
        }
        .alert {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 25px;
            display: none;
        }
        .alert-error {
            background: #ffe6e6;
            color: #d93025;
            border-left: 4px solid #d93025;
        }
        .alert-success {
            background: #e6f4ea;
            color: #137333;
            border-left: 4px solid #137333;
        }
        .alert-info {
            background: #e6f3ff;
            color: #1a73e8;
            border-left: 4px solid #1a73e8;
        }
        .steps-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 40px;
            position: relative;
        }
        .steps-indicator::before {
            content: '';
            position: absolute;
            top: 15px;
            left: 0;
            right: 0;
            height: 2px;
            background: #eee;
            z-index: 1;
        }
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }
        .step-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #eee;
            color: #999;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }
        .step.active .step-number {
            background: #f7921a;
            color: #fff;
        }
        .step.completed .step-number {
            background: #2ecc71;
            color: #fff;
        }
        .step-label {
            font-size: 0.85rem;
            color: #999;
            font-weight: 500;
        }
        .step.active .step-label {
            color: #f7921a;
        }
        .step.completed .step-label {
            color: #2ecc71;
        }
        .reset-step {
            display: none;
        }
        .reset-step.active {
            display: block;
        }

        /* Back to Top Button */
        .back-to-top {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: #f7921a;
            color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            cursor: pointer;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
            z-index: 1000;
            box-shadow: 0 4px 12px rgba(247, 146, 26, 0.3);
        }
        .back-to-top.visible {
            opacity: 1;
            visibility: visible;
        }
        .back-to-top:hover {
            background: #e07b00;
            transform: translateY(-3px);
        }

        /* Responsive Adjustments */
        @media (max-width: 768px) {
            .reset-hero h1 {
                font-size: 2.2rem;
            }
            .reset-container {
                padding: 30px 20px;
            }
            .back-to-top {
                bottom: 20px;
                right: 20px;
                width: 45px;
                height: 45px;
            }
        }

        @media (max-width: 576px) {
            .reset-hero {
                padding: 80px 0 40px;
            }
            .reset-content {
                padding: 60px 0;
            }
            .reset-container {
                padding: 25px 15px;
            }
            .steps-indicator {
                margin-bottom: 30px;
            }
            .step-label {
                font-size: 0.75rem;
            }
        }
    </style>
<?php 
    require_once('inc/head.php');
?>

<body class="home-4">
    
    
      <?php 
    require_once('inc/preloader.php');
    ?>
  <?php 
    require_once('inc/ticker.php');
    ?>

  <?php 
    require_once('inc/header.php');
?>


    <!-- START RESET HERO SECTION -->
    <section class="reset-hero">
        <div class="container">
            <div class="row">
                <div class="col-12 text-center">
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="index.html">Home</a></li>
                            <li class="breadcrumb-item"><a href="login.html">Login</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Reset Password</li>
                        </ol>
                    </nav>
                    <h1 data-aos="fade-down" data-aos-duration="1000">Reset Your Password</h1>
                    <p data-aos="fade-up" data-aos-duration="1000" data-aos-delay="200">
                        Secure your account by creating a new strong password.
                    </p>
                </div>
            </div>
        </div>
    </section>
    <!-- END RESET HERO SECTION -->

    <!-- START RESET CONTENT SECTION -->
    <section class="reset-content">
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-xl-5 col-lg-6 col-md-8 col-12">
                    <div class="reset-container" data-aos="fade-up" data-aos-duration="1000">
                        
                        <!-- Steps Indicator -->
                        <div class="steps-indicator">
                            <div class="step active" id="step1">
                                <div class="step-number">1</div>
                                <div class="step-label">Verify Email</div>
                            </div>
                            <div class="step" id="step2">
                                <div class="step-number">2</div>
                                <div class="step-label">Reset Code</div>
                            </div>
                            <div class="step" id="step3">
                                <div class="step-number">3</div>
                                <div class="step-label">New Password</div>
                            </div>
                        </div>

                        <!-- Step 1: Email Verification -->
                        <div class="reset-step active" id="step1-content">
                            <div class="reset-header">
                                <div class="reset-icon">
                                    <i class="fas fa-envelope"></i>
                                </div>
                                <h2>Verify Your Email</h2>
                                <p>Enter your email address and we'll send you a verification code to reset your password.</p>
                            </div>

                            <div class="alert alert-info" id="infoAlert">
                                Please check your email for the reset code.
                            </div>
                            <div class="alert alert-error" id="errorAlert">
                                Email not found. Please check and try again.
                            </div>

                            <form id="emailForm">
                                <div class="form-group">
                                    <label for="email" class="form-label">Email Address</label>
                                    <input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address" required>
                                </div>

                                <button type="submit" class="reset-btn" id="sendCodeBtn">Send Verification Code</button>
                            </form>

                            <div class="back-to-login">
                                <a href="login.html"><i class="fas fa-arrow-left"></i> Back to Login</a>
                            </div>
                        </div>

                        <!-- Step 2: Code Verification -->
                        <div class="reset-step" id="step2-content">
                            <div class="reset-header">
                                <div class="reset-icon">
                                    <i class="fas fa-key"></i>
                                </div>
                                <h2>Enter Verification Code</h2>
                                <p>We've sent a 6-digit code to your email. Enter it below to continue.</p>
                            </div>

                            <div class="alert alert-error" id="codeErrorAlert">
                                Invalid verification code. Please try again.
                            </div>

                            <form id="codeForm">
                                <div class="form-group">
                                    <label for="verificationCode" class="form-label">Verification Code</label>
                                    <input type="text" class="form-control" id="verificationCode" name="verificationCode" placeholder="Enter 6-digit code" maxlength="6" required>
                                </div>

                                <div class="form-group">
                                    <p class="text-center" id="resendCode">
                                        Didn't receive the code? <a href="#" id="resendLink">Resend code</a>
                                        <span id="countdown" style="display: none;"> in <span id="timer">60</span>s</span>
                                    </p>
                                </div>

                                <button type="submit" class="reset-btn" id="verifyCodeBtn">Verify Code</button>
                            </form>

                            <div class="back-to-login">
                                <a href="#" id="backToEmail"><i class="fas fa-arrow-left"></i> Back to Email Entry</a>
                            </div>
                        </div>

                        <!-- Step 3: New Password -->
                        <div class="reset-step" id="step3-content">
                            <div class="reset-header">
                                <div class="reset-icon">
                                    <i class="fas fa-lock"></i>
                                </div>
                                <h2>Create New Password</h2>
                                <p>Your new password must be different from previously used passwords.</p>
                            </div>

                            <div class="alert alert-success" id="successAlert">
                                Password reset successful! Redirecting to login...
                            </div>
                            <div class="alert alert-error" id="passwordErrorAlert">
                                Password reset failed. Please try again.
                            </div>

                            <form id="passwordForm">
                                <div class="form-group">
                                    <label for="newPassword" class="form-label">New Password</label>
                                    <div class="password-input-container">
                                        <input type="password" class="form-control" id="newPassword" name="newPassword" placeholder="Enter new password" required>
                                        <button type="button" class="password-toggle" id="passwordToggle1">
                                            <i class="fa fa-eye"></i>
                                        </button>
                                    </div>
                                    <div class="password-strength" id="passwordStrength">
                                        <div class="password-strength-bar"></div>
                                    </div>
                                    <div class="password-requirements" id="passwordRequirements">
                                        <div class="requirement unmet" id="reqLength">
                                            <i class="fas fa-times"></i> At least 8 characters
                                        </div>
                                        <div class="requirement unmet" id="reqUppercase">
                                            <i class="fas fa-times"></i> One uppercase letter
                                        </div>
                                        <div class="requirement unmet" id="reqLowercase">
                                            <i class="fas fa-times"></i> One lowercase letter
                                        </div>
                                        <div class="requirement unmet" id="reqNumber">
                                            <i class="fas fa-times"></i> One number
                                        </div>
                                        <div class="requirement unmet" id="reqSpecial">
                                            <i class="fas fa-times"></i> One special character
                                        </div>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="confirmPassword" class="form-label">Confirm New Password</label>
                                    <div class="password-input-container">
                                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="Confirm new password" required>
                                        <button type="button" class="password-toggle" id="passwordToggle2">
                                            <i class="fa fa-eye"></i>
                                        </button>
                                    </div>
                                    <div id="passwordMatch" style="margin-top: 8px; font-size: 0.85rem; display: none;">
                                        <i class="fas fa-check" style="color: #2ecc71;"></i> Passwords match
                                    </div>
                                    <div id="passwordMismatch" style="margin-top: 8px; font-size: 0.85rem; display: none;">
                                        <i class="fas fa-times" style="color: #e74c3c;"></i> Passwords do not match
                                    </div>
                                </div>

                                <button type="submit" class="reset-btn" id="resetPasswordBtn" disabled>Reset Password</button>
                            </form>

                            <div class="back-to-login">
                                <a href="login.html"><i class="fas fa-arrow-left"></i> Back to Login</a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!-- END RESET CONTENT SECTION -->

    <!-- Back to Top Button -->
    <div class="back-to-top" id="backToTop">
        <i class="fa fa-chevron-up"></i>
    </div>

   	 <?php 
    require_once('inc/footer.php');
    ?>	
    <!-- END FOOTER -->

 	 <?php 
    require_once('incx/script.php');
    ?>	
 
    
    <!-- Custom Scripts for Reset Page -->
    	 <?php 
    require_once('incx/ticker.php');
    ?>	
	
	
  <?php 
    require_once('incx/preloader.php');
    ?>
    
    <script>
        $(document).ready(function(){
            // Initialize AOS
            AOS.init();

            // Back to Top Button
            const backToTopButton = $('#backToTop');
            
            $(window).scroll(function() {
                if ($(window).scrollTop() > 300) {
                    backToTopButton.addClass('visible');
                } else {
                    backToTopButton.removeClass('visible');
                }
            });
            
            backToTopButton.click(function() {
                $('html, body').animate({ scrollTop: 0 }, 800);
                return false;
            });

            // Password Toggle Visibility
            $('#passwordToggle1, #passwordToggle2').click(function() {
                const inputId = $(this).attr('id') === 'passwordToggle1' ? '#newPassword' : '#confirmPassword';
                const passwordInput = $(inputId);
                const type = passwordInput.attr('type') === 'password' ? 'text' : 'password';
                passwordInput.attr('type', type);
                
                // Toggle eye icon
                $(this).find('i').toggleClass('fa-eye fa-eye-slash');
            });

            // Step Navigation Variables
            let userEmail = '';
            let verificationCode = '';

            // Step 1: Email Form Submission
            $('#emailForm').submit(function(e) {
                e.preventDefault();
                
                userEmail = $('#email').val();
                
                // Simple validation
                if (!userEmail) {
                    showAlert('error', 'Please enter your email address.');
                    return;
                }
                
                // Email validation
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(userEmail)) {
                    showAlert('error', 'Please enter a valid email address.');
                    return;
                }
                
                // Simulate sending verification code
                simulateSendCode(userEmail);
            });

            // Step 2: Code Form Submission
            $('#codeForm').submit(function(e) {
                e.preventDefault();
                
                const enteredCode = $('#verificationCode').val();
                
                if (!enteredCode || enteredCode.length !== 6) {
                    showCodeAlert('error', 'Please enter the 6-digit verification code.');
                    return;
                }
                
                // Simulate code verification
                simulateVerifyCode(enteredCode);
            });

            // Step 3: Password Form Submission
            $('#passwordForm').submit(function(e) {
                e.preventDefault();
                
                const newPassword = $('#newPassword').val();
                const confirmPassword = $('#confirmPassword').val();
                
                if (newPassword !== confirmPassword) {
                    showPasswordAlert('error', 'Passwords do not match.');
                    return;
                }
                
                // Simulate password reset
                simulateResetPassword(newPassword);
            });

            // Navigation between steps
            $('#backToEmail').click(function(e) {
                e.preventDefault();
                navigateToStep(1);
            });

            $('#resendLink').click(function(e) {
                e.preventDefault();
                if (!$(this).hasClass('disabled')) {
                    simulateSendCode(userEmail);
                }
            });

            // Password Strength Checker
            $('#newPassword').on('input', function() {
                checkPasswordStrength($(this).val());
                checkPasswordMatch();
            });

            $('#confirmPassword').on('input', function() {
                checkPasswordMatch();
            });

            // Show alert message for step 1
            function showAlert(type, message) {
                const errorAlert = $('#errorAlert');
                const infoAlert = $('#infoAlert');
                
                if (type === 'error') {
                    errorAlert.text(message);
                    errorAlert.show();
                    infoAlert.hide();
                } else {
                    infoAlert.text(message);
                    infoAlert.show();
                    errorAlert.hide();
                }
            }

            // Show alert message for step 2
            function showCodeAlert(type, message) {
                const codeErrorAlert = $('#codeErrorAlert');
                
                if (type === 'error') {
                    codeErrorAlert.text(message);
                    codeErrorAlert.show();
                }
            }

            // Show alert message for step 3
            function showPasswordAlert(type, message) {
                const successAlert = $('#successAlert');
                const errorAlert = $('#passwordErrorAlert');
                
                if (type === 'success') {
                    successAlert.text(message);
                    successAlert.show();
                    errorAlert.hide();
                } else {
                    errorAlert.text(message);
                    errorAlert.show();
                    successAlert.hide();
                }
            }

            // Navigate between steps
            function navigateToStep(stepNumber) {
                // Hide all steps
                $('.reset-step').removeClass('active');
                
                // Remove active class from all steps
                $('.step').removeClass('active completed');
                
                // Show target step
                $(`#step${stepNumber}-content`).addClass('active');
                
                // Mark previous steps as completed and current as active
                for (let i = 1; i <= stepNumber; i++) {
                    if (i < stepNumber) {
                        $(`#step${i}`).addClass('completed');
                    } else {
                        $(`#step${i}`).addClass('active');
                    }
                }
            }

            // Check password strength
            function checkPasswordStrength(password) {
                let strength = 0;
                const requirements = {
                    length: password.length >= 8,
                    uppercase: /[A-Z]/.test(password),
                    lowercase: /[a-z]/.test(password),
                    number: /[0-9]/.test(password),
                    special: /[^A-Za-z0-9]/.test(password)
                };

                // Update requirement indicators
                Object.keys(requirements).forEach(key => {
                    const element = $(`#req${key.charAt(0).toUpperCase() + key.slice(1)}`);
                    if (requirements[key]) {
                        element.removeClass('unmet').addClass('met');
                        element.find('i').removeClass('fa-times').addClass('fa-check');
                        strength++;
                    } else {
                        element.removeClass('met').addClass('unmet');
                        element.find('i').removeClass('fa-check').addClass('fa-times');
                    }
                });

                // Update strength bar
                const strengthBar = $('#passwordStrength');
                strengthBar.removeClass('weak medium strong');
                
                if (strength <= 2) {
                    strengthBar.addClass('weak');
                } else if (strength <= 4) {
                    strengthBar.addClass('medium');
                } else {
                    strengthBar.addClass('strong');
                }

                // Enable/disable reset button based on all requirements
                const allMet = Object.values(requirements).every(val => val);
                $('#resetPasswordBtn').prop('disabled', !allMet);
            }

            // Check if passwords match
            function checkPasswordMatch() {
                const password = $('#newPassword').val();
                const confirmPassword = $('#confirmPassword').val();
                
                if (password && confirmPassword) {
                    if (password === confirmPassword) {
                        $('#passwordMatch').show();
                        $('#passwordMismatch').hide();
                    } else {
                        $('#passwordMatch').hide();
                        $('#passwordMismatch').show();
                    }
                } else {
                    $('#passwordMatch').hide();
                    $('#passwordMismatch').hide();
                }
            }

            // Function to send verification code
function simulateSendCode(email) {
    // Show loading state
    const sendBtn = $('#sendCodeBtn');
    const originalText = sendBtn.text();
    sendBtn.html('<i class="fa fa-spinner fa-spin"></i> Sending Code...');
    sendBtn.prop('disabled', true);
    
    // Send AJAX request to current page
    $.ajax({
        url: '',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ email: email }),
        success: function(response) {
             response = JSON.parse(response);
             console.log(response);
            if (response.success) {
                showAlert('info', `Verification code sent to ${email}`);
                
                // Navigate to step 2
                navigateToStep(2);
                
                // Start countdown for resend
                startResendCountdown();
                
                // For testing - display OTP in console (remove in production)
                console.log('OTP for testing:', response.debug_otp);
            } else {
                showAlert('error', response.message);
            }
            
            // Reset button
            sendBtn.text(originalText);
            sendBtn.prop('disabled', false);
        },
        error: function(xhr, status, error) {
            showAlert('error', 'Failed to send verification code. Please try again.');
            console.error('Error:', error);
            
            // Reset button
            sendBtn.text(originalText);
            sendBtn.prop('disabled', false);
        }
    });
}

// Function to verify code
function simulateVerifyCode(enteredCode) {
    // Show loading state
    const verifyBtn = $('#verifyCodeBtn');
    const originalText = verifyBtn.text();
    verifyBtn.html('<i class="fa fa-spinner fa-spin"></i> Verifying...');
    verifyBtn.prop('disabled', true);
    
    // Send AJAX request to current page
    $.ajax({
        url: '',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ 
            email: userEmail, 
            otp: enteredCode 
        }),
        success: function(response) {
             response = JSON.parse(response);
             console.log(response);
            if (response.success) {
                // Navigate to step 3
                navigateToStep(3);
            } else {
                showCodeAlert('error', response.message);
            }
            
            // Reset button
            verifyBtn.text(originalText);
            verifyBtn.prop('disabled', false);
        },
        error: function(xhr, status, error) {
            showCodeAlert('error', 'Verification failed. Please try again.');
            console.error('Error:', error);
            
            // Reset button
            verifyBtn.text(originalText);
            verifyBtn.prop('disabled', false);
        }
    });
}

// Function to reset password
function simulateResetPassword(newPassword) {
    // Show loading state
    const resetBtn = $('#resetPasswordBtn');
    const originalText = resetBtn.text();
    resetBtn.html('<i class="fa fa-spinner fa-spin"></i> Resetting Password...');
    resetBtn.prop('disabled', true);
    
    // Send AJAX request to current page
    $.ajax({
        url: '',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ 
            email: userEmail, 
            new_password: newPassword 
        }),
        success: function(response) {
             response = JSON.parse(response);
             console.log(response);
            if (response.success) {
                showPasswordAlert('success', 'Password reset successful! Redirecting to login...');
                
                // Redirect after delay
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
            } else {
                showPasswordAlert('error', response.message);
                resetBtn.text(originalText);
                resetBtn.prop('disabled', false);
            }
        },
        error: function(xhr, status, error) {
            showPasswordAlert('error', 'Password reset failed. Please try again.');
            console.error('Error:', error);
            
            // Reset button
            resetBtn.text(originalText);
            resetBtn.prop('disabled', false);
        }
    });
}

            // Start countdown for resend code
            function startResendCountdown() {
                let timeLeft = 60;
                const resendLink = $('#resendLink');
                const countdown = $('#countdown');
                const timer = $('#timer');
                
                resendLink.addClass('disabled');
                countdown.show();
                
                const countdownInterval = setInterval(() => {
                    timeLeft--;
                    timer.text(timeLeft);
                    
                    if (timeLeft <= 0) {
                        clearInterval(countdownInterval);
                        resendLink.removeClass('disabled');
                        countdown.hide();
                    }
                }, 1000);
            }

            // Faster Preloader
            setTimeout(function() {
                $('#page-preloader').addClass('loaded');
                
                // Remove from DOM after animation completes
                setTimeout(function() {
                    $('#page-preloader').remove();
                }, 500);
            }, 1500);
            
            // Alternative: Hide when page is fully loaded (even faster)
            $(window).on('load', function() {
                $('#page-preloader').addClass('loaded');
                setTimeout(function() {
                    $('#page-preloader').remove();
                }, 500);
            });
            
            // Fallback: Maximum 3 seconds even if page isn't fully loaded
            setTimeout(function() {
                $('#page-preloader').addClass('loaded');
                setTimeout(function() {
                    $('#page-preloader').remove();
                }, 500);
            }, 3000);
        });
    </script>
</body>
</html>