<?php
// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("Referrer-Policy: strict-origin-when-cross-origin");

require_once './includes/config.php';
require_once './includes/auth_functions.php';

// Rate limiting for password reset attempts
if (!isset($_SESSION['reset_attempts'])) {
    $_SESSION['reset_attempts'] = 0;
    $_SESSION['last_reset_attempt'] = 0;
}

// Check if too many attempts
if ($_SESSION['reset_attempts'] >= 5 && (time() - $_SESSION['last_reset_attempt'] < 300)) {
    die('Too many password reset attempts. Please try again later.');
}

// Load SMTP configuration
$smtpConfig = loadSmtpConfig();

// Initialize variables
$message = '';
$passwordStrength = null;
$resetRequest = null;

if (isset($_GET['token'])) {
    $token = $_GET['token'];

    // Fetch email and token expiry from password_resets table
    try {
        $stmt = $pdo->prepare('SELECT email, expires_at AS token_expiry FROM password_resets WHERE token = :token');
        $stmt->execute(['token' => $token]);
        $resetRequest = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Database error fetching reset token: " . $e->getMessage());
        $message = 'An error occurred. Please try again later.';
    }

    if ($resetRequest) {
        $currentTimestamp = time();
        if ($currentTimestamp <= strtotime($resetRequest['token_expiry'])) {
            if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                // CSRF validation
                if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
                    logSecurityEvent(null, 'csrf_failure', [
                        'page' => 'reset_password',
                        'ip' => $_SERVER['REMOTE_ADDR']
                    ]);
                    die('Invalid request. Please try again.');
                }

                $newPassword = $_POST['new_password'];
                $confirmPassword = $_POST['confirm_password'];
                
                // Check password strength
                $passwordStrength = checkPasswordStrength($newPassword);

                if ($newPassword === $confirmPassword) {
                    if ($passwordStrength['score'] >= 5) { // Require at least 5/7 strength
                        $hashedPassword = password_hash($newPassword, PASSWORD_BCRYPT, ['cost' => 12]);

                        // Fetch the member ID and username from member tables
                        try {
                            $userStmt = $pdo->prepare('
                                SELECT a.member_id, a.username 
                                FROM member_portal_accounts a 
                                WHERE a.email = :email
                            ');
                            $userStmt->execute(['email' => $resetRequest['email']]);
                            $member = $userStmt->fetch(PDO::FETCH_ASSOC);

                            if ($member) {
                                // Update the member's password and password_last_changed timestamp
                                $updateStmt = $pdo->prepare("
                                    UPDATE member_portal_accounts 
                                    SET password_hash = :password, password_last_changed = CURRENT_TIMESTAMP 
                                    WHERE member_id = :id
                                ");
                                $updateStmt->execute([
                                    'password' => $hashedPassword,
                                    'id' => $member['member_id'],
                                ]);

                                // Remove the used token
                                $deleteStmt = $pdo->prepare('DELETE FROM password_resets WHERE token = :token');
                                $deleteStmt->execute(['token' => $token]);

                                // Log the password reset
                                logSecurityEvent($member['member_id'], 'password_reset_success', [
                                    'ip' => $_SERVER['REMOTE_ADDR']
                                ]);

                                // Send email notification with username and IP
                                sendPasswordResetEmail($resetRequest['email'], $member['username'], $smtpConfig, $_SERVER['REMOTE_ADDR']);

                                $message = 'Your password has been reset successfully!';
                            } else {
                                $message = 'Member account not found.';
                                $_SESSION['reset_attempts']++;
                                $_SESSION['last_reset_attempt'] = time();
                                logSecurityEvent(null, 'password_reset_user_not_found', [
                                    'email' => $resetRequest['email'],
                                    'ip' => $_SERVER['REMOTE_ADDR']
                                ]);
                            }
                        } catch (PDOException $e) {
                            error_log("Database error during password reset: " . $e->getMessage());
                            $message = 'An error occurred. Please try again later.';
                            logSecurityEvent(null, 'password_reset_error', [
                                'error' => $e->getMessage(),
                                'ip' => $_SERVER['REMOTE_ADDR']
                            ]);
                        }
                    } else {
                        $message = 'Password does not meet strength requirements: ' . implode(', ', $passwordStrength['messages']);
                        $_SESSION['reset_attempts']++;
                        $_SESSION['last_reset_attempt'] = time();
                        logSecurityEvent(null, 'password_reset_weak_password', [
                            'email' => $resetRequest['email'],
                            'ip' => $_SERVER['REMOTE_ADDR']
                        ]);
                    }
                } else {
                    $message = 'Passwords do not match.';
                    $_SESSION['reset_attempts']++;
                    $_SESSION['last_reset_attempt'] = time();
                    logSecurityEvent(null, 'password_reset_mismatch', [
                        'email' => $resetRequest['email'],
                        'ip' => $_SERVER['REMOTE_ADDR']
                    ]);
                }
            } else {
                $message = 'Please enter a new password.';
            }
        } else {
            // Clean up expired tokens
            try {
                $deleteStmt = $pdo->prepare('DELETE FROM password_resets WHERE token = :token');
                $deleteStmt->execute(['token' => $token]);
            } catch (PDOException $e) {
                error_log("Database error deleting expired token: " . $e->getMessage());
            }
            $message = 'The reset token has expired.';
            logSecurityEvent(null, 'password_reset_expired_token', [
                'email' => $resetRequest['email'],
                'ip' => $_SERVER['REMOTE_ADDR']
            ]);
        }
    } else {
        $message = 'Invalid reset token.';
        $_SESSION['reset_attempts']++;
        $_SESSION['last_reset_attempt'] = time();
        logSecurityEvent(null, 'password_reset_invalid_token', [
            'token' => $token,
            'ip' => $_SERVER['REMOTE_ADDR']
        ]);
    }
} else {
    $message = 'No reset token provided.';
    logSecurityEvent(null, 'password_reset_no_token', [
        'ip' => $_SERVER['REMOTE_ADDR']
    ]);
}

// Generate CSRF token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/**
 * Check password strength
 */
function checkPasswordStrength($password) {
    $strength = 0;
    $messages = [];
    
    // Check length
    if (strlen($password) >= 12) {
        $strength += 2;
    } elseif (strlen($password) >= 8) {
        $strength += 1;
        $messages[] = 'Consider using a longer password (12+ characters)';
    } else {
        $messages[] = 'Password too short (minimum 8 characters)';
    }
    
    // Check for uppercase
    if (preg_match('/[A-Z]/', $password)) {
        $strength += 1;
    } else {
        $messages[] = 'Add at least one uppercase letter';
    }
    
    // Check for lowercase
    if (preg_match('/[a-z]/', $password)) {
        $strength += 1;
    } else {
        $messages[] = 'Add at least one lowercase letter';
    }
    
    // Check for numbers
    if (preg_match('/[0-9]/', $password)) {
        $strength += 1;
    } else {
        $messages[] = 'Add at least one number';
    }
    
    // Check for special chars
    if (preg_match('/[^A-Za-z0-9]/', $password)) {
        $strength += 2;
    } else {
        $messages[] = 'Add at least one special character';
    }
    
    // Check against common passwords
    $commonPasswords = ['password', '123456', 'qwerty', 'letmein'];
    if (in_array(strtolower($password), $commonPasswords)) {
        $strength = 0;
        $messages[] = 'Password is too common';
    }
    
    return [
        'score' => $strength,
        'max_score' => 7,
        'messages' => $messages
    ];
}

/**
 * Send a password reset email using PHPMailer.
 */
function sendPasswordResetEmail($email, $username, $config, $ipAddress) {
    // Check if SMTP configuration is valid
    if (empty($config) || !is_array($config)) {
        error_log("Invalid SMTP configuration array");
        return false;
    }
    
    // Map the configuration keys to match what PHPMailer expects
    $smtpHost = $config['smtp_host'] ?? $config['host'] ?? '';
    $smtpUsername = $config['smtp_username'] ?? $config['username'] ?? $config['from_address'] ?? '';
    $smtpPassword = $config['smtp_password'] ?? $config['password'] ?? '';
    $smtpEncryption = $config['smtp_encryption'] ?? $config['encryption'] ?? 'tls';
    $smtpPort = $config['smtp_port'] ?? $config['port'] ?? 587;
    $fromAddress = $config['from_address'] ?? $config['smtp_username'] ?? '';
    $fromName = $config['from_name'] ?? 'Member Portal';
    
    // Validate required configuration
    if (empty($smtpHost) || empty($smtpUsername) || empty($smtpPassword)) {
        error_log("Missing required SMTP configuration");
        return false;
    }

    require_once __DIR__ . '/./vendor/autoload.php';

    $mail = new PHPMailer\PHPMailer\PHPMailer(true);

    try {
        // SMTP configuration
        $mail->isSMTP();
        $mail->Host = $smtpHost;
        $mail->SMTPAuth = true;
        $mail->Username = $smtpUsername;
        $mail->Password = $smtpPassword;
        $mail->SMTPSecure = $smtpEncryption;
        $mail->Port = $smtpPort;

        // Email content
        $mail->setFrom($fromAddress, $fromName);
        $mail->addAddress($email);
        $mail->addReplyTo($fromAddress, 'Member Support');

        // Current time for email footer
        $currentTime = date('Y-m-d H:i:s');

        // Load email template
        $emailTemplate = <<<HTML
        <!DOCTYPE html>
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                .header { background-color: #2563eb; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; background-color: #f9f9f9; }
                .footer { padding: 20px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h2>Member Portal Password Reset</h2>
                </div>
                <div class="content">
                    <p>Hello {$username},</p>
                    <p>Your password has been successfully reset from IP address {$ipAddress}.</p>
                    <p>If you did not perform this action, please contact our support team immediately.</p>
                    <p>Date/Time: {$currentTime}</p>
                </div>
                <div class="footer">
                    <p>&copy; " . date('Y') . " Baptist Convention SACCO LTD. All rights reserved.</p>
                </div>
            </div>
        </body>
        </html>
        HTML;

        $plainText = "Hello {$username},\n\nYour password has been successfully reset from IP address {$ipAddress}.\n\nIf you did not perform this action, please contact our support team immediately.\n\nDate/Time: {$currentTime}";

        $mail->isHTML(true);
        $mail->Subject = 'Member Portal Password Reset Successful';
        $mail->Body = $emailTemplate;
        $mail->AltBody = $plainText;

        // Send email
        return $mail->send();
    } catch (Exception $e) {
        error_log("Email send failed: " . $mail->ErrorInfo);
        return false;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reset Password | Member Portal</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
        
        :root {
            --primary: #2563eb;
            --primary-dark: #1d4ed8;
            --secondary: #64748b;
            --success: #10b981;
            --danger: #ef4444;
            --warning: #f59e0b;
            --light: #f8fafc;
            --dark: #1e293b;
            --gray: #94a3b8;
            --border: #e2e8f0;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Inter', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }
        
        .reset-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 440px;
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .reset-header {
            background: var(--primary);
            color: white;
            padding: 24px 32px;
            text-align: center;
            position: relative;
        }
        
        .security-indicator {
            position: absolute;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            gap: 5px;
            font-size: 12px;
            background: rgba(255, 255, 255, 0.2);
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        .reset-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .reset-header p {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .reset-body {
            padding: 32px;
        }
        
        .logo {
            margin-bottom: 24px;
            text-align: center;
        }
        
        .logo img {
            height: 60px;
        }
        
        .form-group {
            margin-bottom: 20px;
            position: relative;
        }
        
        label {
            display: block;
            font-size: 14px;
            font-weight: 500;
            margin-bottom: 8px;
            color: var(--dark);
        }
        
        .input-group {
            position: relative;
        }
        
        input[type="password"] {
            width: 100%;
            padding: 12px 16px;
            padding-right: 40px;
            border: 1px solid var(--border);
            border-radius: 8px;
            font-size: 15px;
            transition: all 0.2s;
        }
        
        input[type="password"]:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            outline: none;
        }
        
        .toggle-password {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--gray);
            cursor: pointer;
            padding: 4px;
            z-index: 2;
        }
        
        .toggle-password:hover {
            color: var(--secondary);
        }
        
        .password-strength {
            margin-top: 8px;
            height: 4px;
            background-color: #e2e8f0;
            border-radius: 2px;
            overflow: hidden;
        }
        
        .strength-meter {
            height: 100%;
            width: 0%;
            transition: width 0.3s ease;
        }
        
        .password-requirements {
            margin-top: 8px;
            font-size: 12px;
            color: var(--secondary);
        }
        
        .requirement {
            display: flex;
            align-items: center;
            gap: 5px;
            margin-bottom: 4px;
        }
        
        .requirement i {
            font-size: 10px;
        }
        
        .requirement.met {
            color: var(--success);
        }
        
        .submit-btn {
            width: 100%;
            padding: 14px;
            background-color: var(--primary);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.2s;
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
        }
        
        .submit-btn:hover {
            background-color: var(--primary-dark);
        }
        
        .submit-btn:active {
            transform: translateY(1px);
        }
        
        .submit-btn.loading {
            opacity: 0.8;
            pointer-events: none;
        }
        
        .submit-btn:disabled {
            background-color: var(--gray);
            cursor: not-allowed;
        }
        
        .spinner {
            width: 18px;
            height: 18px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s linear infinite;
        }
        
        .error-message {
            background-color: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid var(--danger);
        }
        
        .success-message {
            background-color: rgba(16, 185, 129, 0.1);
            color: var(--success);
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            border-left: 4px solid var(--success);
        }
        
        .login-footer {
            text-align: center;
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid var(--border);
            font-size: 14px;
            color: var(--secondary);
        }
        
        .login-footer a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        
        .login-footer a:hover {
            text-decoration: underline;
        }
        
        .privacy-notice {
            font-size: 12px;
            color: var(--secondary);
            margin-top: 16px;
            text-align: center;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
            20%, 40%, 60%, 80% { transform: translateX(5px); }
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        @media (max-width: 480px) {
            .reset-container {
                border-radius: 12px;
            }
            
            .reset-header {
                padding: 20px;
            }
            
            .reset-body {
                padding: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="reset-container">
        <div class="reset-header">
            <div class="security-indicator">
                <i class="fas fa-lock"></i>
                <span>Secure</span>
            </div>
            <h1>Reset Your Password</h1>
            <p>Create a new secure password</p>
        </div>
        
        <div class="reset-body">
            <div class="logo">
                <!-- Replace with your SACCO logo -->
                <svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <rect width="60" height="60" rx="12" fill="#2563eb"/>
                    <path d="M20 30L26 36L40 22" stroke="white" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            
            <?php if (!empty($message)): ?>
                <div class="<?php echo (strpos($message, 'successfully') !== false ? 'success-message' : 'error-message'); ?>">
                    <i class="fas <?php echo (strpos($message, 'successfully') !== false ? 'fa-check-circle' : 'fa-exclamation-circle'); ?>"></i>
                    <span><?php echo htmlspecialchars($message); ?></span>
                </div>
            <?php endif; ?>
            
            <?php if (!isset($resetRequest) || empty($message) || $message === 'Please enter a new password.'): ?>
                <form method="POST" action="" id="resetForm">
                    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">

                    <div class="form-group">
                        <label for="new_password">New Password</label>
                        <div class="input-group">
                            <input type="password" name="new_password" id="new_password" required placeholder="Enter new password" oninput="checkPasswordStrength()">
                            <button type="button" class="toggle-password" id="toggleNewPassword">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                        <div class="password-strength" id="passwordStrength">
                            <div class="strength-meter" id="strengthMeter"></div>
                        </div>
                        <div class="password-requirements" id="passwordRequirements">
                            <div class="requirement" id="reqLength">
                                <i class="fas fa-circle"></i>
                                <span>At least 8 characters</span>
                            </div>
                            <div class="requirement" id="reqUppercase">
                                <i class="fas fa-circle"></i>
                                <span>One uppercase letter</span>
                            </div>
                            <div class="requirement" id="reqLowercase">
                                <i class="fas fa-circle"></i>
                                <span>One lowercase letter</span>
                            </div>
                            <div class="requirement" id="reqNumber">
                                <i class="fas fa-circle"></i>
                                <span>One number</span>
                            </div>
                            <div class="requirement" id="reqSpecial">
                                <i class="fas fa-circle"></i>
                                <span>One special character</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password">Confirm Password</label>
                        <div class="input-group">
                            <input type="password" name="confirm_password" id="confirm_password" required placeholder="Confirm your password">
                            <button type="button" class="toggle-password" id="toggleConfirmPassword">
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    
                    <button type="submit" class="submit-btn" id="submitBtn">
                        <span>Reset Password</span>
                        <div class="spinner" style="display: none;"></div>
                    </button>
                    
                    <div class="privacy-notice">
                        <i class="fas fa-shield-alt"></i>
                        Your password information is encrypted and secure
                    </div>
                </form>
            <?php endif; ?>
            
            <div class="login-footer">
                <p>Remember your password? <a href="login.php">Back to Login</a></p>
                <p>Need help? <a href="contact.php">Contact Support</a></p>
                <p>&copy; <?php echo date('Y'); ?> Baptist Convention SACCO LTD. All rights reserved.</p>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const resetForm = document.getElementById('resetForm');
            const submitBtn = document.getElementById('submitBtn');
            const toggleNewPassword = document.getElementById('toggleNewPassword');
            const toggleConfirmPassword = document.getElementById('toggleConfirmPassword');
            const newPasswordInput = document.getElementById('new_password');
            const confirmPasswordInput = document.getElementById('confirm_password');
            
            // Toggle password visibility
            function setupPasswordToggle(toggleButton, passwordInput) {
                toggleButton.addEventListener('click', function() {
                    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                    passwordInput.setAttribute('type', type);
                    
                    // Toggle eye icon
                    const eyeIcon = this.querySelector('i');
                    eyeIcon.classList.toggle('fa-eye');
                    eyeIcon.classList.toggle('fa-eye-slash');
                });
            }
            
            setupPasswordToggle(toggleNewPassword, newPasswordInput);
            setupPasswordToggle(toggleConfirmPassword, confirmPasswordInput);
            
            // Password strength indicator
            function checkPasswordStrength() {
                const password = newPasswordInput.value;
                const strengthMeter = document.getElementById('strengthMeter');
                
                // Check requirements
                const hasLength = password.length >= 8;
                const hasUppercase = /[A-Z]/.test(password);
                const hasLowercase = /[a-z]/.test(password);
                const hasNumber = /[0-9]/.test(password);
                const hasSpecial = /[^A-Za-z0-9]/.test(password);
                
                // Update requirement indicators
                document.getElementById('reqLength').classList.toggle('met', hasLength);
                document.getElementById('reqUppercase').classList.toggle('met', hasUppercase);
                document.getElementById('reqLowercase').classList.toggle('met', hasLowercase);
                document.getElementById('reqNumber').classList.toggle('met', hasNumber);
                document.getElementById('reqSpecial').classList.toggle('met', hasSpecial);
                
                // Calculate strength (matches server-side logic)
                let strength = 0;
                if (password.length >= 12) strength += 2;
                else if (password.length >= 8) strength += 1;
                
                if (/[A-Z]/.test(password)) strength += 1;
                if (/[a-z]/.test(password)) strength += 1;
                if (/[0-9]/.test(password)) strength += 1;
                if (/[^A-Za-z0-9]/.test(password)) strength += 2;
                
                // Check against common passwords
                const common = ['password', '123456', 'qwerty', 'letmein'];
                if (common.includes(password.toLowerCase())) {
                    strength = 0;
                }
                
                // Update strength meter
                let strengthPercentage = (strength / 7) * 100;
                strengthMeter.style.width = strengthPercentage + '%';
                
                // Set color based on strength
                if (strengthPercentage < 40) {
                    strengthMeter.style.backgroundColor = '#ef4444'; // red
                } else if (strengthPercentage < 70) {
                    strengthMeter.style.backgroundColor = '#f59e0b'; // orange
                } else {
                    strengthMeter.style.backgroundColor = '#10b981'; // green
                }
                
                // Enable/disable submit button based on strength
                submitBtn.disabled = strength < 5;
            }
            
            // Form submission
            resetForm.addEventListener('submit', function(e) {
                // Basic validation
                const newPassword = newPasswordInput.value;
                const confirmPassword = confirmPasswordInput.value;
                
                if (newPassword !== confirmPassword) {
                    e.preventDefault();
                    resetForm.classList.add('shake');
                    setTimeout(() => {
                        resetForm.classList.remove('shake');
                    }, 500);
                    return;
                }
                
                const spinner = submitBtn.querySelector('.spinner');
                const buttonText = submitBtn.querySelector('span');
                
                // Show loading state
                spinner.style.display = 'block';
                buttonText.textContent = 'Resetting...';
                submitBtn.classList.add('loading');
            });
            
            // Auto-focus on password field
            if (newPasswordInput) {
                newPasswordInput.focus();
            }
        });
    </script>
</body>
</html>