<!-- OTP Verification Modal -->
<div class="modal fade" id="otpVerificationModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header border-0 pb-0">
                <h5 class="modal-title">Verify Transaction</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" onclick="cancelOtpVerification()"></button>
            </div>
            <div class="modal-body text-center">
                <!-- Send OTP Step -->
                <div id="otpSendStep">
                    <div class="mb-3">
                        <ion-icon name="mail-outline" style="font-size: 64px; color: #1E74FD;"></ion-icon>
                    </div>
                    <h4>Email Verification Required</h4>
                    <p class="text-muted mb-3">
                        For your security, we'll send a verification code to your registered email address.
                    </p>
                    <p class="mb-4">
                        <strong id="otpUserEmail"></strong>
                    </p>
                    <button type="button" class="btn btn-primary btn-lg btn-block" id="sendOtpBtn" onclick="sendOtp()">
                        <ion-icon name="send-outline"></ion-icon> Send Verification Code
                    </button>
                </div>
                
                <!-- Enter OTP Step -->
                <div id="otpEnterStep" style="display: none;">
                    <div class="mb-3">
                        <ion-icon name="shield-checkmark-outline" style="font-size: 64px; color: #1E74FD;"></ion-icon>
                    </div>
                    <h4>Enter Verification Code</h4>
                    <p class="text-muted mb-2">
                        We've sent a 6-digit code to <strong id="otpSentEmail"></strong>
                    </p>
                    <p class="text-muted small mb-3" id="otpExpiryText">
                        Code expires in <span id="otpCountdown">5:00</span>
                    </p>
                    
                    <div class="otp-input-group mb-4">
                        <input type="text" class="otp-input" maxlength="1" data-index="0" inputmode="numeric" pattern="[0-9]">
                        <input type="text" class="otp-input" maxlength="1" data-index="1" inputmode="numeric" pattern="[0-9]">
                        <input type="text" class="otp-input" maxlength="1" data-index="2" inputmode="numeric" pattern="[0-9]">
                        <input type="text" class="otp-input" maxlength="1" data-index="3" inputmode="numeric" pattern="[0-9]">
                        <input type="text" class="otp-input" maxlength="1" data-index="4" inputmode="numeric" pattern="[0-9]">
                        <input type="text" class="otp-input" maxlength="1" data-index="5" inputmode="numeric" pattern="[0-9]">
                    </div>
                    
                    <div id="otpError" class="alert alert-danger mb-3" style="display: none;"></div>
                    
                    <button type="button" class="btn btn-primary btn-lg btn-block mb-3" id="verifyOtpBtn" onclick="verifyOtp()" disabled>
                        <ion-icon name="checkmark-outline"></ion-icon> Verify & Continue
                    </button>
                    
                    <p class="text-muted small mb-0">
                        Didn't receive the code? 
                        <a href="#" id="resendOtpLink" onclick="resendOtp(); return false;">Resend</a>
                        <span id="resendCooldown" style="display: none;">
                            (wait <span id="resendCountdown">60</span>s)
                        </span>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.otp-input-group {
    display: flex;
    justify-content: center;
    gap: 8px;
}
.otp-input {
    width: 45px;
    height: 55px;
    text-align: center;
    font-size: 24px;
    font-weight: bold;
    border: 2px solid #e1e1e1;
    border-radius: 10px;
    background: var(--bs-body-bg);
    color: var(--bs-body-color);
    transition: border-color 0.2s;
}
.otp-input:focus {
    border-color: #1E74FD;
    outline: none;
    box-shadow: 0 0 0 3px rgba(30, 116, 253, 0.2);
}
.otp-input.filled {
    border-color: #1E74FD;
    background-color: rgba(30, 116, 253, 0.1);
}
.otp-input.error {
    border-color: #dc3545;
    animation: shake 0.5s;
}
@keyframes shake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    75% { transform: translateX(5px); }
}
</style>

<script>
// OTP Verification System
var otpConfig = {
    purpose: 'transaction',
    formId: null,
    callback: null,
    expiryTime: null,
    resendCooldown: 0,
    countdownInterval: null,
    resendInterval: null
};

/**
 * Initialize OTP verification for a form
 * @param {string} formId - The form ID to protect
 * @param {string} purpose - Purpose of the OTP (transaction, transfer, etc.)
 * @param {function} callback - Callback to execute after successful verification
 */
function initOtpVerification(formId, purpose, callback) {
    otpConfig.formId = formId;
    otpConfig.purpose = purpose || 'transaction';
    otpConfig.callback = callback;
    
    // Mask email for display
    var userEmail = '<?php 
        if (isset($user) && !empty($user->email)) {
            $email = $user->email;
            $parts = explode("@", $email);
            if (count($parts) === 2) {
                $name = $parts[0];
                $domain = $parts[1];
                if (strlen($name) <= 2) {
                    $masked_name = str_repeat("*", strlen($name));
                } else {
                    $masked_name = substr($name, 0, 2) . str_repeat("*", strlen($name) - 2);
                }
                echo $masked_name . "@" . $domain;
            } else {
                echo $email;
            }
        }
    ?>';
    document.getElementById('otpUserEmail').textContent = userEmail;
}

/**
 * Request OTP verification before form submission
 */
function requestOtpVerification() {
    // Reset modal state
    document.getElementById('otpSendStep').style.display = 'block';
    document.getElementById('otpEnterStep').style.display = 'none';
    document.getElementById('otpError').style.display = 'none';
    
    // Clear OTP inputs
    document.querySelectorAll('.otp-input').forEach(function(input) {
        input.value = '';
        input.classList.remove('filled', 'error');
    });
    
    // Show modal
    var modal = new bootstrap.Modal(document.getElementById('otpVerificationModal'));
    modal.show();
}

/**
 * Send OTP to user's email
 */
function sendOtp() {
    var btn = document.getElementById('sendOtpBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Sending...';
    
    fetch('<?php echo base_url("otp/send"); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            purpose: otpConfig.purpose,
            <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
        })
    })
    .then(response => response.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '<ion-icon name="send-outline"></ion-icon> Send Verification Code';
        
        if (data.success) {
            // Show OTP entry step
            document.getElementById('otpSendStep').style.display = 'none';
            document.getElementById('otpEnterStep').style.display = 'block';
            document.getElementById('otpSentEmail').textContent = (data.data && data.data.masked_email) || '';
            
            // Start countdown timer
            startExpiryCountdown((data.data && data.data.expires_in) || 300);
            
            // Start resend cooldown
            startResendCooldown(60);
            
            // Focus first input
            document.querySelector('.otp-input[data-index="0"]').focus();
        } else {
            showOtpError(data.message);
        }
    })
    .catch(error => {
        btn.disabled = false;
        btn.innerHTML = '<ion-icon name="send-outline"></ion-icon> Send Verification Code';
        showOtpError('Failed to send OTP. Please try again.');
    });
}

/**
 * Verify the entered OTP
 */
function verifyOtp() {
    var otpCode = '';
    document.querySelectorAll('.otp-input').forEach(function(input) {
        otpCode += input.value;
    });
    
    if (otpCode.length !== 6) {
        showOtpError('Please enter all 6 digits');
        return;
    }
    
    var btn = document.getElementById('verifyOtpBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Verifying...';
    
    fetch('<?php echo base_url("otp/verify"); ?>', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        },
        body: JSON.stringify({
            otp: otpCode,
            purpose: otpConfig.purpose,
            <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Close modal
            bootstrap.Modal.getInstance(document.getElementById('otpVerificationModal')).hide();
            
            // Clear timers
            clearInterval(otpConfig.countdownInterval);
            clearInterval(otpConfig.resendInterval);
            
            // Execute callback or submit form
            if (typeof otpConfig.callback === 'function') {
                otpConfig.callback();
            } else if (otpConfig.formId) {
                // Add verified flag to form and submit
                var form = document.getElementById(otpConfig.formId);
                if (form) {
                    var input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'otp_verified';
                    input.value = '1';
                    form.appendChild(input);
                    form.submit();
                }
            }
        } else {
            btn.disabled = false;
            btn.innerHTML = '<ion-icon name="checkmark-outline"></ion-icon> Verify & Continue';
            showOtpError(data.message);
            
            // Shake inputs on error
            document.querySelectorAll('.otp-input').forEach(function(input) {
                input.classList.add('error');
                setTimeout(() => input.classList.remove('error'), 500);
            });
        }
    })
    .catch(error => {
        btn.disabled = false;
        btn.innerHTML = '<ion-icon name="checkmark-outline"></ion-icon> Verify & Continue';
        showOtpError('Verification failed. Please try again.');
    });
}

/**
 * Resend OTP
 */
function resendOtp() {
    if (otpConfig.resendCooldown > 0) return;
    sendOtp();
}

/**
 * Cancel OTP verification
 */
function cancelOtpVerification() {
    clearInterval(otpConfig.countdownInterval);
    clearInterval(otpConfig.resendInterval);
}

/**
 * Show error message
 */
function showOtpError(message) {
    var errorDiv = document.getElementById('otpError');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
}

/**
 * Start expiry countdown
 */
function startExpiryCountdown(seconds) {
    clearInterval(otpConfig.countdownInterval);
    otpConfig.expiryTime = seconds;
    
    var countdownEl = document.getElementById('otpCountdown');
    
    otpConfig.countdownInterval = setInterval(function() {
        otpConfig.expiryTime--;
        var mins = Math.floor(otpConfig.expiryTime / 60);
        var secs = otpConfig.expiryTime % 60;
        countdownEl.textContent = mins + ':' + (secs < 10 ? '0' : '') + secs;
        
        if (otpConfig.expiryTime <= 0) {
            clearInterval(otpConfig.countdownInterval);
            showOtpError('OTP has expired. Please request a new one.');
            document.getElementById('verifyOtpBtn').disabled = true;
        }
    }, 1000);
}

/**
 * Start resend cooldown
 */
function startResendCooldown(seconds) {
    clearInterval(otpConfig.resendInterval);
    otpConfig.resendCooldown = seconds;
    
    var link = document.getElementById('resendOtpLink');
    var cooldownSpan = document.getElementById('resendCooldown');
    var countdownEl = document.getElementById('resendCountdown');
    
    link.style.display = 'none';
    cooldownSpan.style.display = 'inline';
    
    otpConfig.resendInterval = setInterval(function() {
        otpConfig.resendCooldown--;
        countdownEl.textContent = otpConfig.resendCooldown;
        
        if (otpConfig.resendCooldown <= 0) {
            clearInterval(otpConfig.resendInterval);
            link.style.display = 'inline';
            cooldownSpan.style.display = 'none';
        }
    }, 1000);
}

// Handle OTP input
document.addEventListener('DOMContentLoaded', function() {
    var otpInputs = document.querySelectorAll('.otp-input');
    
    otpInputs.forEach(function(input, index) {
        input.addEventListener('input', function(e) {
            // Only allow numbers
            this.value = this.value.replace(/[^0-9]/g, '');
            
            if (this.value.length === 1) {
                this.classList.add('filled');
                // Move to next input
                if (index < otpInputs.length - 1) {
                    otpInputs[index + 1].focus();
                }
            } else {
                this.classList.remove('filled');
            }
            
            // Enable verify button if all filled
            var allFilled = Array.from(otpInputs).every(inp => inp.value.length === 1);
            document.getElementById('verifyOtpBtn').disabled = !allFilled;
        });
        
        input.addEventListener('keydown', function(e) {
            // Handle backspace
            if (e.key === 'Backspace' && this.value === '' && index > 0) {
                otpInputs[index - 1].focus();
                otpInputs[index - 1].value = '';
                otpInputs[index - 1].classList.remove('filled');
            }
            
            // Handle paste
            if (e.key === 'v' && (e.ctrlKey || e.metaKey)) {
                e.preventDefault();
                navigator.clipboard.readText().then(function(text) {
                    var digits = text.replace(/[^0-9]/g, '').substring(0, 6);
                    for (var i = 0; i < digits.length; i++) {
                        if (otpInputs[i]) {
                            otpInputs[i].value = digits[i];
                            otpInputs[i].classList.add('filled');
                        }
                    }
                    if (digits.length === 6) {
                        document.getElementById('verifyOtpBtn').disabled = false;
                    }
                });
            }
        });
        
        // Handle paste event
        input.addEventListener('paste', function(e) {
            e.preventDefault();
            var pasteData = e.clipboardData.getData('text');
            var digits = pasteData.replace(/[^0-9]/g, '').substring(0, 6);
            for (var i = 0; i < digits.length; i++) {
                if (otpInputs[i]) {
                    otpInputs[i].value = digits[i];
                    otpInputs[i].classList.add('filled');
                }
            }
            if (digits.length === 6) {
                document.getElementById('verifyOtpBtn').disabled = false;
            }
        });
    });
});
</script>
