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

// Load actual config like the real page does
$headerConfigFile = __DIR__ . '/data/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>FINAL COMPREHENSIVE TEST</title>
    <style>
        * { box-sizing: border-box; }
        body { font-family: Arial, sans-serif; margin: 0; padding: 0; background: #f5f5f5; }
        
        .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;
        }
        
        select {
            background: #1a1a1a;
            color: #fff;
            border: none;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            outline: none;
            padding: 4px 6px;
            border-radius: 3px;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }
        
        h1 { color: #333; }
        
        .box {
            background: white;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .success { background: #d4edda; border-color: #c3e6cb; color: #155724; }
        .error { background: #f8d7da; border-color: #f5c6cb; color: #721c24; }
        .info { background: #d1ecf1; border-color: #bee5eb; color: #0c5460; }
        
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            cursor: pointer;
            border-radius: 3px;
            margin: 5px 5px 5px 0;
            font-size: 14px;
        }
        
        button:hover { background: #0056b3; }
        
        .test-row {
            display: flex;
            gap: 10px;
            align-items: center;
            margin: 10px 0;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 3px;
        }
        
        code {
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }
        
        .status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 3px;
            font-weight: bold;
            font-size: 12px;
        }
        
        .status.ok { background: #4CAF50; color: white; }
        .status.bad { background: #f44336; color: white; }
        
        pre {
            background: #f0f0f0;
            padding: 10px;
            border-radius: 3px;
            overflow-x: auto;
            max-height: 200px;
        }
    </style>
</head>
<body>
    <!-- REAL HEADER REPLICA -->
    <div class="promo-strip">
        <span>Emporio Sport</span>
        <div>
            <label>Language:</label>
            <select id="languageSelect" onchange="testLanguage(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>
            
            <label style="margin-left: 20px;">Currency:</label>
            <select id="currencySelect" onchange="testCurrency(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="container">
        <h1>🧪 FINAL COMPREHENSIVE SESSION TEST</h1>
        
        <div class="box info">
            <h3>Current State</h3>
            <div class="test-row">
                <label>Session ID:</label>
                <code><?php echo session_id(); ?></code>
                <span class="status ok">✓ ACTIVE</span>
            </div>
            <div class="test-row">
                <label>Language:</label>
                <code><?php echo htmlspecialchars($selected_lang); ?></code>
                <span class="status <?php echo $selected_lang === 'it' ? 'ok' : 'bad'; ?>">
                    <?php echo $selected_lang === 'it' ? '✓ DEFAULT' : 'CHANGED'; ?>
                </span>
            </div>
            <div class="test-row">
                <label>Currency:</label>
                <code><?php echo htmlspecialchars($selected_currency); ?></code>
                <span class="status <?php echo $selected_currency === 'eur' ? 'ok' : 'bad'; ?>">
                    <?php echo $selected_currency === 'eur' ? '✓ DEFAULT' : 'CHANGED'; ?>
                </span>
            </div>
        </div>
        
        <div class="box success" style="border-color: #c3e6cb;">
            <h3>✓ Dropdown Verification</h3>
            <?php
            $langMatch = false;
            foreach ($headerConfig['languages'] as $lang) {
                if (strtolower($lang['code']) === $selected_lang) {
                    echo '<p>✓ Language dropdown shows <code>' . htmlspecialchars($lang['label']) . '</code> as selected</p>';
                    $langMatch = true;
                    break;
                }
            }
            if (!$langMatch) {
                echo '<p style="color:red;">✗ Language "' . htmlspecialchars($selected_lang) . '" not found in config!</p>';
            }
            
            $currMatch = false;
            foreach ($headerConfig['currencies'] as $curr) {
                if (strtolower($curr['code']) === $selected_currency) {
                    echo '<p>✓ Currency dropdown shows <code>' . htmlspecialchars($curr['label']) . '</code> as selected</p>';
                    $currMatch = true;
                    break;
                }
            }
            if (!$currMatch) {
                echo '<p style="color:red;">✗ Currency "' . htmlspecialchars($selected_currency) . '" not found in config!</p>';
            }
            ?>
        </div>
        
        <div class="box">
            <h3>Test Actions</h3>
            <p>Click a button to change language/currency. The dropdown should update AND the value should persist after reload.</p>
            
            <div class="test-row">
                <label>Quick Language Tests:</label>
                <button onclick="directSet('lang', 'it')">Set Italian</button>
                <button onclick="directSet('lang', 'en')">Set English</button>
                <button onclick="directSet('lang', 'es')">Set Spanish</button>
                <button onclick="directSet('lang', 'de')">Set German</button>
            </div>
            
            <div class="test-row">
                <label>Quick Currency Tests:</label>
                <button onclick="directSet('curr', 'eur')">Set EUR</button>
                <button onclick="directSet('curr', 'usd')">Set USD</button>
                <button onclick="directSet('curr', 'gbp')">Set GBP</button>
                <button onclick="directSet('curr', 'cad')">Set CAD</button>
            </div>
            
            <div id="testOutput"></div>
        </div>
        
        <div class="box">
            <h3>Debug Information</h3>
            <p><strong>Config Languages:</strong></p>
            <pre><?php foreach ($headerConfig['languages'] as $l) echo $l['code'] . ' => ' . $l['label'] . "\n"; ?></pre>
            <p><strong>Config Currencies:</strong></p>
            <pre><?php foreach ($headerConfig['currencies'] as $c) echo $c['code'] . ' => ' . $c['label'] . "\n"; ?></pre>
        </div>
    </div>
    
    <script>
    function testLanguage(select) {
        const value = select.value;
        console.log('Testing language:', value);
        callAPI('language', value);
    }
    
    function testCurrency(select) {
        const value = select.value;
        console.log('Testing currency:', value);
        callAPI('currency', value);
    }
    
    function callAPI(type, value) {
        const output = document.getElementById('testOutput');
        output.innerHTML = '<p style="color: blue;">Calling API...</p>';
        
        fetch('/emporio-sport/api_set_preference.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                type: type,
                value: value
            })
        })
        .then(response => {
            console.log('HTTP Status:', response.status);
            return response.json();
        })
        .then(data => {
            console.log('API Response:', data);
            
            if (data.success) {
                output.innerHTML = '<p style="color: green; font-weight: bold;">✓ SUCCESS! Reloading page...</p>' +
                    '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
                setTimeout(() => location.reload(), 1000);
            } else {
                output.innerHTML = '<p style="color: red; font-weight: bold;">✗ FAILED: ' + (data.message || 'Unknown error') + '</p>' +
                    '<pre>' + JSON.stringify(data, null, 2) + '</pre>';
            }
        })
        .catch(err => {
            console.error('Fetch Error:', err);
            output.innerHTML = '<p style="color: red; font-weight: bold;">✗ NETWORK ERROR: ' + err.message + '</p>';
        });
    }
    
    function directSet(type, value) {
        const typeMap = { 'lang': 'language', 'curr': 'currency' };
        callAPI(typeMap[type], value);
    }
    </script>
</body>
</html>
