<?php
session_start();

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

$userData = JWTAuth::requireAuth();

// Verificar permiso para ver y editar plantillas
if (!hasPermission('manage_templates', 'discord')) {
    die('No tienes permiso para editar plantillas de Discord.'); // Mensaje de error más general para evitar leaks
}

// Obtener ID de la plantilla
$id = $_GET['id'] ?? null;

if (!$id) {
    header('Location: list.php');
    exit;
}

$db = getDB();
$stmt = $db->prepare("
    SELECT p.*, c.comando 
    FROM plantillas_discord p
    LEFT JOIN comandos_discord c ON p.id = c.plantilla_id
    WHERE p.id = ?
");
$stmt->execute([$id]);
$plantilla = $stmt->fetch();

if (!$plantilla) {
    header('Location: list.php');
    exit;
}

// Verificar propiedad de la plantilla si no es Admin
if ($userData->rol !== 'Admin' && $plantilla['usuario_id'] != $userData->userId) {
    die('No tienes permiso para editar esta plantilla, ya que no te pertenece.');
}

$error = $_GET['error'] ?? '';
$success = $_GET['success'] ?? '';
?>
<!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>Editar Plantilla - Discord</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">
    <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;
        }
        
        .container {
            max-width: 1000px;
            margin: 0 auto;
        }
        
        .form-container {
            background: white;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
        }
        
        .form-group {
            margin-bottom: 25px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 600;
            font-size: 14px;
        }
        
        .form-group input[type="text"] {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 15px;
            transition: border-color 0.3s;
        }
        
        .form-group input[type="text"]:focus {
            outline: none;
            border-color: var(--discord-color);
        }
        
        .form-help {
            font-size: 13px;
            color: #666;
            margin-top: 5px;
        }
        
        .alert {
            padding: 12px 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
        }
        
        .alert-error {
            background: #fee;
            color: #c33;
            border-left: 4px solid #c33;
        }
        
        .alert-success {
            background: #efe;
            color: #3c3;
            border-left: 4px solid #3c3;
        }
        
        .btn {
            padding: 12px 24px;
            border-radius: 8px;
            text-decoration: none;
            transition: all 0.2s;
            border: none;
            cursor: pointer;
            font-size: 15px;
            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;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .form-actions {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }
        
        .note-editor {
            border: 2px solid #e0e0e0;
            border-radius: 8px;
        }
        
        .note-editor.note-frame {
            border-color: var(--discord-color);
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 9999;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
        }
        
        .modal-content {
            background: white;
            margin: 50px auto;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 900px;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .modal-header h2 {
            color: var(--discord-color);
        }
        
        .close {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
        }
        
        .close:hover {
            color: #333;
        }
        
        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .gallery-item {
            cursor: pointer;
            border: 3px solid transparent;
            border-radius: 10px;
            overflow: hidden;
            transition: all 0.3s;
        }
        
        .gallery-item:hover {
            border-color: var(--discord-color);
            transform: scale(1.05);
        }
        
        .gallery-item img {
            width: 100%;
            height: 150px;
            object-fit: cover;
            display: block;
        }
        
        .upload-area {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            border-color: var(--discord-color);
            background: #f8f9fa;
        }
        
        .upload-area input[type="file"] {
            display: none;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1><i class="fas fa-edit"></i> Editar Plantilla</h1>
        <a href="list.php" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i> Volver
        </a>
    </div>
    
    <div class="container">
        <div class="form-container">
            <div id="alert-messages">
                <?php if ($error): ?>
                    <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
                <?php endif; ?>
                
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
                <?php endif; ?>
            </div>
            
            <form id="editTemplateForm">
                <input type="hidden" id="templateId" value="<?php echo htmlspecialchars($plantilla['id']); ?>">
                <div class="form-group">
                    <label for="nombre">Nombre de la Plantilla *</label>
                    <input type="text" id="nombre" name="nombre" required value="<?php echo htmlspecialchars($plantilla['nombre']); ?>">
                    <div class="form-help">Nombre descriptivo para identificar la plantilla</div>
                </div>
                
                <div class="form-group">
                    <label for="comando">Comando (opcional)</label>
                    <input type="text" id="comando" name="comando" placeholder="Ej: /comandos, #asedio" value="<?php echo htmlspecialchars($plantilla['comando'] ?? ''); ?>">
                    <div class="form-help">Comando para invocar esta plantilla en Discord. Debe ser único.</div>
                </div>
                
                <div class="form-group">
                    <label for="contenido">Contenido *</label>
                    <button type="button" onclick="openGallery()" class="btn btn-success" style="margin-bottom: 10px;">
                        <i class="fas fa-images"></i> Insertar Imagen
                    </button>
                    <textarea id="contenido" name="contenido"><?php echo htmlspecialchars($plantilla['contenido']); ?></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> Guardar Cambios
                    </button>
                    <button type="button" onclick="previewContent()" class="btn btn-secondary">
                        <i class="fas fa-eye"></i> Vista Previa
                    </button>
                    <a href="list.php" class="btn btn-secondary">
                        <i class="fas fa-times"></i> Cancelar
                    </a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Modal de Galería -->
    <div id="galleryModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2><i class="fas fa-images"></i> Galería de Imágenes</h2>
                <span class="close" onclick="closeGallery()">&times;</span>
            </div>
            
            <div class="upload-area" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-cloud-upload-alt" style="font-size: 48px; color: #ddd;"></i>
                <p style="margin-top: 10px; color: #666;">Haz clic para subir una imagen o arrastra aquí</p>
                <input type="file" id="fileInput" accept="image/*" onchange="uploadImage(this)">
            </div>
            
            <div class="gallery-grid" id="galleryGrid">
                <p style="text-align: center; color: #999;">Cargando imágenes...</p>
            </div>
        </div>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script>
        $(document).ready(function() {
            console.log('edit.php script loaded and ready');
            $('#contenido').summernote({
                height: 300,
                toolbar: [
                    ['style', ['style']],
                    ['font', ['bold', 'underline', 'clear']],
                    ['color', ['color']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link']],
                    ['view', ['fullscreen', 'codeview', 'help']]
                ]
            });

            // Handle form submission via Fetch API
            $('#editTemplateForm').on('submit', async function(e) {
                e.preventDefault(); // Prevent default form submission

                const id = $('#templateId').val();
                const nombre = $('#nombre').val();
                const comando = $('#comando').val();
                const contenido = $('#contenido').summernote('code'); // Get content from Summernote

                // Clear previous alerts
                $('#alert-messages').empty();

                if (!nombre || !contenido) {
                    showAlert('El nombre y el contenido son obligatorios.', 'error');
                    return;
                }

                try {
                    const response = await fetch('/discord/api/templates/edit.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ id, nombre, comando, contenido })
                    });

                    const result = await response.json();

                    if (result.success) {
                        showAlert('Plantilla actualizada correctamente.', 'success');
                        setTimeout(() => {
                            window.location.href = 'list.php';
                        }, 1500); // Redirect after a short delay
                    } else {
                        showAlert(result.error || 'Error desconocido al actualizar la plantilla.', 'error');
                    }
                } catch (error) {
                    console.error('Error al enviar la solicitud:', error);
                    showAlert('Error de conexión al guardar la plantilla.', 'error');
                }
            });
        });
        
        function openGallery() {
            document.getElementById('galleryModal').style.display = 'block';
            loadGallery();
        }
        
        function closeGallery() {
            document.getElementById('galleryModal').style.display = 'none';
        }
        
        async function loadGallery() {
            try {
                const response = await fetch('/gallery/api/list.php');
                const data = await response.json();
                
                const grid = document.getElementById('galleryGrid');
                
                if (data.success && data.images.length > 0) {
                    grid.innerHTML = data.images.map(img => `
                        <div class="gallery-item" onclick="insertImage('${img.url}')">
                            <img src="${img.url_thumbnail}" alt="${img.nombre_original}">
                        </div>
                    `).join('');
                } else {
                    grid.innerHTML = '<p style="text-align: center; color: #999;">No hay imágenes disponibles</p>';
                }
            } catch (error) {
                console.error('Error cargando galería:', error);
                document.getElementById('galleryGrid').innerHTML = '<p style="text-align: center; color: #c33;">Error cargando imágenes</p>';
            }
        }
        
        function insertImage(url) {
            const fullUrl = window.location.origin + url;
            $('#contenido').summernote('insertImage', fullUrl);
            closeGallery();
        }
        
        async function uploadImage(input) {
            if (!input.files || !input.files[0]) return;
            
            const formData = new FormData();
            formData.append('image', input.files[0]);
            
            try {
                const response = await fetch('/gallery/api/upload.php', {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('Imagen subida correctamente');
                    loadGallery();
                } else {
                    alert('Error: ' + data.error);
                }
            } catch (error) {
                alert('Error al subir la imagen');
                console.error(error);
            }
            
            input.value = '';
        }
        
        function previewContent() {
            const content = $('#contenido').summernote('code');
            const win = window.open('', 'Preview', 'width=800,height=600');
            win.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Vista Previa</title>
                    <style>
                        body {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                            padding: 20px;
                            background: #f8f9fa;
                        }
                        .preview-container {
                            background: white;
                            padding: 30px;
                            border-radius: 10px;
                            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                        }
                    </style>
                </head>
                <body>
                    <div class="preview-container">
                        ${content}
                    </div>
                </body>
                </html>
            `);
        }
        
        window.onclick = function(event) {
            const modal = document.getElementById('galleryModal');
            if (event.target == modal) {
                closeGallery();
            }
        }

        function showAlert(message, type) {
            const alertDiv = `<div class="alert alert-${type}">${message}</div>`;
            $('#alert-messages').html(alertDiv);
        }
    </script>
</body>
</html>
