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

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

// Fetch recipients from the database
$channels = [];
$users = [];
try {
    $stmt = $pdo->query("SELECT id, name, type FROM recipients ORDER BY name ASC");
    while ($row = $stmt->fetch()) {
        if ($row['type'] === 'channel') {
            $channels[] = $row;
        } else {
            $users[] = $row;
        }
    }
} catch (PDOException $e) {
    die("Error: No se pudieron cargar los destinatarios: " . $e->getMessage());
}

// Fetch existing recurrent messages
try {
    $recurrent_messages_stmt = $pdo->query("SELECT * FROM recurrent_messages ORDER BY created_at DESC");
    $recurrent_messages = $recurrent_messages_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Create a map of recipient IDs to names for easy lookup
    $all_recipients_stmt = $pdo->query("SELECT id, name FROM recipients");
    $recipient_map = [];
    foreach($all_recipients_stmt->fetchAll(PDO::FETCH_ASSOC) as $recipient) {
        $recipient_map[$recipient['id']] = $recipient['name'];
    }
} catch (PDOException $e) {
    die("Error: No se pudieron cargar los mensajes recurrentes.");
}


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" data-translate="true">Crear Mensaje Recurrente</h1>

    <div class="card card-body p-4 mb-4">
        <form action="includes/recurrent_message_handler.php" method="POST" id="recurrentMessageForm">
            <input type="hidden" name="action" value="create">
            <input type="hidden" name="_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
            
            <div class="row">
                <div class="col-md-6">
                    <!-- Message Name -->
                    <div class="mb-3">
                        <label for="messageName" class="form-label" data-translate="true">Nombre del Mensaje</label>
                        <input type="text" class="form-control" id="messageName" name="messageName" placeholder="Ej: Recordatorio de acomodar sus bases" data-translate-placeholder="true" required>
                        <small class="form-text text-muted" data-translate="true">Este nombre es solo para tu referencia y no se enviará.</small>
                    </div>
                </div>
                <div class="col-md-6">
                    <!-- Telegram Command -->
                    <div class="mb-3">
                        <label for="telegramCommand" class="form-label" data-translate="true">Comando de Telegram</label>
                        <input type="text" class="form-control" id="telegramCommand" name="telegram_command" placeholder="Ej: Dia6 (sin #)" data-translate-placeholder="true">
                        <small class="form-text text-muted" data-translate="true">Opcional. El comando que los usuarios usarán en Telegram (sin el #).</small>
                    </div>
                </div>
            </div>

            <!-- Message Content -->
            <div class="mb-3">
                <label for="messageContent" class="form-label" data-translate="true">Contenido del Mensaje</label>
                <textarea id="messageContent" name="messageContent" class="form-control"></textarea>
            </div>

            <!-- Submit Button -->
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-save-fill me-1"></i> <span data-translate="true">Guardar Mensaje Recurrente</span>
            </button>
        </form>
    </div>

    <hr>

    <h2 class="mt-4" data-translate="true">Mensajes Recurrentes Guardados</h2>
    <div class="table-responsive">
        <table class="table table-striped table-hover">
            <thead>
                <tr>
                    <th data-translate="true">Nombre</th>
                    <th data-translate="true">Comando Telegram</th>
                    <th data-translate="true">Acciones</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($recurrent_messages)): ?>
                    <tr>
                        <td colspan="6" class="text-center" data-translate="true">No hay mensajes recurrentes guardados.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($recurrent_messages as $msg): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($msg['name']); ?></td>
                            <td>
                                <?php if (!empty($msg['telegram_command'])): ?>
                                    <span class="badge bg-secondary">#<?php echo htmlspecialchars($msg['telegram_command']); ?></span>
                                <?php else: ?>
                                    <span class="text-muted small" data-translate="true">No asignado</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info" onclick='previewMessage(<?php echo json_encode($msg['message_content']); ?>)' data-translate-title="true" title="Vista previa">
                                    <i class="bi bi-eye-fill"></i>
                                </button>
                                <a href="edit_recurrent_message.php?id=<?php echo $msg['id']; ?>" class="btn btn-sm btn-warning" data-translate-title="true" title="Editar">
                                    <i class="bi bi-pencil-fill"></i>
                                </a>
                                <form action="includes/recurrent_message_handler.php" method="POST" class="d-inline" onsubmit="return confirm(this.querySelector('[data-translate-confirm]').getAttribute('data-translate-confirm'));">
                                    <input type="hidden" name="confirm_message" value="¿Estás seguro de que quieres eliminar este mensaje recurrente?" data-translate-confirm="¿Estás seguro de que quieres eliminar este mensaje recurrente?">
                                    <input type="hidden" name="id" value="<?php echo $msg['id']; ?>">
                                    <input type="hidden" name="action" value="delete">
                                    <button type="submit" class="btn btn-sm btn-danger" data-translate-title="true" title="Eliminar"><i class="bi bi-trash-fill"></i></button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </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" data-translate="true">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)) {
                            $image_url = site_url('galeria/' . $file);
                            echo '<div class="col-lg-3 col-md-4 col-sm-6 mb-4 text-center"><img src="' . htmlspecialchars($image_url) . '" 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" data-translate="true">Cerrar</button>
        <button type="button" class="btn btn-primary" id="insertImageFromGallery" data-translate="true">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" data-translate="true">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í...', // Este texto es manejado por Summernote internamente
        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(){
            const imageSrc = $(this).attr('src');
            console.log('Inserting image:', imageSrc);
            $('#messageContent').summernote('insertImage', imageSrc);
        });
        $('#galleryModal').modal('hide');
        $('.gallery-item').removeClass('border-primary');
    });

    // Toggle between channel and user selection (only if elements exist)
    const recipientTypeChannel = document.getElementById('recipientTypeChannel');
    const recipientTypeUser = document.getElementById('recipientTypeUser');
    const channelSelect = document.getElementById('recipientId');
    const userSelect = document.getElementById('recipientId_user');

    function updateRecipientType() {
        if (!recipientTypeChannel || !recipientTypeUser || !channelSelect || !userSelect) {
            return; // Elements don't exist, exit gracefully
        }
        
        if (recipientTypeChannel.checked) {
            channelSelect.classList.remove('d-none');
            channelSelect.required = true;
            channelSelect.disabled = false;
            userSelect.classList.add('d-none');
            userSelect.required = false;
            userSelect.disabled = true;
        } else {
            channelSelect.classList.add('d-none');
            channelSelect.required = false;
            channelSelect.disabled = true;
            userSelect.classList.remove('d-none');
            userSelect.required = true;
            userSelect.disabled = false;
        }
    }
    
    // Only add event listeners if elements exist
    if (recipientTypeChannel && recipientTypeUser) {
        recipientTypeChannel.addEventListener('change', updateRecipientType);
        recipientTypeUser.addEventListener('change', updateRecipientType);
        updateRecipientType(); // Initial call
    }

    // Form validation
    $('#recurrentMessageForm').submit(function(e) {
        if ($('#messageContent').summernote('isEmpty')) {
            e.preventDefault();
            alert('El contenido del mensaje no puede estar vacío.');
            return false;
        }
        if ($('.day-checkbox:checked').length === 0) {
            e.preventDefault();
            alert('Por favor selecciona al menos un día para la programación recurrente.');
            return false;
        }
        return true;
    });
});

// Preview message function
function previewMessage(content) {
    const previewModalBody = document.getElementById('previewModalBody');
    const modalElement = document.getElementById('previewModal');
    
    if (!previewModalBody || !modalElement) {
        console.error('Modal elements not found');
        return;
    }
    
    let processedContent = content;
    
    // Simple cleanup - ensure all image URLs are correct
    processedContent = processedContent
        .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;
    
    // Create and show the modal
    const myModal = new bootstrap.Modal(modalElement);
    myModal.show();
}
</script>
