<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Cargar variables de entorno
if (file_exists(__DIR__ . '/../../../.env')) {
    $lines = file(__DIR__ . '/../../../.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        if (strpos($line, '=') === false) continue;
        list($key, $value) = explode('=', $line, 2);
        $_ENV[trim($key)] = trim($value);
    }
}

require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';

$userData = JWTAuth::requireAuth();

// Verificar permiso para ver la página de plantillas
if (!hasPermission('view_templates', 'telegram')) {
    die('No tienes permiso para ver las plantillas de Telegram.');
}
?>
<!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>Plantillas Telegram - Sistema de Bots</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --telegram-color: #0088cc;
            --telegram-dark: #006699;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--telegram-color) 0%, var(--telegram-dark) 100%);
            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: var(--telegram-color); font-size: 24px; }
        
        .container { max-width: 1200px; margin: 0 auto; }
        
        .card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            border: none;
            cursor: pointer;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }
        .btn-primary { background: var(--telegram-color); color: white; }
        .btn-secondary { background: #6c757d; color: white; }
        .btn-danger { background: #dc3545; color: white; }
        
        #templates-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
        .template-card {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            border: 2px solid #eee;
            transition: all 0.2s;
        }
        
        .template-card:hover {
            border-color: var(--telegram-color);
            transform: translateY(-2px);
        }
        
        .template-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 15px;
        }
        
        .template-title {
            font-size: 18px;
            font-weight: 700;
            color: #333;
        }
        
        .template-meta {
            font-size: 12px;
            color: #666;
            margin-bottom: 10px;
        }
        
        .template-preview-content {
            background: white;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 15px;
            max-height: 100px;
            overflow: hidden;
            font-size: 14px;
            color: #666;
            position: relative;
        }
        .template-preview-content::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 30px;
            background: linear-gradient(transparent, white);
        }
        
        .template-actions {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .empty-state, .loading-state, .error-state {
            background: white;
            border-radius: 15px;
            padding: 60px 40px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .empty-state i, .loading-state i, .error-state i {
            font-size: 64px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .empty-state h2, .loading-state h2, .error-state h2 {
            color: #666;
            margin-bottom: 10px;
        }
        
        .empty-state p, .loading-state p, .error-state p {
            color: #999;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-file-alt"></i> Plantillas de Telegram</h1>
        <div style="display: flex; gap: 10px;">
            <?php if (hasPermission('manage_templates', 'telegram')): ?>
            <a href="create.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Nueva Plantilla
            </a>
            <?php endif; ?>
            <a href="/telegram/dashboard_telegram.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
        </div>
    </div>
    
    <div class="container">
        <div class="card">
            <div id="templates-container">
                <!-- Templates will be loaded here by JavaScript -->
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', loadTemplates);

        function escapeHTML(str) {
            if (str === null || str === undefined) return '';
            return str.toString().replace(/[&<>"']/g, function(match) {
                return {
                    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
                }[match];
            });
        }

        async function loadTemplates() {
            const container = document.getElementById('templates-container');
            container.innerHTML = `
                <div class="loading-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <h2>Cargando Plantillas...</h2>
                </div>`;

            try {
                const response = await fetch('/telegram/api/templates/list.php');
                const result = await response.json();

                if (!result.success) {
                    throw new Error(result.error || 'Failed to load templates');
                }

                if (result.templates.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-file-alt"></i>
                            <h2>No hay plantillas creadas</h2>
                            <p>Crea tu primera plantilla para empezar a enviar mensajes en Telegram</p>
                            <?php if (hasPermission('manage_templates', 'telegram')): ?>
                            <a href="create.php" class="btn btn-primary">
                                <i class="fas fa-plus"></i> Crear Primera Plantilla
                            </a>
                            <?php endif; ?>
                        </div>`;
                    return;
                }

                container.innerHTML = '<div class="templates-grid"></div>'; // Clear loading state and add grid
                const templatesGrid = container.querySelector('.templates-grid');
                result.templates.forEach(template => {
                    const card = document.createElement('div');
                    card.className = 'template-card';

                    const commandHTML = template.comando 
                        ? `<span class="template-command" style="background: #e3f2fd; color: var(--telegram-color); padding: 4px 12px; border-radius: 12px; font-size: 13px; font-weight: 600; font-family: monospace;">${escapeHTML(template.comando)}</span>`
                        : '';
                    
                    const contentPreview = document.createElement('div');
                    // Telegram doesn't use HTML in the same way, but it can use Markdown.
                    // For preview, we'll just show plain text or stripped HTML.
                    contentPreview.innerHTML = template.contenido; 
                    
                    card.innerHTML = `
                        <div class="template-header">
                            <div>
                                <div class="template-title">${escapeHTML(template.nombre)}</div>
                                ${commandHTML}
                            </div>
                        </div>
                        <div class="template-meta">
                            <i class="fas fa-user"></i> ${escapeHTML(template.username) || 'Desconocido'}
                            <br>
                            <i class="fas fa-clock"></i> ${new Date(template.fecha_modificacion).toLocaleString()}
                        </div>
                        <div class="template-preview-content">
                            ${escapeHTML(contentPreview.textContent || '')}
                        </div>
                        <div class="template-actions">
                            <?php if (hasPermission('manage_templates', 'telegram')): ?>
                            <a href="edit.php?id=${template.id}" class="btn btn-primary" style="font-size: 12px; padding: 5px 10px;">
                                <i class="fas fa-edit"></i> Editar
                            </a>
                            <?php endif; ?>
                            <?php if (hasPermission('view_templates', 'telegram')): ?>
                            <a href="preview.php?id=${template.id}" class="btn btn-secondary" style="font-size: 12px; padding: 5px 10px;" target="_blank">
                                <i class="fas fa-eye"></i> Vista Previa
                            </a>
                            <?php endif; ?>
                            <?php if (hasPermission('manage_templates', 'telegram')): ?>
                            <button onclick="deleteTemplate(${template.id}, '${escapeHTML(template.nombre)}') " class="btn btn-danger" style="font-size: 12px; padding: 5px 10px;">
                                <i class="fas fa-trash"></i> Eliminar
                            </button>
                            <?php endif; ?>
                        </div>
                    `;
                    templatesGrid.appendChild(card);
                });

            } catch (error) {
                console.error('Error loading templates:', error);
                container.innerHTML = `
                    <div class="error-state">
                        <i class="fas fa-exclamation-triangle"></i>
                        <h2>Error al Cargar</h2>
                        <p>No se pudieron cargar las plantillas. Revisa la consola para más detalles.</p>
                    </div>`;
            }
        }

        async function deleteTemplate(id, nombre) {
            if (!confirm(\`¿Estás seguro de eliminar la plantilla "\${nombre}"?\`)) {
                return;
            }

            try {
                const response = await fetch('/telegram/api/templates/delete.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ id: id })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Plantilla eliminada correctamente');
                    loadTemplates(); // Reload the list dynamically
                } else {
                    alert('Error al eliminar: ' + (data.error || 'Error desconocido'));
                }
            } catch (error) {
                console.error('Error deleting template:', error);
                alert('Error de conexión al intentar eliminar la plantilla.');
            }
        }
    </script>
</body>
</html>
