<?php
session_start();

// Habilitar logging para depuración
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../shared/utils/helpers.php';
require_once __DIR__ . '/../../shared/auth/jwt.php';
require_once __DIR__ . '/../../shared/database/connection.php';
require_once __DIR__ . '/../../shared/translations/manager.php'; // Incluir helper de traducciones

$userData = JWTAuth::requireAuth();

// Verificar permiso para ver la página de gestión de idiomas
if (!hasPermission('view_languages')) {
    die(__('you_do_not_have_permission_to_manage_languages'));
}

$db = getDB();

// Manejar acciones POST (Activar/Desactivar/Sincronizar/Actualizar Bandera)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verificar permiso para realizar acciones de gestión de idiomas
    if (!hasPermission('manage_languages')) {
        jsonResponse(['success' => false, 'error' => __('you_do_not_have_permission_to_manage_languages')], 403);
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (isset($input['action'])) {
        try {
            if ($input['action'] === 'toggle' && isset($input['id'])) {
                $stmt = $db->prepare("UPDATE idiomas SET activo = NOT activo WHERE id = ?");
                $stmt->execute([$input['id']]);
                jsonResponse(['success' => true]);
            }
            elseif ($input['action'] === 'update_flag' && isset($input['id'])) {
                $flag = $input['flag'] ?? null;
                $stmt = $db->prepare("UPDATE idiomas SET bandera = ? WHERE id = ?");
                $stmt->execute([$flag, $input['id']]);
                jsonResponse(['success' => true]);
            }
            elseif ($input['action'] === 'sync') {
                // 1. Obtener idiomas de LibreTranslate
                $ltUrl = $_ENV['LIBRETRANSLATE_URL'] ?? getenv('LIBRETRANSLATE_URL') ?? 'http://10.10.4.17:5000';
                $ch = curl_init("$ltUrl/languages");
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);
                
                if ($httpCode !== 200 || !$response) {
                    throw new Exception("No se pudo conectar con LibreTranslate ($ltUrl)");
                }
                
                $languages = json_decode($response, true);
                if (!is_array($languages)) {
                    throw new Exception("Respuesta inválida de LibreTranslate");
                }
                
                // 2. Actualizar base de datos
                $stmt = $db->prepare("
                    INSERT INTO idiomas (codigo, nombre, nombre_nativo, activo) 
                    VALUES (?, ?, ?, 1)
                    ON DUPLICATE KEY UPDATE nombre = VALUES(nombre), nombre_nativo = VALUES(nombre_nativo)
                ");
                
                $count = 0;
                foreach ($languages as $lang) {
                    // LibreTranslate devuelve: code, name, targets
                    // No siempre devuelve nombre nativo, usaremos el nombre en inglés por defecto
                    $stmt->execute([
                        $lang['code'], 
                        $lang['name'], 
                        $lang['name'], // Usamos el mismo nombre ya que LT no siempre da el nativo en /languages
                    ]);
                    $count++;
                }
                
                jsonResponse(['success' => true, 'message' => str_replace('{count}', $count, __('synced_languages'))]);
            }
        } catch (Exception $e) {
            jsonResponse(['success' => false, 'error' => $e->getMessage()], 500);
        }
    }
    exit;
}

// Obtener idiomas
$stmt = $db->query("SELECT * FROM idiomas ORDER BY nombre ASC");
$idiomas = $stmt->fetchAll();

// URL de LibreTranslate desde .env
$libreTranslateUrl = $_ENV['LIBRETRANSLATE_URL'] ?? getenv('LIBRETRANSLATE_URL') ?? 'http://10.10.4.17:5000';
?>
<!DOCTYPE html>
<html lang="<?php echo $userData->idioma ?? 'es'; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('language_manager_title'); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="/shared/public/js/notifications.js"></script>
    <style>
        :root {
            --primary-color: #5865F2;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f0f2f5;
            min-height: 100vh;
            padding: 20px;
        }
        
        .header {
            background: white;
            border-radius: 15px;
            padding: 20px 30px;
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }
        
        .header h1 {
            color: #333;
            font-size: 24px;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 20px;
        }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            font-weight: 600;
            font-size: 18px;
            color: #444;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        th, td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        th {
            font-weight: 600;
            color: #555;
            background: #f8f9fa;
        }
        
        .switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 34px;
        }
        
        .slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .slider {
            background-color: var(--success-color);
        }
        
        input:checked + .slider:before {
            transform: translateX(26px);
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: var(--primary-color);
            color: white;
        }
        
        .btn-secondary {
            background: var(--secondary-color);
            color: white;
        }
        
        .btn-success {
            background: var(--success-color);
            color: white;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        
        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        
        .test-area textarea {
            width: 100%;
            padding: 10px;
            border: 2px solid #eee;
            border-radius: 8px;
            margin-bottom: 10px;
            min-height: 100px;
            resize: vertical;
        }
        
        .test-result {
            margin-top: 15px;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid var(--primary-color);
            display: none;
        }

        .btn-flag {
            background: white;
            border: 1px solid #ddd;
            border-radius: 50%;
            width: 36px;
            height: 36px;
            font-size: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }
        .btn-flag:hover {
            background: #f0f0f0;
            transform: scale(1.1);
        }

        /* Modal Banderas */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal-content { background: white; margin: 10% auto; padding: 25px; width: 90%; max-width: 600px; border-radius: 15px; position: relative; }
        .close-modal { position: absolute; top: 15px; right: 20px; font-size: 24px; cursor: pointer; color: #aaa; }
        .flag-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(40px, 1fr)); gap: 10px; margin-top: 15px; max-height: 300px; overflow-y: auto; padding: 5px; }
        .flag-option { font-size: 24px; cursor: pointer; padding: 5px; border-radius: 5px; text-align: center; }
        .flag-option:hover { background: #f0f0f0; }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-language"></i> <?php echo __('language_manager_header'); ?></h1>
        <a href="/index.php" class="btn btn-secondary">
            <i class="fas fa-home"></i> <?php echo __('back_to_dashboard'); ?>
        </a>
    </div>
    
    <div class="container">
        <div class="card">
            <div class="card-header">
                <span><?php echo __('available_languages'); ?></span>
                <button onclick="syncLanguages()" class="btn btn-success" style="font-size: 12px; padding: 5px 10px;">
                    <i class="fas fa-sync"></i> <?php echo __('sync_with_libretranslate'); ?>
                </button>
            </div>
            <table>
                <thead>
                    <tr>
                        <th><?php echo __('flag'); ?></th>
                        <th><?php echo __('code'); ?></th>
                        <th><?php echo __('name'); ?></th>
                        <th><?php echo __('native'); ?></th>
                        <th><?php echo __('status'); ?></th>
                        <th><?php echo __('action'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($idiomas as $lang): ?>
                        <tr>
                            <td>
                                <button class="btn-flag" onclick="openFlagModal(<?php echo $lang['id']; ?>, '<?php echo $lang['bandera'] ?? ''; ?>')">
                                    <?php echo $lang['bandera'] ? $lang['bandera'] : '<i class="fas fa-plus" style="font-size: 10px; color: #ccc;"></i>'; ?>
                                </button>
                            </td>
                            <td><code><?php echo htmlspecialchars($lang['codigo']); ?></code></td>
                            <td><?php echo htmlspecialchars($lang['nombre']); ?></td>
                            <td><?php echo htmlspecialchars($lang['nombre_nativo']); ?></td>
                            <td>
                                <span class="status-badge <?php echo $lang['activo'] ? 'status-active' : 'status-inactive'; ?>">
                                    <?php echo $lang['activo'] ? __('active') : __('inactive'); ?>
                                </span>
                            </td>
                            <td>
                                <label class="switch">
                                    <input type="checkbox" 
                                           onchange="toggleLanguage(<?php echo $lang['id']; ?>)" 
                                           <?php echo $lang['activo'] ? 'checked' : ''; ?>>
                                    <span class="slider"></span>
                                </label>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <div class="card">
            <div class="card-header"><?php echo __('translation_test'); ?></div>
            <p style="margin-bottom: 15px; color: #666; font-size: 14px;">
                <?php echo __('test_connection_with_libretranslate'); ?> (<?php echo htmlspecialchars($libreTranslateUrl); ?>).
            </p>
            
            <div class="test-area">
                <textarea id="sourceText" placeholder="<?php echo __('type_something_to_translate'); ?>"></textarea>
                
                <div style="margin-bottom: 15px;">
                    <label style="display:block; margin-bottom:5px; font-weight:600;"><?php echo __('translate_to'); ?></label>
                    <select id="targetLang" style="width:100%; padding:8px; border-radius:5px; border:1px solid #ddd;">
                        <?php foreach ($idiomas as $lang): ?>
                            <?php if ($lang['activo']): ?>
                                <option value="<?php echo $lang['codigo']; ?>">
                                    <?php echo htmlspecialchars($lang['nombre']); ?>
                                </option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <button onclick="testTranslation()" class="btn btn-primary" style="width: 100%;">
                    <i class="fas fa-magic"></i> <?php echo __('translate'); ?>
                </button>
                
                <div id="translationResult" class="test-result"></div>
            </div>
        </div>
    </div>

    <!-- Modal Selección de Bandera -->
    <div id="flagModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeFlagModal()">&times;</span>
            <h2 style="margin-bottom: 15px;"><?php echo __('select_flag'); ?></h2>
            
            <div style="display: flex; gap: 10px; margin-bottom: 15px;">
                <input type="text" id="customFlag" placeholder="<?php echo __('paste_emoji_here'); ?>" class="form-control" style="flex: 1; padding: 10px; border: 2px solid #eee; border-radius: 8px; font-size: 18px;">
                <button onclick="saveCustomFlag()" class="btn btn-primary"><?php echo __('save'); ?></button>
            </div>
            
            <p style="color: #666; font-size: 14px;"><?php echo __('or_select_common_one'); ?></p>
            <div class="flag-grid">
                <!-- Banderas comunes -->
                <div class="flag-option" onclick="selectFlag('🇺🇸')">🇺🇸</div>
                <div class="flag-option" onclick="selectFlag('🇬🇧')">🇬🇧</div>
                <div class="flag-option" onclick="selectFlag('🇪🇸')">🇪🇸</div>
                <div class="flag-option" onclick="selectFlag('🇲🇽')">🇲🇽</div>
                <div class="flag-option" onclick="selectFlag('🇫🇷')">🇫🇷</div>
                <div class="flag-option" onclick="selectFlag('🇩🇪')">🇩🇪</div>
                <div class="flag-option" onclick="selectFlag('🇮🇹')">🇮🇹</div>
                <div class="flag-option" onclick="selectFlag('🇵🇹')">🇵🇹</div>
                <div class="flag-option" onclick="selectFlag('🇧🇷')">🇧🇷</div>
                <div class="flag-option" onclick="selectFlag('🇷🇺')">🇷🇺</div>
                <div class="flag-option" onclick="selectFlag('🇨🇳')">🇨🇳</div>
                <div class="flag-option" onclick="selectFlag('🇯🇵')">🇯🇵</div>
                <div class="flag-option" onclick="selectFlag('🇰🇷')">🇰🇷</div>
                <div class="flag-option" onclick="selectFlag('🇮🇳')">🇮🇳</div>
                <div class="flag-option" onclick="selectFlag('🇸🇦')">🇸🇦</div>
                <div class="flag-option" onclick="selectFlag('🇹🇷')">🇹🇷</div>
                <div class="flag-option" onclick="selectFlag('🇳🇱')">🇳🇱</div>
                <div class="flag-option" onclick="selectFlag('🇵🇱')">🇵🇱</div>
                <div class="flag-option" onclick="selectFlag('🇸🇪')">🇸🇪</div>
                <div class="flag-option" onclick="selectFlag('🇺🇦')">🇺🇦</div>
                <div class="flag-option" onclick="selectFlag('🇨🇦')">🇨🇦</div>
                <div class="flag-option" onclick="selectFlag('🇦🇺')">🇦🇺</div>
                <div class="flag-option" onclick="selectFlag('🇦🇷')">🇦🇷</div>
                <div class="flag-option" onclick="selectFlag('🇨🇴')">🇨🇴</div>
                <div class="flag-option" onclick="selectFlag('🇨🇱')">🇨🇱</div>
                <div class="flag-option" onclick="selectFlag('🇵🇪')">🇵🇪</div>
                <div class="flag-option" onclick="selectFlag('🇻🇪')">🇻🇪</div>
                <div class="flag-option" onclick="selectFlag('🌍')">🌍</div>
            </div>
        </div>
    </div>

    <script>
        let currentLangId = null;

        function openFlagModal(id, currentFlag) {
            currentLangId = id;
            document.getElementById('customFlag').value = currentFlag;
            document.getElementById('flagModal').style.display = 'block';
        }

        function closeFlagModal() {
            document.getElementById('flagModal').style.display = 'none';
            currentLangId = null;
        }

        function selectFlag(flag) {
            document.getElementById('customFlag').value = flag;
            saveCustomFlag();
        }

        async function saveCustomFlag() {
            const flag = document.getElementById('customFlag').value;
            if (!currentLangId) return;

            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'update_flag',
                        id: currentLangId,
                        flag: flag
                    })
                });
                const result = await response.json();
                
                if (result.success) {
                    location.reload();
                } else {
                    showNotification("<?php echo __('error'); ?>" + result.error, 'error');
                }
            } catch (error) {
                console.error(error);
                showNotification("<?php echo __('connection_error'); ?>", 'error');
            }
        }

        window.onclick = function(event) {
            if (event.target == document.getElementById('flagModal')) {
                closeFlagModal();
            }
        }
        async function syncLanguages() {
            if (!confirm("<?php echo __('confirm_sync'); ?>")) return;
            
            const btn = document.querySelector('.btn-success');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo __('syncing'); ?>';
            btn.disabled = true;
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'sync'
                    })
                });
                const result = await response.json();
                
                if (result.success) {
                    showNotification(result.message, 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showNotification("<?php echo __('sync_error'); ?>" + result.error, 'error');
                }
            } catch (error) {
                console.error(error);
                showNotification("<?php echo __('connection_error'); ?>", 'error');
            } finally {
                btn.innerHTML = originalText;
                btn.disabled = false;
            }
        }

        async function toggleLanguage(id) {
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        action: 'toggle',
                        id: id
                    })
                });
                const result = await response.json();
                
                if (result.success) {
                    // Recargar para actualizar UI visualmente (badges)
                    location.reload();
                } else {
                    showNotification("<?php echo __('language_update_error'); ?>: " + result.error, 'error');
                }
            } catch (error) {
                console.error(error);
                showNotification("<?php echo __('connection_error'); ?>", 'error');
            }
        }
        
        async function testTranslation() {
            const text = document.getElementById('sourceText').value;
            const target = document.getElementById('targetLang').value;
            const resultDiv = document.getElementById('translationResult');
            
            if (!text) return;
            
            resultDiv.style.display = 'block';
            resultDiv.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <?php echo __('translating'); ?>';
            
            try {
                // Usar el endpoint de LibreTranslate directamente o a través de un proxy PHP si hay CORS
                // Por ahora intentamos directo, si falla implementaremos proxy
                const response = await fetch('<?php echo $libreTranslateUrl; ?>/translate', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({
                        q: text,
                        source: 'auto',
                        target: target,
                        format: 'text'
                    })
                });
                
                const data = await response.json();
                
                if (data.translatedText) {
                    resultDiv.innerHTML = '<strong><?php echo __('result'); ?></strong><br>' + data.translatedText;
                } else {
                    resultDiv.innerHTML = `<span style="color:red"><?php echo __('error'); ?>${data.error || 'Desconocido'}</span>`;
                }
            } catch (error) {
                console.error(error);
                resultDiv.innerHTML = `<span style="color:red"><?php echo __('libretranslate_connection_error'); ?></span>`;
            }
        }
    </script>
</body>
</html>
