<?php
/**
 * Script de prueba para la API de autenticación
 * Sistema de Inventario Forestal de Guatemala V1.0
 */

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test API - SIF Guatemala</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        .test-section { margin: 20px 0; padding: 15px; border: 1px solid #ddd; border-radius: 4px; }
        .success { background: #e8f5e8; border-color: #4caf50; }
        .error { background: #ffebee; border-color: #f44336; }
        .info { background: #e3f2fd; border-color: #2196f3; }
        button { background: #2e7d32; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; margin: 5px; }
        button:hover { background: #1b5e20; }
        pre { background: #f5f5f5; padding: 10px; border-radius: 4px; overflow-x: auto; }
        input { padding: 8px; margin: 5px; border: 1px solid #ddd; border-radius: 4px; }
        .form-group { margin: 10px 0; }
        label { display: inline-block; width: 100px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🌲 Test API - Sistema de Inventario Forestal</h1>
        
        <div class="test-section info">
            <h3>📋 Información del Sistema</h3>
            <p><strong>Base URL:</strong> <?php echo "http://" . $_SERVER['HTTP_HOST']; ?></p>
            <p><strong>API Endpoint:</strong> <?php echo "http://" . $_SERVER['HTTP_HOST']; ?>/api/</p>
            <p><strong>Fecha/Hora:</strong> <?php echo date('Y-m-d H:i:s'); ?></p>
        </div>

        <div class="test-section">
            <h3>🔍 1. Probar Conexión API</h3>
            <button onclick="testApiConnection()">Probar API</button>
            <div id="api-result"></div>
        </div>

        <div class="test-section">
            <h3>🔐 2. Probar Login</h3>
            <div class="form-group">
                <label>Email:</label>
                <input type="email" id="email" value="admin@demo.com" placeholder="admin@demo.com">
            </div>
            <div class="form-group">
                <label>Contraseña:</label>
                <input type="password" id="password" value="demo123" placeholder="demo123">
            </div>
            <button onclick="testLogin()">Iniciar Sesión</button>
            <div id="login-result"></div>
        </div>

        <div class="test-section">
            <h3>👤 3. Probar Usuario Actual</h3>
            <button onclick="testCurrentUser()">Obtener Usuario</button>
            <div id="user-result"></div>
        </div>

        <div class="test-section">
            <h3>📊 4. Probar Proyectos</h3>
            <button onclick="testProjects()">Obtener Proyectos</button>
            <div id="projects-result"></div>
        </div>

        <div class="test-section">
            <h3>🌿 5. Probar Especies</h3>
            <button onclick="testSpecies()">Obtener Especies</button>
            <div id="species-result"></div>
        </div>
    </div>

    <script>
        let authToken = null;

        async function makeApiCall(endpoint, options = {}) {
            const baseUrl = window.location.origin;
            const url = `${baseUrl}/api${endpoint}`;
            
            const config = {
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers
                },
                ...options
            };

            if (authToken) {
                config.headers.Authorization = `Bearer ${authToken}`;
            }

            try {
                console.log('Making API call to:', url);
                const response = await fetch(url, config);
                const data = await response.text();
                
                let jsonData;
                try {
                    jsonData = JSON.parse(data);
                } catch (e) {
                    jsonData = { raw: data };
                }

                return {
                    ok: response.ok,
                    status: response.status,
                    data: jsonData
                };
            } catch (error) {
                return {
                    ok: false,
                    status: 0,
                    error: error.message
                };
            }
        }

        function displayResult(elementId, result) {
            const element = document.getElementById(elementId);
            const isSuccess = result.ok;
            
            element.className = isSuccess ? 'success' : 'error';
            element.innerHTML = `
                <h4>${isSuccess ? '✅ Éxito' : '❌ Error'}</h4>
                <p><strong>Status:</strong> ${result.status}</p>
                <pre>${JSON.stringify(result.data || result.error, null, 2)}</pre>
            `;
        }

        async function testApiConnection() {
            const result = await makeApiCall('/');
            displayResult('api-result', result);
        }

        async function testLogin() {
            const email = document.getElementById('email').value;
            const password = document.getElementById('password').value;

            const result = await makeApiCall('/auth/login', {
                method: 'POST',
                body: JSON.stringify({ email, password })
            });

            if (result.ok && result.data.data && result.data.data.token) {
                authToken = result.data.data.token;
                localStorage.setItem('auth_token', authToken);
            }

            displayResult('login-result', result);
        }

        async function testCurrentUser() {
            const result = await makeApiCall('/auth/me');
            displayResult('user-result', result);
        }

        async function testProjects() {
            const result = await makeApiCall('/projects');
            displayResult('projects-result', result);
        }

        async function testSpecies() {
            const result = await makeApiCall('/species');
            displayResult('species-result', result);
        }

        // Cargar token guardado si existe
        window.onload = function() {
            const savedToken = localStorage.getItem('auth_token');
            if (savedToken) {
                authToken = savedToken;
            }
        };
    </script>
</body>
</html>