<?php
// Exact replica of header setup
if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.use_strict_mode', 1);
    ini_set('session.use_only_cookies', 1);
    session_start();
}

$dataDir = __DIR__ . '/data';
$headerConfigFile = $dataDir . '/header_config.json';
$headerConfig = ['languages' => [], 'currencies' => []];

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

$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>Header Dropdown Test</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        .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;
            position:static;
        }
        
        select {
            background:#1a1a1a;
            color:#fff;
            border:none;
            cursor:pointer;
            font-size:12px;
            font-weight:600;
            outline:none;
            padding:4px 6px;
        }
        
        .main {
            padding: 40px;
            background: white;
        }
        
        .test-section {
            background: #f5f5f5;
            padding: 20px;
            margin: 20px 0;
            border-left: 4px solid #007bff;
        }
        
        button {
            padding: 8px 16px;
            margin: 5px;
            background: #28a745;
            color: white;
            border: none;
            cursor: pointer;
            border-radius: 3px;
        }
        
        button:hover { background: #218838; }
        
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 3px;
        }
        
        .status.ok { background: #d4edda; border: 1px solid #c3e6cb; color: #155724; }
        .status.error { background: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; }
        
        code {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <!-- EXACT REPLICA OF HEADER DROPDOWNS -->
    <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; display:flex; align-items:center; gap:6px;" title="Need Help">
                <span style="font-size:14px;">❓</span>
                <span>NEED HELP</span>
            </a>
            
            <!-- Language Dropdown -->
            <select id="languageSelect" onchange="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="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>🧪 Language & Currency Dropdown Test</h1>
        
        <div class="test-section">
            <h3>Current Session State</h3>
            <div class="status ok">
                <p><strong>Language:</strong> <code><?php echo htmlspecialchars($selected_lang); ?></code></p>
                <p><strong>Currency:</strong> <code><?php echo htmlspecialchars($selected_currency); ?></code></p>
                <p><strong>Session ID:</strong> <code><?php echo substr(session_id(), 0, 15); ?>...</code></p>
            </div>
        </div>
        
        <div class="test-section">
            <h3>Quick Test Actions</h3>
            <p>Click buttons below OR use dropdowns above:</p>
            
            <div>
                <strong>Set Language:</strong>
                <button onclick="testLang('it')">Italian</button>
                <button onclick="testLang('en')">English</button>
                <button onclick="testLang('es')">Spanish</button>
                <button onclick="testLang('de')">German</button>
            </div>
            
            <div style="margin-top: 15px;">
                <strong>Set Currency:</strong>
                <button onclick="testCurr('eur')">EUR</button>
                <button onclick="testCurr('usd')">USD</button>
                <button onclick="testCurr('gbp')">GBP</button>
                <button onclick="testCurr('cad')">CAD</button>
            </div>
        </div>
        
        <div id="results" style="display: none;" class="test-section">
            <h3>Test Results</h3>
            <div id="resultsContent"></div>
        </div>
    </div>
    
    <script>
    // Test language
    function testLang(code) {
        console.log('Test: Language ' + code);
        callAPI('language', code);
    }
    
    // Test currency
    function testCurr(code) {
        console.log('Test: Currency ' + code);
        callAPI('currency', code);
    }
    
    // Call API
    function callAPI(type, value) {
        const resultsDiv = document.getElementById('results');
        const resultsContent = document.getElementById('resultsContent');
        resultsDiv.style.display = 'block';
        resultsContent.innerHTML = '<p>Testing ' + type + ' = ' + value + '...</p>';
        
        fetch('/emporio-sport/api_set_preference.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: type, value: value })
        })
        .then(r => {
            console.log('Status: ' + r.status);
            resultsContent.innerHTML += '<p>HTTP Status: ' + r.status + '</p>';
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.json();
        })
        .then(d => {
            console.log('Response: ', d);
            resultsContent.innerHTML += '<p style="color: green; font-weight: bold;">✓ SUCCESS!</p>';
            resultsContent.innerHTML += '<pre>' + JSON.stringify(d, null, 2) + '</pre>';
            resultsContent.innerHTML += '<p style="color: blue;">Reloading in 2 seconds...</p>';
            setTimeout(() => location.reload(), 2000);
        })
        .catch(e => {
            console.error('Error: ', e);
            resultsContent.innerHTML += '<p style="color: red; font-weight: bold;">✗ ERROR: ' + e.message + '</p>';
        });
    }
    
    // Make functions global
    window.changeLanguage = function(selectElement) {
        const select = selectElement || document.getElementById('languageSelect');
        if (!select) { alert('Select not found'); return; }
        testLang(select.value);
    };
    
    window.changeCurrency = function(selectElement) {
        const select = selectElement || document.getElementById('currencySelect');
        if (!select) { alert('Select not found'); return; }
        testCurr(select.value);
    };
    
    console.log('Test page ready');
    console.log('changeLanguage:', typeof changeLanguage);
    console.log('changeCurrency:', typeof changeCurrency);
    </script>
</body>
</html>
