<?php
/**
 * Simple API Test - Test language/currency changes
 */
session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Emporio Sport - API Test</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }
        h1 { color: #333; }
        .button { padding: 10px 20px; margin: 5px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold; }
        .btn-lang { background: #4CAF50; color: white; }
        .btn-curr { background: #2196F3; color: white; }
        .output { background: #f0f0f0; padding: 15px; border-radius: 4px; margin: 20px 0; font-family: monospace; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        h2 { border-bottom: 2px solid #333; padding-bottom: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Emporio Sport - API Test Console</h1>
        
        <h2>Current Session Status</h2>
        <div class="output">
            Language: <strong><?php echo $_SESSION['selected_language'] ?? 'Not set'; ?></strong><br>
            Currency: <strong><?php echo $_SESSION['selected_currency'] ?? 'Not set'; ?></strong>
        </div>

        <h2>Test Language Change</h2>
        <p>Click buttons below to test changing languages via API:</p>
        <button class="button btn-lang" onclick="testLanguage('it')">Test: Italian (IT)</button>
        <button class="button btn-lang" onclick="testLanguage('en')">Test: English (EN)</button>
        <button class="button btn-lang" onclick="testLanguage('es')">Test: Spanish (ES)</button>
        <button class="button btn-lang" onclick="testLanguage('de')">Test: German (DE)</button>

        <h2>Test Currency Change</h2>
        <p>Click buttons below to test changing currencies via API:</p>
        <button class="button btn-curr" onclick="testCurrency('eur')">Test: EUR</button>
        <button class="button btn-curr" onclick="testCurrency('usd')">Test: USD</button>
        <button class="button btn-curr" onclick="testCurrency('gbp')">Test: GBP</button>
        <button class="button btn-curr" onclick="testCurrency('cad')">Test: CAD</button>

        <h2>Test Results</h2>
        <div id="output" class="output" style="min-height: 200px;">
            <em>Results will appear here...</em>
        </div>

        <h2>Debug Info</h2>
        <div class="output">
            <strong>Current URL:</strong> <code id="urlinfo"></code><br>
            <strong>API Endpoint:</strong> <code id="apiinfo"></code><br>
            <strong>Page Origin:</strong> <code id="origininfo"></code>
        </div>
    </div>

    <script>
        // Display debug info
        const url = window.location.href;
        const origin = window.location.origin;
        const pathname = window.location.pathname;
        const hasEmporio = pathname.includes('/emporio-sport/');
        const baseUrl = hasEmporio ? '/emporio-sport/' : '/';
        const apiUrl = origin + baseUrl + 'api_set_preference.php';

        document.getElementById('urlinfo').textContent = url;
        document.getElementById('apiinfo').textContent = apiUrl;
        document.getElementById('origininfo').textContent = origin;

        function addOutput(message, isSuccess = false) {
            const output = document.getElementById('output');
            if (output.innerHTML.includes('Results will appear here')) {
                output.innerHTML = '';
            }
            const div = document.createElement('div');
            div.className = 'output ' + (isSuccess ? 'success' : 'error');
            const timestamp = new Date().toLocaleTimeString();
            div.innerHTML = `<strong>${timestamp}:</strong> ${message}`;
            output.insertBefore(div, output.firstChild);
        }

        function testLanguage(lang) {
            addOutput(`Testing language change to: ${lang}...`);
            
            const apiUrl = window.location.origin + 
                (window.location.pathname.includes('/emporio-sport/') ? '/emporio-sport/' : '/') + 
                'api_set_preference.php';

            fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'language', value: lang })
            })
            .then(response => {
                addOutput(`Response status: ${response.status}`, response.ok);
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    addOutput(`✓ Language changed to: ${data.language_name}`, true);
                } else {
                    addOutput(`✗ Error: ${data.message}`, false);
                }
                console.log('API Response:', data);
            })
            .catch(e => {
                addOutput(`✗ Error: ${e.message}`, false);
                console.error('Fetch error:', e);
            });
        }

        function testCurrency(curr) {
            addOutput(`Testing currency change to: ${curr}...`);
            
            const apiUrl = window.location.origin + 
                (window.location.pathname.includes('/emporio-sport/') ? '/emporio-sport/' : '/') + 
                'api_set_preference.php';

            fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ type: 'currency', value: curr })
            })
            .then(response => {
                addOutput(`Response status: ${response.status}`, response.ok);
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    addOutput(`✓ Currency changed to: ${data.currency} (Rate: ${data.exchange_rate})`, true);
                } else {
                    addOutput(`✗ Error: ${data.message}`, false);
                }
                console.log('API Response:', data);
            })
            .catch(e => {
                addOutput(`✗ Error: ${e.message}`, false);
                console.error('Fetch error:', e);
            });
        }

        // Log initial info
        console.log('API Test Console Started');
        console.log('Origin:', origin);
        console.log('Pathname:', pathname);
        console.log('Has /emporio-sport/:', hasEmporio);
        console.log('API URL:', apiUrl);
    </script>
</body>
</html>
