<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.use_strict_mode', 1);
    ini_set('session.use_only_cookies', 1);
    session_start();
}

// Load the exact same config as the real page
$dataDir = __DIR__ . '/data';
$headerConfigFile = $dataDir . '/header_config.json';
$headerConfig = ['languages' => [], 'currencies' => [], 'help_link' => '/contact.php'];

if (file_exists($headerConfigFile)) {
    $headerConfigData = @json_decode(file_get_contents($headerConfigFile), true);
    if (is_array($headerConfigData)) {
        $headerConfig = $headerConfigData;
    }
}

$selected_lang = isset($_SESSION['selected_language']) ? strtolower($_SESSION['selected_language']) : 'it';
$selected_currency = isset($_SESSION['selected_currency']) ? strtolower($_SESSION['selected_currency']) : 'eur';
?>
<!DOCTYPE html>
<html>
<head>
    <title>Direct Dropdown Test</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: Arial; }
        .promo-strip { background:#1a1a1a; color:#fff; padding:12px 18px; font-size:12px; font-weight:600; display:flex; justify-content:space-between; align-items:center; gap:25px; flex-wrap:wrap; }
        select { background:#1a1a1a; color:#fff; border:none; cursor:pointer; font-size:12px; font-weight:600; outline:none; padding:4px 6px; }
        .main { padding: 40px; }
        .test-section { background: #f0f0f0; padding: 20px; margin: 20px 0; border: 1px solid #ccc; }
        button { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; margin: 5px; }
        #console { background: black; color: #0f0; padding: 15px; font-family: monospace; font-size: 12px; height: 300px; overflow-y: auto; margin-top: 20px; }
        .log { margin: 2px 0; }
    </style>
</head>
<body>
    <!-- EXACT COPY OF PROMO STRIP -->
    <div class="promo-strip">
        <div style="display:flex; align-items:center; gap:25px;">
            <span>FREE RETURNS & STANDARD SHIPPING ON ORDERS $99+</span>
        </div>
        <div style="display:flex; align-items:center; gap:25px;">
            <a href="/contact.php" style="color:#fff; text-decoration:none;">? NEED HELP</a>
            
            <!-- Language Dropdown -->
            <select id="languageSelect" onchange="console.log('DROPDOWN CHANGED'); changeLanguage(this)">
                <?php
                foreach ($headerConfig['languages'] as $lang) {
                    $code = strtolower($lang['code']);
                    $selected = ($code === $selected_lang) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($code) . '" ' . $selected . '>' . htmlspecialchars($lang['label']) . '</option>';
                }
                ?>
            </select>
            
            <!-- Currency Dropdown -->
            <select id="currencySelect" onchange="console.log('CURRENCY DROPDOWN CHANGED'); changeCurrency(this)">
                <?php
                foreach ($headerConfig['currencies'] as $curr) {
                    $code = strtolower($curr['code']);
                    $selected = ($code === $selected_currency) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($code) . '" ' . $selected . '>' . htmlspecialchars($curr['label']) . '</option>';
                }
                ?>
            </select>
        </div>
    </div>
    
    <div class="main">
        <h1>Direct Dropdown Test</h1>
        
        <div class="test-section">
            <h3>Current Session State</h3>
            <p>Language: <strong><?php echo htmlspecialchars($selected_lang); ?></strong></p>
            <p>Currency: <strong><?php echo htmlspecialchars($selected_currency); ?></strong></p>
        </div>
        
        <div class="test-section">
            <h3>Try the Dropdowns</h3>
            <p>Change the dropdowns at the top. The console below should show what's happening.</p>
        </div>
        
        <h3>JavaScript Console</h3>
        <div id="console"></div>
    </div>
    
    <script>
    // Override console.log to show in page
    const originalLog = console.log;
    function myLog(...args) {
        originalLog(...args);
        const msg = args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ');
        const consoleEl = document.getElementById('console');
        const logEl = document.createElement('div');
        logEl.className = 'log';
        logEl.textContent = msg;
        consoleEl.appendChild(logEl);
        consoleEl.scrollTop = consoleEl.scrollHeight;
    }
    console.log = myLog;
    console.error = (...args) => {
        myLog('❌ ERROR:', ...args);
    };
    
    console.log('Page loaded');
    console.log('Language select ID:', document.getElementById('languageSelect') ? 'FOUND' : 'NOT FOUND');
    console.log('Currency select ID:', document.getElementById('currencySelect') ? 'FOUND' : 'NOT FOUND');
    console.log('changeLanguage function:', typeof changeLanguage);
    console.log('changeCurrency function:', typeof changeCurrency);
    
    // Change language
    function changeLanguage(selectElement) {
        const langSelect = selectElement || document.getElementById('languageSelect');
        if (!langSelect) {
            console.error('Language select not found');
            return;
        }
        
        const selectedLang = langSelect.value;
        console.log('🔄 Language change initiated:', selectedLang);
        
        let apiUrl = '/emporio-sport/api_set_preference.php';
        console.log('🌐 API URL:', apiUrl);
        
        fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'language', value: selectedLang })
        })
        .then(response => {
            console.log('✅ HTTP Status:', response.status);
            if (!response.ok) throw new Error('HTTP ' + response.status);
            return response.json();
        })
        .then(data => {
            console.log('📦 Response:', JSON.stringify(data));
            if (data.success) {
                console.log('✅ Language changed to:', data.language_name);
                alert('✓ Language changed to: ' + data.language_name);
                setTimeout(() => location.reload(), 500);
            } else {
                console.error('API Error:', data.message);
                alert('✗ Error: ' + data.message);
            }
        })
        .catch(err => {
            console.error('Network error:', err.message);
            alert('✗ Error: ' + err.message);
        });
    }
    
    // Change currency
    function changeCurrency(selectElement) {
        const currSelect = selectElement || document.getElementById('currencySelect');
        if (!currSelect) {
            console.error('Currency select not found');
            return;
        }
        
        const selectedCurr = currSelect.value;
        console.log('🔄 Currency change initiated:', selectedCurr);
        
        let apiUrl = '/emporio-sport/api_set_preference.php';
        console.log('🌐 API URL:', apiUrl);
        
        fetch(apiUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'currency', value: selectedCurr })
        })
        .then(response => {
            console.log('✅ HTTP Status:', response.status);
            if (!response.ok) throw new Error('HTTP ' + response.status);
            return response.json();
        })
        .then(data => {
            console.log('📦 Response:', JSON.stringify(data));
            if (data.success) {
                console.log('✅ Currency changed to:', data.currency);
                alert('✓ Currency changed to: ' + data.currency.toUpperCase());
                setTimeout(() => location.reload(), 500);
            } else {
                console.error('API Error:', data.message);
                alert('✗ Error: ' + data.message);
            }
        })
        .catch(err => {
            console.error('Network error:', err.message);
            alert('✗ Error: ' + err.message);
        });
    }
    </script>
</body>
</html>
