<?php
require_once __DIR__ . '/includes/session_check.php';
require_once __DIR__ . '/includes/db.php';

$base_url = rtrim(BOT_BASE_URL, '/');

$message_id = $_GET['id'] ?? 0;
if (!$message_id) {
    header('Location: recurrentes.php');
    exit;
}

// Fetch the recurrent message data
try {
    $stmt = $pdo->prepare("SELECT * FROM recurrent_messages WHERE id = ?");
    $stmt->execute([$message_id]);
    $message = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$message) {
        die("Mensaje recurrente no encontrado.");
    }
} catch (PDOException $e) {
    die("Error al cargar el mensaje: " . $e->getMessage());
}

// Recipient selection is handled on the 'send from template' page, not here.

$current_days = explode(',', $message['recurring_days']);

require_once __DIR__ . '/templates/header.php';
?>

<!-- Summernote CSS -->
<link href="<?php echo asset('css/summernote-bs5.min.css'); ?>" rel="stylesheet">

<div class="container-fluid">
    <h1 class="mt-4">Editar Mensaje Recurrente</h1>

    <div class="card card-body p-4">
        <form action="includes/recurrent_message_handler.php" method="POST" id="editRecurrentMessageForm">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="<?php echo $message['id']; ?>">

            <!-- Message Name -->
            <div class="mb-3">
                <label for="messageName" class="form-label">Nombre del Mensaje</label>
                <input type="text" class="form-control" id="messageName" name="messageName" value="<?php echo htmlspecialchars($message['name']); ?>" required>
            </div>

            <!-- Telegram Command -->
            <div class="mb-3">
                <label for="telegramCommand" class="form-label">Comando de Telegram</label>
                <input type="text" class="form-control" id="telegramCommand" name="telegram_command" value="<?php echo htmlspecialchars($message['telegram_command'] ?? ''); ?>" placeholder="Ej: Dia6 (sin #)">
                <small class="form-text text-muted">Opcional. El comando que los usuarios usarán en Telegram (sin el #).</small>
            </div>

            <!-- Message Content -->
            <div class="mb-3">
                <label for="messageContent" class="form-label">Contenido del Mensaje</label>
                <textarea id="messageContent" name="messageContent" class="form-control"><?php echo htmlspecialchars($message['message_content']); ?></textarea>
            </div>

            <!-- Submit Button -->
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save-fill me-1"></i> Actualizar Mensaje
            </button>
            <a href="recurrentes.php" class="btn btn-secondary">Cancelar</a>
        </form>
    </div>
</div>

<!-- Gallery Modal (same as create_message.php) -->
<div class="modal fade" id="galleryModal" tabindex="-1" aria-labelledby="galleryModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="galleryModalLabel">Galería de Imágenes</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <div class="row">
            <?php
                $gallery_path = __DIR__ . '/galeria';
                $files = array_diff(scandir($gallery_path), array('.', '..'));
                if (empty($files)) {
                    echo '<p class="text-center text-muted">No hay imágenes en la galería.</p>';
                } else {
                    foreach ($files as $file) {
                        if (is_file($gallery_path . '/' . $file)) {
                            echo '<div class="col-lg-3 col-md-4 col-sm-6 mb-4 text-center"><img src="' . site_url('galeria/' . $file) . '" class="img-fluid img-thumbnail gallery-item" style="cursor:pointer;" alt="' . htmlspecialchars($file) . '"><p class="small text-muted mt-1">' . htmlspecialchars($file) . '</p></div>';
                        }
                    }
                }
            ?>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
        <button type="button" class="btn btn-primary" id="insertImageFromGallery">Insertar Imagen</button>
      </div>
    </div>
  </div>
</div>

<!-- Preview Modal -->
<div class="modal fade" id="previewModal" tabindex="-1" aria-labelledby="previewModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="previewModalLabel">Vista Previa del Mensaje</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="previewModalBody">
        <!-- Content will be injected here -->
      </div>
    </div>
  </div>
</div>

<?php require_once __DIR__ . '/templates/footer.php'; ?>

<script>
$(document).ready(function() {
    // Custom Gallery Button
    var GalleryButton = function (context) {
      var ui = $.summernote.ui;
      var button = ui.button({
        contents: '<i class="bi bi-images"></i> Galería',
        tooltip: 'Insertar imagen desde la galería',
        click: function () {
          $('#galleryModal').modal('show');
        }
      });
      return button.render();
    }

    // Initialize Summernote
    $('#messageContent').summernote({
        placeholder: 'Escribe tu mensaje aquí...',
        tabsize: 2,
        height: 300,
        toolbar: [
          ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['color', ['color']],
          ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']],
          ['insert', ['picture']], ['view', ['codeview']], ['mybutton', ['gallery']]
        ],
        buttons: { gallery: GalleryButton },
        callbacks: {
            onImageUpload: function(files) {
                var editor = $(this);
                var data = new FormData();
                data.append("file", files[0]);
                $.ajax({
                    url: 'upload_editor_image.php', method: 'POST', data: data,
                    processData: false, contentType: false,
                    success: function(response) {
                        if (response.url) {
                            editor.summernote('insertImage', response.url);
                        } else {
                            alert(response.error || 'Error al subir la imagen.');
                        }
                    },
                    error: function() {
                        alert('Error: No se pudo comunicar con el servidor para subir la imagen.');
                    }
                });
            }
        }
    });

    // Handle image selection and insertion from gallery
    $(document).on('click', '.gallery-item', function() { $(this).toggleClass('border-primary'); });
    $('#insertImageFromGallery').click(function() {
        $('.gallery-item.border-primary').each(function(){
            $('#messageContent').summernote('insertImage', $(this).attr('src'));
        });
        $('#galleryModal').modal('hide');
        $('.gallery-item').removeClass('border-primary');
    });

    // No recipient logic is needed on this page.

    // Form validation
    $('#editRecurrentMessageForm').submit(function(e) {
        if ($('#messageContent').summernote('isEmpty')) {
            e.preventDefault();
            alert('El contenido del mensaje no puede estar vacío.');
            return false;
        }
        return true;
    });
});

// Preview message function
function previewMessage(content) {
    const previewModalBody = document.getElementById('previewModalBody');
    const modalElement = document.getElementById('previewModal');
    
    // Simple cleanup - ensure all image URLs are correct
    let processedContent = content
        .replace(/src="[^"]*galeria\/([^"]+)"/g, 'src="/galeria/$1"')
        .replace(/src='[^']*galeria\/([^']+)'/g, "src='/galeria/$1'");
    
    // Add proper styling to images
    processedContent = processedContent.replace(/<img([^>]*)>/g, '<img$1 style="max-width: 100%; height: auto; border-radius: 8px; margin: 10px 0;">');
    
    previewModalBody.innerHTML = processedContent;
    
    const myModal = new bootstrap.Modal(modalElement);
    myModal.show();
}
</script>
