<?php
/**
 * MASTER VERIFICATION SCRIPT
 * Tests all language/currency functionality end-to-end
 */

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

$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';

// Check for test parameter
if (isset($_GET['test_lang'])) {
    $_SESSION['selected_language'] = strtolower($_GET['test_lang']);
    session_write_close();
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'action' => 'set_lang', 'value' => $_GET['test_lang']]);
    exit;
}

if (isset($_GET['test_curr'])) {
    $_SESSION['selected_currency'] = strtolower($_GET['test_curr']);
    session_write_close();
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'action' => 'set_curr', 'value' => $_GET['test_curr']]);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Master Verification - Language & Currency</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; }
        
        .header {
            background: #1a1a1a;
            color: white;
            padding: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header select { background: #1a1a1a; color: white; border: none; cursor: pointer; padding: 5px; }
        .header label { margin-right: 10px; font-weight: 600; }
        
        .container { max-width: 1000px; margin: 30px auto; }
        
        .card {
            background: white;
            border-radius: 8px;
            padding: 25px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        h1 { color: #333; margin-bottom: 10px; }
        h2 { color: #555; font-size: 18px; margin: 20px 0 15px 0; border-bottom: 2px solid #f0f2f5; padding-bottom: 10px; }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        
        .status-item {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #ddd;
        }
        
        .status-item.ok { border-left-color: #4CAF50; background: #f1f8f4; }
        .status-item.warning { border-left-color: #ff9800; background: #fff8f1; }
        .status-item.error { border-left-color: #f44336; background: #fdf1f0; }
        
        .label { font-weight: 600; color: #555; margin-bottom: 5px; }
        .value { font-family: 'Courier New', monospace; color: #333; font-size: 16px; }
        
        .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin: 15px 0;
        }
        
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            transition: background 0.2s;
        }
        
        button:hover { background: #0056b3; }
        button.success { background: #4CAF50; }
        button.success:hover { background: #45a049; }
        button.warning { background: #ff9800; }
        button.warning:hover { background: #e68900; }
        
        .test-log {
            background: #f0f0f0;
            padding: 15px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 300px;
            overflow-y: auto;
            margin-top: 15px;
        }
        
        .log-entry { margin: 5px 0; padding: 5px 0; border-bottom: 1px solid #ddd; }
        .log-success { color: #4CAF50; }
        .log-error { color: #f44336; }
        .log-info { color: #2196F3; }
    </style>
</head>
<body>
    <!-- Replica Header -->
    <div class="header">
        <span>Emporio Sport</span>
        <div>
            <label>Language:</label>
            <select id="langSelect" onchange="changeLang(this)">
                <?php foreach ($headerConfig['languages'] as $l) {
                    $code = strtolower($l['code']);
                    $sel = ($code === $selected_lang) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($code) . '" ' . $sel . '>' . htmlspecialchars($l['label']) . '</option>';
                } ?>
            </select>
            
            <label style="margin-left: 30px;">Currency:</label>
            <select id="currSelect" onchange="changeCurr(this)">
                <?php foreach ($headerConfig['currencies'] as $c) {
                    $code = strtolower($c['code']);
                    $sel = ($code === $selected_currency) ? 'selected' : '';
                    echo '<option value="' . htmlspecialchars($code) . '" ' . $sel . '>' . htmlspecialchars($c['label']) . '</option>';
                } ?>
            </select>
        </div>
    </div>
    
    <div class="container">
        <div class="card">
            <h1>🧪 Master Language & Currency Verification</h1>
            <p>Test all language and currency changing functionality. Dropdowns should update and persist after reload.</p>
        </div>
        
        <div class="card">
            <h2>📊 Current Session State</h2>
            <div class="status-grid">
                <div class="status-item ok">
                    <div class="label">Session ID</div>
                    <div class="value"><?php echo substr(session_id(), 0, 20); ?>...</div>
                </div>
                <div class="status-item <?php echo ($selected_lang !== 'it' ? 'warning' : 'ok'); ?>">
                    <div class="label">Language</div>
                    <div class="value"><?php echo strtoupper($selected_lang); ?></div>
                </div>
                <div class="status-item <?php echo ($selected_currency !== 'eur' ? 'warning' : 'ok'); ?>">
                    <div class="label">Currency</div>
                    <div class="value"><?php echo strtoupper($selected_currency); ?></div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <h2>🚀 Quick Test Actions</h2>
            
            <div>
                <strong>Set Language:</strong>
                <div class="button-group">
                    <button onclick="testLang('it')" <?php echo $selected_lang === 'it' ? 'class="success"' : ''; ?>>Italian (IT)</button>
                    <button onclick="testLang('en')" <?php echo $selected_lang === 'en' ? 'class="success"' : ''; ?>>English (EN)</button>
                    <button onclick="testLang('es')" <?php echo $selected_lang === 'es' ? 'class="success"' : ''; ?>>Spanish (ES)</button>
                    <button onclick="testLang('de')" <?php echo $selected_lang === 'de' ? 'class="success"' : ''; ?>>German (DE)</button>
                </div>
            </div>
            
            <div style="margin-top: 20px;">
                <strong>Set Currency:</strong>
                <div class="button-group">
                    <button onclick="testCurr('eur')" <?php echo $selected_currency === 'eur' ? 'class="success"' : ''; ?>>EUR (€)</button>
                    <button onclick="testCurr('usd')" <?php echo $selected_currency === 'usd' ? 'class="success"' : ''; ?>>USD ($)</button>
                    <button onclick="testCurr('gbp')" <?php echo $selected_currency === 'gbp' ? 'class="success"' : ''; ?>>GBP (£)</button>
                    <button onclick="testCurr('cad')" <?php echo $selected_currency === 'cad' ? 'class="success"' : ''; ?>>CAD (C$)</button>
                </div>
            </div>
            
            <div class="test-log" id="testLog">
                <div class="log-entry log-info">Test log ready. Click a button to begin testing.</div>
            </div>
        </div>
        
        <div class="card">
            <h2>📋 Verification Checklist</h2>
            <div class="status-grid">
                <div class="status-item <?php echo (!empty($headerConfig['languages']) ? 'ok' : 'error'); ?>">
                    <div class="label">✓ Languages Loaded</div>
                    <div class="value"><?php echo count($headerConfig['languages']); ?> languages</div>
                </div>
                <div class="status-item <?php echo (!empty($headerConfig['currencies']) ? 'ok' : 'error'); ?>">
                    <div class="label">✓ Currencies Loaded</div>
                    <div class="value"><?php echo count($headerConfig['currencies']); ?> currencies</div>
                </div>
                <div class="status-item ok">
                    <div class="label">✓ API Endpoint</div>
                    <div class="value">api_set_preference.php</div>
                </div>
            </div>
        </div>
    </div>
    
    <script>
    function log(message, type = 'info') {
        const logEl = document.getElementById('testLog');
        const entry = document.createElement('div');
        entry.className = 'log-entry log-' + type;
        entry.textContent = new Date().toLocaleTimeString() + ' - ' + message;
        logEl.insertBefore(entry, logEl.firstChild);
        if (logEl.children.length > 20) {
            logEl.removeChild(logEl.lastChild);
        }
    }
    
    function changeLang(select) {
        testLang(select.value);
    }
    
    function changeCurr(select) {
        testCurr(select.value);
    }
    
    function testLang(value) {
        log('Testing language: ' + value, 'info');
        callAPI('language', value);
    }
    
    function testCurr(value) {
        log('Testing currency: ' + value, 'info');
        callAPI('currency', value);
    }
    
    function callAPI(type, value) {
        fetch('/emporio-sport/api_set_preference.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ type: type, value: value })
        })
        .then(r => {
            log('API Response: ' + r.status, r.status === 200 ? 'success' : 'error');
            return r.json();
        })
        .then(data => {
            if (data.success) {
                log('✓ ' + (type === 'language' ? 'Language' : 'Currency') + ' changed to ' + value.toUpperCase(), 'success');
                log('Reloading page...', 'info');
                setTimeout(() => location.reload(), 800);
            } else {
                log('✗ API Error: ' + (data.message || 'Unknown'), 'error');
            }
        })
        .catch(err => {
            log('✗ Network Error: ' + err.message, 'error');
        });
    }
    
    log('Master verification page loaded', 'info');
    </script>
</body>
</html>
