<?php
session_start();

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

// Cargar configuración
require_once __DIR__ . '/../../../shared/utils/helpers.php';
require_once __DIR__ . '/../../../shared/auth/jwt.php';
require_once __DIR__ . '/../../../shared/database/connection.php';

// Verificar autenticación
$userData = JWTAuth::requireAuth();

// Verificar permiso para ver la página
if (!hasPermission('view_templates', 'discord')) {
    die('No tienes permiso para ver las plantillas de Discord.');
}

// Obtener plantillas
$db = getDB();
$stmt = $db->query("
    SELECT p.*, c.comando, u.username
    FROM plantillas_discord p
    LEFT JOIN comandos_discord c ON p.id = c.plantilla_id
    LEFT JOIN usuarios u ON p.usuario_id = u.id
    ORDER BY p.fecha_creacion DESC
");
$plantillas = $stmt->fetchAll();
?>
<!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 Discord - 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 {
            --discord-color: #5865F2;
            --discord-dark: #4752C4;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, var(--discord-color) 0%, var(--discord-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(--discord-color);
            font-size: 24px;
        }
        
        .header-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
        }
        
        .btn-primary {
            background: var(--discord-color);
            color: white;
        }
        
        .btn-primary:hover {
            background: var(--discord-dark);
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .templates-grid {
            display: grid;
            gap: 20px;
        }
        
        .template-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
        }
        
        .template-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
        }
        
        .template-header {
            display: flex;
            justify-content: space-between;
            align-items: start;
            margin-bottom: 15px;
        }
        
        .template-title {
            font-size: 20px;
            font-weight: 700;
            color: #333;
            margin-bottom: 5px;
        }
        
        .template-command {
            display: inline-block;
            background: #e3e7ff;
            color: var(--discord-color);
            padding: 4px 12px;
            border-radius: 12px;
            font-size: 13px;
            font-weight: 600;
            font-family: monospace;
        }
        
        .template-meta {
            font-size: 13px;
            color: #666;
            margin-bottom: 15px;
        }
        
        .template-content {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 15px;
            max-height: 150px;
            overflow: hidden;
            position: relative;
        }
        
        .template-content::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 40px;
            background: linear-gradient(transparent, #f8f9fa);
        }
        
        .template-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-sm {
            padding: 8px 16px;
            font-size: 13px;
        }
        
        .empty-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 {
            font-size: 64px;
            color: #ddd;
            margin-bottom: 20px;
        }
        
        .empty-state h2 {
            color: #666;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #999;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-file-alt"></i> Plantillas Discord</h1>
        <div class="header-actions">
            <a href="/discord/dashboard_discord.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Volver
            </a>
            <?php if (hasPermission('manage_templates', 'discord')): ?>
            <a href="create.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Nueva Plantilla
            </a>
            <?php endif; ?>
        </div>
    </div>
    
    <div class="container">
        <?php if (empty($plantillas)): ?>
            <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 Discord</p>
                <?php if (hasPermission('manage_templates', 'discord')): ?>
                <a href="create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Crear Primera Plantilla
                </a>
                <?php endif; ?>
            </div>
        <?php else: ?>
            <div class="templates-grid">
                <?php foreach ($plantillas as $plantilla): ?>
                    <div class="template-card">
                        <div class="template-header">
                            <div>
                                <div class="template-title"><?php echo htmlspecialchars($plantilla['nombre']); ?></div>
                                <?php if ($plantilla['comando']): ?>
                                    <span class="template-command"><?php echo htmlspecialchars($plantilla['comando']); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <div class="template-meta">
                            <i class="fas fa-user"></i> <?php echo htmlspecialchars($plantilla['username'] ?? 'Desconocido'); ?>
                            &nbsp;&nbsp;|&nbsp;&nbsp;
                            <i class="fas fa-clock"></i> <?php echo date('d/m/Y H:i', strtotime($plantilla['fecha_creacion'])); ?>
                        </div>
                        
                        <div class="template-content">
                            <?php echo $plantilla['contenido']; ?>
                        </div>
                        
                        <div class="template-actions">
                            <?php if (hasPermission('manage_templates', 'discord')): ?>
                            <a href="edit.php?id=<?php echo $plantilla['id']; ?>" class="btn btn-primary btn-sm">
                                <i class="fas fa-edit"></i> Editar
                            </a>
                            <?php endif; ?>
                            <?php if (hasPermission('view_templates', 'discord')): ?>
                            <button onclick="previewTemplate(<?php echo $plantilla['id']; ?>)" class="btn btn-secondary btn-sm">
                                <i class="fas fa-eye"></i> Vista Previa
                            </button>
                            <?php endif; ?>
                            <?php if (hasPermission('manage_templates', 'discord')): ?>
                            <button onclick="deleteTemplate(<?php echo $plantilla['id']; ?>, '<?php echo htmlspecialchars($plantilla['nombre'], ENT_QUOTES); ?>')" class="btn btn-danger btn-sm">
                                <i class="fas fa-trash"></i> Eliminar
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
        function previewTemplate(id) {
            window.open('preview.php?id=' + id, 'preview', 'width=800,height=600');
        }
        
        async function deleteTemplate(id, nombre) {
            if (!confirm(`¿Estás seguro de eliminar la plantilla "${nombre}"?`)) {
                return;
            }
            
            try {
                const response = await fetch('/discord/api/templates/delete.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ id })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Plantilla eliminada correctamente');
                    location.reload();
                } else {
                    alert('Error al eliminar: ' + data.error);
                }
            } catch (error) {
                alert('Error de conexión');
                console.error(error);
            }
        }
    </script>
</body>
</html>