<?php
require_once './includes/session_init.php';
require_once './includes/config.php';
require_once './includes/auth_functions.php';
require_once './includes/sms_helper.php';

// Check if user is logged in
if (!isset($_SESSION['member_id']) || !isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

$error = '';
$success = '';
$step = 'form'; // form, verify_otp, success

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

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF validation
    if (empty($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        logSecurityEvent($_SESSION['member_id'], 'csrf_failure', [
            'page' => 'change_password',
            'ip' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
        ]);
        die("Invalid request. Please try again.");
    }

    $member_id = $_SESSION['member_id'];
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    try {
        // Fetch member details for OTP sending
        $stmt = $pdo->prepare("
            SELECT a.member_id, a.email, a.username, m.first_name, m.last_name, 
                   m.communication_preference, m.phone_number
            FROM member_portal_accounts a
            JOIN members m ON m.id = a.member_id
            WHERE a.member_id = ?
        ");
        $stmt->execute([$member_id]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$member) {
            logSecurityEvent($member_id, 'member_not_found', [
                'action' => 'password_change',
                'ip' => $ip_address
            ]);
            throw new Exception("Member not found.");
        }

        // Step 1: Initial form submission - send OTP
        if (isset($_POST['change_password']) && !isset($_POST['verify_otp'])) {
            $current_password = $_POST['current_password'] ?? '';
            $new_password = $_POST['new_password'] ?? '';
            $confirm_password = $_POST['confirm_password'] ?? '';

            // Validate current password
            $stmt = $pdo->prepare("SELECT password_hash FROM member_portal_accounts WHERE member_id = ?");
            $stmt->execute([$member_id]);
            $account = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$account || !password_verify($current_password, $account['password_hash'])) {
                $error = "Current password is incorrect.";
                logSecurityEvent($member_id, 'password_change_failed', [
                    'reason' => 'incorrect_current_password',
                    'ip' => $ip_address
                ]);
            } 
            // Validate new password complexity
            elseif (strlen($new_password) < 8 || 
                   !preg_match('/[A-Z]/', $new_password) || 
                   !preg_match('/[a-z]/', $new_password) || 
                   !preg_match('/[0-9]/', $new_password) || 
                   !preg_match('/[^A-Za-z0-9]/', $new_password)) {
                $error = 'Password must be at least 8 characters long and include uppercase, lowercase, numbers, and at least one special character.';
                logSecurityEvent($member_id, 'password_complexity_failed', [
                    'reason' => 'password_change',
                    'ip' => $ip_address
                ]);
            }
            // Check if new password is same as old
            elseif (password_verify($new_password, $account['password_hash'])) {
                $error = 'New password must be different from current password.';
                logSecurityEvent($member_id, 'password_change_failed', [
                    'reason' => 'same_as_old',
                    'ip' => $ip_address
                ]);
            }
            // Check if passwords match
            elseif ($new_password !== $confirm_password) {
                $error = 'New passwords do not match.';
                logSecurityEvent($member_id, 'password_mismatch', [
                    'reason' => 'password_change',
                    'ip' => $ip_address
                ]);
            } else {
                // Store the new password temporarily in session
                $_SESSION['temp_new_password'] = password_hash($new_password, PASSWORD_BCRYPT);
                
                // Generate and send OTP using the function from auth_functions.php
                error_log("DEBUG: Attempting to send OTP for member ID: " . $member_id);
                $sent = sendOTPByPreference($member, 'password_change');
                
                if ($sent) {
                    $step = 'verify_otp';
                    $success = "OTP sent successfully to your " . 
                              ($member['communication_preference'] === 'sms' ? 'phone' : 'email') . 
                              ". Please enter it below.";
                    logSecurityEvent($member_id, 'password_change_otp_sent', [
                        'method' => $member['communication_preference'],
                        'ip' => $ip_address
                    ]);
                    
                    // Store OTP verification state in session
                    $_SESSION['otp_verified'] = false;
                    $_SESSION['otp_purpose'] = 'password_change';
                    
                } else {
                    $error = "Failed to send OTP. Please check your contact information and try again.";
                    logSecurityEvent($member_id, 'password_change_otp_failed', [
                        'method' => $member['communication_preference'],
                        'email' => $member['email'],
                        'phone' => $member['phone_number'],
                        'ip' => $ip_address
                    ]);
                    unset($_SESSION['temp_new_password']);
                }
            }
        }

        // Step 2: OTP verification
        if (isset($_POST['verify_otp'])) {
            $entered_otp = implode('', $_POST['otp'] ?? []);
            
            error_log("DEBUG: OTP verification attempt - Entered OTP: " . $entered_otp . " for member: " . $member_id);

            // Verify OTP using the function from auth_functions.php
            if (verifyOTP($member_id, $entered_otp, 'password_change')) {
                // OTP verified - update password
                $stmt = $pdo->prepare("
                    UPDATE member_portal_accounts 
                    SET password_hash = ?, password_last_changed = NOW() 
                    WHERE member_id = ?
                ");
                $stmt->execute([$_SESSION['temp_new_password'], $member_id]);

                // Log the successful password change
                logSecurityEvent($member_id, 'password_change_success', [
                    'ip' => $ip_address,
                    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown',
                    'timestamp' => date('Y-m-d H:i:s')
                ]);

                // Send notification email
                sendPasswordChangeNotification($member_id);

                // Clear session data
                unset(
                    $_SESSION['temp_new_password'],
                    $_SESSION['otp_verified'],
                    $_SESSION['otp_purpose']
                );

                $step = 'success';
                $success = "Password changed successfully!";
                
            } else {
                // Invalid OTP
                if (!isset($_SESSION['password_change_attempts'])) {
                    $_SESSION['password_change_attempts'] = 1;
                } else {
                    $_SESSION['password_change_attempts']++;
                }
                
                $remaining_attempts = 3 - $_SESSION['password_change_attempts'];
                
                if ($remaining_attempts > 0) {
                    $error = "Invalid OTP. You have {$remaining_attempts} attempt(s) remaining.";
                } else {
                    $error = "Too many failed OTP attempts. Please start over.";
                    logSecurityEvent($member_id, 'password_change_otp_attempts_exceeded', [
                        'ip' => $ip_address,
                        'attempts' => $_SESSION['password_change_attempts']
                    ]);
                    unset($_SESSION['temp_new_password'], $_SESSION['password_change_attempts']);
                    $step = 'form';
                }
                
                logSecurityEvent($member_id, 'password_change_otp_invalid', [
                    'attempts' => $_SESSION['password_change_attempts'],
                    'remaining' => $remaining_attempts,
                    'ip' => $ip_address
                ]);
            }
        }

    } catch (Exception $e) {
        error_log("Password change error: " . $e->getMessage());
        $error = "An error occurred. Please try again.";
        logSecurityEvent($member_id, 'password_change_error', [
            'error' => $e->getMessage(),
            'ip' => $ip_address,
            'trace' => $e->getTraceAsString()
        ]);
    }

    // Regenerate CSRF token after POST
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/**
 * Send password change notification email
 */
function sendPasswordChangeNotification($memberId) {
    global $pdo;
    
    try {
        $smtpConfig = loadSmtpConfig();
        
        $stmt = $pdo->prepare("
            SELECT a.email, m.first_name, m.last_name 
            FROM member_portal_accounts a
            JOIN members m ON m.id = a.member_id
            WHERE a.member_id = ?
        ");
        $stmt->execute([$memberId]);
        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($member && !empty($member['email'])) {
            require_once __DIR__ . '/vendor/autoload.php';

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

            // SMTP configuration
            $mail->isSMTP();
            $mail->Host       = $smtpConfig['host'];
            $mail->SMTPAuth   = true;
            $mail->Username   = $smtpConfig['username'];
            $mail->Password   = $smtpConfig['password'];
            $mail->SMTPSecure = $smtpConfig['encryption'];
            $mail->Port       = $smtpConfig['port'];

            // Email content
            $mail->setFrom($smtpConfig['from_address'], $smtpConfig['from_name']);
            $mail->addAddress($member['email']);

            $mail->isHTML(true);
            $mail->Subject = 'Password Changed Successfully';
            $mail->Body = "
                <h2>Password Changed Successfully</h2>
                <p>Hello " . htmlspecialchars($member['first_name']) . ",</p>
                <p>Your password was successfully changed on " . date('F j, Y \a\t g:i A') . ".</p>
                <p>If you did not make this change, please contact support immediately.</p>
                <p>Thank you,<br>Member Portal Team</p>
            ";
            $mail->AltBody = "Hello " . $member['first_name'] . ",\n\nYour password was successfully changed on " . date('F j, Y \a\t g:i A') . ".\n\nIf you did not make this change, please contact support immediately.\n\nThank you,\nMember Portal Team";

            $mail->send();
            logSecurityEvent($memberId, 'password_change_email_sent', [
                'email' => $member['email'],
                'timestamp' => date('Y-m-d H:i:s')
            ]);
            error_log("DEBUG: Password change notification email sent to: " . $member['email']);
        } else {
            error_log("DEBUG: No email found for password change notification for member: " . $memberId);
        }
    } catch (Exception $e) {
        error_log("Failed to send password change email: " . $e->getMessage());
        logSecurityEvent($memberId, 'password_change_email_failed', [
            'error' => $e->getMessage(),
            'email' => $member['email'] ?? 'unknown'
        ]);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Change 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%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding: 20px 0;
        }
        
        .back-button {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .back-button:hover {
            text-decoration: underline;
        }
        
        .user-info {
            text-align: right;
        }
        
        .user-info .welcome {
            color: var(--secondary);
            font-size: 14px;
        }
        
        .user-info .username {
            font-weight: 600;
            color: var(--dark);
        }
        
        .password-container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            margin: 0 auto;
            overflow: hidden;
            animation: fadeIn 0.5s ease-out;
        }
        
        .password-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;
        }
        
        .password-header h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .password-header p {
            font-size: 14px;
            opacity: 0.9;
        }
        
        .password-body {
            padding: 32px;
        }
        
        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 32px;
            position: relative;
        }
        
        .step {
            display: flex;
            flex-direction: column;
            align-items: center;
            position: relative;
            z-index: 2;
        }
        
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--light);
            border: 2px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: var(--secondary);
            margin-bottom: 8px;
            transition: all 0.3s ease;
        }
        
        .step.active .step-number {
            background: var(--primary);
            border-color: var(--primary);
            color: white;
        }
        
        .step.completed .step-number {
            background: var(--success);
            border-color: var(--success);
            color: white;
        }
        
        .step-label {
            font-size: 12px;
            color: var(--secondary);
            font-weight: 500;
        }
        
        .step.active .step-label {
            color: var(--primary);
            font-weight: 600;
        }
        
        .step-line {
            position: absolute;
            top: 20px;
            left: 50px;
            right: 50px;
            height: 2px;
            background: var(--border);
            z-index: 1;
        }
        
        .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"],
        input[type="text"] {
            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,
        input[type="text"]: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);
        }
        
        .requirement.met i {
            color: var(--success);
        }
        
        .otp-section {
            position: relative;
        }
        
        .otp-input-container {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin: 20px 0;
            position: relative;
        }
        
        .otp-input {
            width: 50px;
            height: 60px;
            text-align: center;
            font-size: 24px;
            font-weight: 600;
            border: 2px solid var(--border);
            border-radius: 8px;
            transition: all 0.2s;
        }
        
        .otp-input:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
            outline: none;
        }
        
        .toggle-otp {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: var(--gray);
            cursor: pointer;
            padding: 8px;
            z-index: 2;
            border-radius: 4px;
        }
        
        .toggle-otp:hover {
            background: var(--light);
            color: var(--secondary);
        }
        
        .otp-timer {
            text-align: center;
            margin: 16px 0;
            font-size: 14px;
            color: var(--secondary);
        }
        
        .resend-otp {
            text-align: center;
            margin: 16px 0;
        }
        
        .resend-link {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
            cursor: pointer;
        }
        
        .resend-link:hover {
            text-decoration: underline;
        }
        
        .resend-link.disabled {
            color: var(--gray);
            cursor: not-allowed;
        }
        
        .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;
        }
        
        .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);
        }
        
        .success-container {
            text-align: center;
            padding: 40px 20px;
        }
        
        .success-icon {
            font-size: 64px;
            color: var(--success);
            margin-bottom: 20px;
        }
        
        .success-container h2 {
            color: var(--success);
            margin-bottom: 16px;
        }
        
        .success-container p {
            color: var(--secondary);
            margin-bottom: 24px;
        }
        
        .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: 768px) {
            .header {
                flex-direction: column;
                gap: 15px;
                text-align: center;
            }
            
            .user-info {
                text-align: center;
            }
            
            .password-container {
                margin: 0 10px;
            }
            
            .password-body {
                padding: 24px;
            }
            
            .otp-input-container {
                gap: 5px;
            }
            
            .otp-input {
                width: 45px;
                height: 55px;
                font-size: 20px;
            }
            
            .toggle-otp {
                right: 5px;
                padding: 6px;
            }
        }
    </style>
</head>
    <?php include './partials/layouts/layoutTop.php'; ?>

<body>
    <div class="container">
        <div class="password-container">
            <div class="password-header">
                <div class="security-indicator">
                    <i class="fas fa-lock"></i>
                    <span>Secure</span>
                </div>
                <h1>Change Password</h1>
                <p>Secure your account with a new password</p>
            </div>
            
            <div class="password-body">
                <!-- Step Indicator -->
                <div class="step-indicator">
                    <div class="step-line"></div>
                    <div class="step <?php echo $step === 'form' ? 'active' : ($step === 'verify_otp' || $step === 'success' ? 'completed' : ''); ?>">
                        <div class="step-number">1</div>
                        <div class="step-label">Enter Details</div>
                    </div>
                    <div class="step <?php echo $step === 'verify_otp' ? 'active' : ($step === 'success' ? 'completed' : ''); ?>">
                        <div class="step-number">2</div>
                        <div class="step-label">Verify OTP</div>
                    </div>
                    <div class="step <?php echo $step === 'success' ? 'active' : ''; ?>">
                        <div class="step-number">3</div>
                        <div class="step-label">Success</div>
                    </div>
                </div>
                
                <?php if ($error): ?>
                    <div class="error-message">
                        <i class="fas fa-exclamation-circle"></i>
                        <span><?php echo htmlspecialchars($error); ?></span>
                    </div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="success-message">
                        <i class="fas fa-check-circle"></i>
                        <span><?php echo htmlspecialchars($success); ?></span>
                    </div>
                <?php endif; ?>
                
                <!-- Step 1: Password Form -->
                <?php if ($step === 'form'): ?>
                    <form method="POST" id="passwordForm">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        
                        <div class="form-group">
                            <label for="current_password">Current Password</label>
                            <div class="input-group">
                                <input type="password" id="current_password" name="current_password" required placeholder="Enter current password" autocomplete="current-password">
                                <button type="button" class="toggle-password" id="toggleCurrentPassword">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="new_password">New Password</label>
                            <div class="input-group">
                                <input type="password" id="new_password" name="new_password" required placeholder="Enter new password" autocomplete="new-password">
                                <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 New Password</label>
                            <div class="input-group">
                                <input type="password" id="confirm_password" name="confirm_password" required placeholder="Confirm new password" autocomplete="new-password">
                                <button type="button" class="toggle-password" id="toggleConfirmPassword">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div id="passwordMatch" style="margin-top: 8px; font-size: 12px;"></div>
                        </div>
                        
                        <button type="submit" name="change_password" class="submit-btn" id="submitButton">
                            <span>Continue to OTP Verification</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>
                
                <!-- Step 2: OTP Verification -->
                <?php elseif ($step === 'verify_otp'): ?>
                    <form method="POST" id="otpForm">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
                        
                        <div style="text-align: center; margin-bottom: 24px;">
                            <p>Enter the 6-digit OTP sent to your registered contact method.</p>
                            <p><small>If you don't receive the OTP, please check your spam folder or ensure your contact information is up to date.</small></p>
                        </div>
                        
                        <div class="otp-section">
                            <div class="otp-input-container">
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" autocomplete="one-time-code" required>
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                                <input type="password" class="otp-input" name="otp[]" maxlength="1" pattern="[0-9]" inputmode="numeric" required>
                                <button type="button" class="toggle-otp" id="toggleOtpVisibility">
                                    <i class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="otp-timer" id="otpTimer">
                            OTP expires in: <span id="countdown">10:00</span>
                        </div>
                        
                        <div class="resend-otp">
                            <a href="#" class="resend-link" id="resendOtp" onclick="resendOTP()">Resend OTP</a>
                        </div>
                        
                        <button type="submit" name="verify_otp" class="submit-btn" id="verifyButton">
                            <span>Verify OTP</span>
                            <div class="spinner" style="display: none;"></div>
                        </button>
                        
                        <div style="text-align: center; margin-top: 16px;">
                            <a href="dashboard.php" style="color: var(--secondary); text-decoration: none;">Cancel and return to dashboard</a>
                        </div>
                    </form>
                
                <!-- Step 3: Success -->
                <?php elseif ($step === 'success'): ?>
                    <div class="success-container">
                        <div class="success-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h2>Password Changed Successfully!</h2>
                        <p>Your password has been updated. You'll be redirected to your dashboard shortly.</p>
                        <a href="dashboard.php" class="submit-btn" style="text-decoration: none; display: inline-block; width: auto; padding: 12px 24px;">
                            Go to Dashboard
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const passwordForm = document.getElementById('passwordForm');
            const otpForm = document.getElementById('otpForm');
            const submitButton = document.getElementById('submitButton');
            const verifyButton = document.getElementById('verifyButton');
            const toggleOtpBtn = document.getElementById('toggleOtpVisibility');
            
            // Password toggle functionality
            function setupPasswordToggle(toggleButtonId, passwordInputId) {
                const toggleButton = document.getElementById(toggleButtonId);
                const passwordInput = document.getElementById(passwordInputId);
                
                if (toggleButton && passwordInput) {
                    toggleButton.addEventListener('click', function() {
                        const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                        passwordInput.setAttribute('type', type);
                        
                        const eyeIcon = this.querySelector('i');
                        eyeIcon.classList.toggle('fa-eye');
                        eyeIcon.classList.toggle('fa-eye-slash');
                    });
                }
            }
            
            setupPasswordToggle('toggleCurrentPassword', 'current_password');
            setupPasswordToggle('toggleNewPassword', 'new_password');
            setupPasswordToggle('toggleConfirmPassword', 'confirm_password');
            
            // OTP visibility toggle
            if (toggleOtpBtn) {
                toggleOtpBtn.addEventListener('click', function() {
                    const otpInputs = document.querySelectorAll('.otp-input');
                    const isCurrentlyVisible = otpInputs[0].getAttribute('type') === 'text';
                    
                    otpInputs.forEach(input => {
                        input.setAttribute('type', isCurrentlyVisible ? 'password' : 'text');
                    });
                    
                    const eyeIcon = this.querySelector('i');
                    eyeIcon.classList.toggle('fa-eye');
                    eyeIcon.classList.toggle('fa-eye-slash');
                    
                    // Update button title for accessibility
                    this.setAttribute('title', isCurrentlyVisible ? 'Show OTP' : 'Hide OTP');
                });
            }
            
            // Password strength indicator
            const newPasswordInput = document.getElementById('new_password');
            const confirmPasswordInput = document.getElementById('confirm_password');
            const strengthMeter = document.getElementById('strengthMeter');
            const passwordMatch = document.getElementById('passwordMatch');
            
            if (newPasswordInput) {
                newPasswordInput.addEventListener('input', function() {
                    const password = this.value;
                    
                    // 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
                    let strength = 0;
                    if (hasLength) strength += 20;
                    if (hasUppercase) strength += 20;
                    if (hasLowercase) strength += 20;
                    if (hasNumber) strength += 20;
                    if (hasSpecial) strength += 20;
                    
                    if (strengthMeter) {
                        strengthMeter.style.width = strength + '%';
                        
                        // Set color based on strength
                        if (strength < 60) {
                            strengthMeter.style.backgroundColor = '#ef4444';
                        } else if (strength < 100) {
                            strengthMeter.style.backgroundColor = '#f59e0b';
                        } else {
                            strengthMeter.style.backgroundColor = '#10b981';
                        }
                    }
                    
                    validatePasswordMatch();
                });
            }
            
            // Password match validation
            function validatePasswordMatch() {
                if (!newPasswordInput || !confirmPasswordInput || !passwordMatch) return;
                
                const newPassword = newPasswordInput.value;
                const confirmPassword = confirmPasswordInput.value;
                
                if (confirmPassword === '') {
                    passwordMatch.textContent = '';
                    passwordMatch.style.color = '';
                } else if (newPassword === confirmPassword) {
                    passwordMatch.innerHTML = '<i class="fas fa-check-circle"></i> Passwords match';
                    passwordMatch.style.color = '#10b981';
                } else {
                    passwordMatch.innerHTML = '<i class="fas fa-times-circle"></i> Passwords do not match';
                    passwordMatch.style.color = '#ef4444';
                }
            }
            
            if (confirmPasswordInput) {
                confirmPasswordInput.addEventListener('input', validatePasswordMatch);
            }
            
            // OTP input handling
            const otpInputs = document.querySelectorAll('.otp-input');
            if (otpInputs.length > 0) {
                otpInputs.forEach((input, index) => {
                    input.addEventListener('input', function() {
                        // Only allow numbers
                        this.value = this.value.replace(/[^0-9]/g, '');
                        
                        if (this.value.length === 1 && index < otpInputs.length - 1) {
                            otpInputs[index + 1].focus();
                        }
                        
                        // Auto-submit when all fields are filled
                        const allFilled = Array.from(otpInputs).every(input => input.value.length === 1);
                        if (allFilled) {
                            document.getElementById('verifyButton').focus();
                        }
                    });
                    
                    input.addEventListener('keydown', function(e) {
                        if (e.key === 'Backspace' && this.value === '' && index > 0) {
                            otpInputs[index - 1].focus();
                        }
                        
                        // Allow paste
                        if (e.key === 'v' && (e.ctrlKey || e.metaKey)) {
                            setTimeout(() => {
                                const pastedText = this.value;
                                if (pastedText.length === 6 && /^\d+$/.test(pastedText)) {
                                    otpInputs.forEach((input, i) => {
                                        input.value = pastedText[i] || '';
                                    });
                                    document.getElementById('verifyButton').focus();
                                }
                            }, 10);
                        }
                    });
                    
                    // Prevent non-numeric input
                    input.addEventListener('keypress', function(e) {
                        if (!/[0-9]/.test(e.key)) {
                            e.preventDefault();
                        }
                    });
                });
                
                // Auto-focus first OTP input
                otpInputs[0].focus();
            }
            
            // OTP Countdown Timer
            const otpTimer = document.getElementById('otpTimer');
            const countdownElement = document.getElementById('countdown');
            const resendOtp = document.getElementById('resendOtp');
            
            if (countdownElement) {
                let timeLeft = 600; // 10 minutes in seconds
                
                const countdown = setInterval(function() {
                    const minutes = Math.floor(timeLeft / 60);
                    const seconds = timeLeft % 60;
                    
                    countdownElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                    
                    if (timeLeft <= 0) {
                        clearInterval(countdown);
                        if (otpTimer) otpTimer.style.display = 'none';
                        if (resendOtp) {
                            resendOtp.classList.remove('disabled');
                            resendOtp.onclick = function() { location.reload(); };
                        }
                    } else {
                        timeLeft--;
                    }
                }, 1000);
            }
            
            // Form submission handlers
            if (passwordForm) {
                passwordForm.addEventListener('submit', function(e) {
                    const currentPassword = document.getElementById('current_password').value;
                    const newPassword = document.getElementById('new_password').value;
                    const confirmPassword = document.getElementById('confirm_password').value;
                    
                    if (!currentPassword || !newPassword || !confirmPassword) {
                        e.preventDefault();
                        this.classList.add('shake');
                        setTimeout(() => {
                            this.classList.remove('shake');
                        }, 500);
                        return;
                    }
                    
                    if (newPassword !== confirmPassword) {
                        e.preventDefault();
                        passwordMatch.innerHTML = '<i class="fas fa-exclamation-circle"></i> Please make sure passwords match before submitting';
                        passwordMatch.style.color = '#ef4444';
                        this.classList.add('shake');
                        setTimeout(() => {
                            this.classList.remove('shake');
                        }, 500);
                        return;
                    }
                    
                    const spinner = submitButton.querySelector('.spinner');
                    const buttonText = submitButton.querySelector('span');
                    
                    spinner.style.display = 'block';
                    buttonText.textContent = 'Sending OTP...';
                    submitButton.classList.add('loading');
                });
            }
            
            if (otpForm) {
                otpForm.addEventListener('submit', function(e) {
                    const otpInputs = this.querySelectorAll('.otp-input');
                    let otp = '';
                    
                    otpInputs.forEach(input => {
                        otp += input.value;
                    });
                    
                    if (otp.length !== 6) {
                        e.preventDefault();
                        this.classList.add('shake');
                        setTimeout(() => {
                            this.classList.remove('shake');
                        }, 500);
                        return;
                    }
                    
                    const spinner = verifyButton.querySelector('.spinner');
                    const buttonText = verifyButton.querySelector('span');
                    
                    spinner.style.display = 'block';
                    buttonText.textContent = 'Verifying...';
                    verifyButton.classList.add('loading');
                });
            }
            
            // Auto-redirect on success
            <?php if ($step === 'success'): ?>
                setTimeout(function() {
                    window.location.href = 'dashboard.php';
                }, 5000);
            <?php endif; ?>
        });
        
        function resendOTP() {
            // This would typically make an AJAX call to resend OTP
            // For now, we'll just reload the page to simulate resend
            window.location.reload();
        }
    </script>
</body>
<?php include './partials/layouts/layoutBottom.php'; ?>
</html>