<?php
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// Load header config to match real behavior
$headerConfigFile = __DIR__ . '/data/header_config.json';
$headerConfig = ['languages' => [], 'currencies' => []];
if (file_exists($headerConfigFile)) {
    $headerConfigData = @json_decode(file_get_contents($headerConfigFile), true);
    if (is_array($headerConfigData)) {
        $headerConfig = $headerConfigData;
    }
}

// Get selected language and currency from session or config
$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>Integration Test - Header Dropdowns</title>
    <style>
        body { font-family: Arial; margin: 0; padding: 0; }
        .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; }
        h1 { margin: 20px; }
        .test-results { margin: 20px; padding: 20px; border: 2px solid #ccc; }
        .success { color: green; font-weight: bold; }
        .error { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <!-- Replica of actual header -->
    <div class="promo-strip">
        <span>Emporio Sport - Test</span>
        <div>
            <label>Language:</label>
            <select id="languageSelect" onchange="changeLanguage(this)">
                <?php
                if (!empty($headerConfig['languages']) && is_array($headerConfig['languages'])) {
                    foreach ($headerConfig['languages'] as $lang) {
                        $langCode = isset($lang['code']) ? strtolower($lang['code']) : '';
                        $isSelected = ($langCode === $selected_lang) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($langCode) . '" ' . $isSelected . '>' . htmlspecialchars($lang['label'] ?? '') . '</option>';
                    }
                }
                ?>
            </select>
            
            <label style="margin-left: 15px;">Currency:</label>
            <select id="currencySelect" onchange="changeCurrency(this)">
                <?php
                if (!empty($headerConfig['currencies']) && is_array($headerConfig['currencies'])) {
                    foreach ($headerConfig['currencies'] as $curr) {
                        $currCode = isset($curr['code']) ? strtolower($curr['code']) : '';
                        $isSelected = ($currCode === $selected_currency) ? 'selected' : '';
                        echo '<option value="' . htmlspecialchars($currCode) . '" ' . $isSelected . '>' . htmlspecialchars($curr['label'] ?? '') . '</option>';
                    }
                }
                ?>
            </select>
        </div>
    </div>
    
    <h1>Integration Test Results</h1>
    
    <div class="test-results">
        <h3>Session State</h3>
        <p>Session ID: <code><?php echo session_id(); ?></code></p>
        <p>Selected Language: <span class="success"><?php echo htmlspecialchars($selected_lang); ?></span></p>
        <p>Selected Currency: <span class="success"><?php echo htmlspecialchars($selected_currency); ?></span></p>
        
        <h3>Language Dropdown Check</h3>
        <?php
        $langFound = false;
        foreach ($headerConfig['languages'] as $lang) {
            $langCode = strtolower($lang['code']);
            if ($langCode === $selected_lang) {
                $langFound = true;
                echo '<p class="success">✓ Language "' . htmlspecialchars($langCode) . '" is marked as selected in dropdown</p>';
                break;
            }
        }
        if (!$langFound) {
            echo '<p class="error">✗ Language "' . htmlspecialchars($selected_lang) . '" NOT found as selected!</p>';
        }
        ?>
        
        <h3>Currency Dropdown Check</h3>
        <?php
        $currFound = false;
        foreach ($headerConfig['currencies'] as $curr) {
            $currCode = strtolower($curr['code']);
            if ($currCode === $selected_currency) {
                $currFound = true;
                echo '<p class="success">✓ Currency "' . htmlspecialchars($currCode) . '" is marked as selected in dropdown</p>';
                break;
            }
        }
        if (!$currFound) {
            echo '<p class="error">✗ Currency "' . htmlspecialchars($selected_currency) . '" NOT found as selected!</p>';
        }
        ?>
        
        <h3>Raw Config Data</h3>
        <pre><?php print_r($headerConfig); ?></pre>
    </div>
    
    <script>
    function changeLanguage(selectElement) {
        const selectedLang = selectElement.value;
        console.log('Language change initiated:', selectedLang);
        
        fetch('/emporio-sport/api_set_preference.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'language', value: selectedLang })
        })
        .then(response => {
            console.log('API Response Status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('API Response:', 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('Fetch Error:', err);
            alert('Error: ' + err.message);
        });
    }
    
    function changeCurrency(selectElement) {
        const selectedCurr = selectElement.value;
        console.log('Currency change initiated:', selectedCurr);
        
        fetch('/emporio-sport/api_set_preference.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: 'currency', value: selectedCurr })
        })
        .then(response => {
            console.log('API Response Status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('API Response:', 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('Fetch Error:', err);
            alert('Error: ' + err.message);
        });
    }
    
    console.log('Integration test page loaded');
    console.log('Current language from session:', '<?php echo $selected_lang; ?>');
    console.log('Current currency from session:', '<?php echo $selected_currency; ?>');
    </script>
</body>
</html>
