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

if (!isset($_GET['schedule_id'])) {
    header('Location: scheduled_messages.php');
    exit();
}

$scheduleId = $_GET['schedule_id'];

// Fetch the message details
$stmt = $pdo->prepare(
    "SELECT s.*, m.content, dr.type as recipient_type 
     FROM schedules s 
     JOIN messages m ON s.message_id = m.id 
     JOIN discord_recipients dr ON s.recipient_id = dr.id
     WHERE s.id = ?"
);
$stmt->execute([$scheduleId]);
$message = $stmt->fetch();

if (!$message) {
    header('Location: scheduled_messages.php?error=not_found');
    exit();
}

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

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

<!-- Summernote CSS -->
<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs5.min.css" rel="stylesheet">

<div class="container-fluid">
    <h1 class="mt-4">Editar Notificación</h1>

    <form action="includes/message_handler_edit.php" method="POST" id="editMessageForm">
        <input type="hidden" name="schedule_id" value="<?php echo $message['id']; ?>">
        <input type="hidden" name="message_id" value="<?php echo $message['message_id']; ?>">

        <!-- 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['content']); ?></textarea>
        </div>

        <!-- Recipient Selection -->
        <div class="mb-3">
            <label class="form-label">Tipo de Destinatario</label>
            <div>
                <input type="radio" id="recipientTypeChannel" name="recipientType" value="channel" <?php echo ($message['recipient_type'] === 'channel') ? 'checked' : ''; ?>>
                <label for="recipientTypeChannel">Canal</label>
                <input type="radio" id="recipientTypeUser" name="recipientType" value="user" class="ms-3" <?php echo ($message['recipient_type'] === 'user') ? 'checked' : ''; ?>>
                <label for="recipientTypeUser">Usuario</label>
            </div>
        </div>

        <div class="mb-3 <?php echo ($message['recipient_type'] === 'user') ? 'd-none' : ''; ?>" id="channelSelectWrapper">
            <label for="channelId" class="form-label">Seleccionar Canal</label>
            <select id="channelId" name="recipientId_channel" class="form-select">
                <?php foreach ($channels as $channel): ?>
                    <option value="<?php echo $channel['id']; ?>" <?php echo ($message['recipient_id'] == $channel['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($channel['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3 <?php echo ($message['recipient_type'] === 'channel') ? 'd-none' : ''; ?>" id="userSelectWrapper">
            <label for="userId" class="form-label">Seleccionar Usuario</label>
            <select id="userId" name="recipientId_user" class="form-select">
                 <?php foreach ($users as $user): ?>
                    <option value="<?php echo $user['id']; ?>" <?php echo ($message['recipient_id'] == $user['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($user['name']); ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <!-- Scheduling Options -->
        <fieldset class="mb-3">
            <legend class="h6">Opciones de Envío</legend>
            <!-- Current implementation only allows re-scheduling. 'Send Now' could be added. -->
            <div>
                <input type="radio" id="scheduleLater" name="scheduleType" value="later" checked>
                <label for="scheduleLater">Programar para más tarde</label>
            </div>
        </fieldset>

        <div class="mb-3" id="scheduleDateTimeWrapper">
            <label for="scheduleDateTime" class="form-label">Fecha y Hora de Envío</label>
            <input type="datetime-local" id="scheduleDateTime" name="scheduleDateTime" class="form-control" value="<?php echo date('Y-m-d\TH:i', strtotime($message['send_time'])); ?>">
        </div>

        <!-- Submit Button -->
        <button type="submit" class="btn btn-primary">Actualizar Mensaje</button>

    </form>
</div>

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

<!-- Gallery Modal -->
<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>


<!-- Summernote JS -->
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs5.min.js"></script>
<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', ['link', 'picture', 'video']],
          ['view', ['fullscreen', 'codeview', 'help']],
          ['mybutton', ['gallery']]
        ],
        buttons: {
            gallery: GalleryButton
        }
    });

    // Handle image selection in modal
    $(document).on('click', '.gallery-item', function() {
        $(this).toggleClass('border-primary');
    });

    // Handle image insertion
    $('#insertImageFromGallery').click(function() {
        $('.gallery-item.border-primary').each(function(){
            var imageUrl = $(this).attr('src');
            $('#messageContent').summernote('insertImage', imageUrl);
        });
        $('#galleryModal').modal('hide');
        $('.gallery-item').removeClass('border-primary');
    });

    // Function to toggle recipient selects
    function toggleRecipientFields() {
        if ($('input[name="recipientType"]:checked').val() === 'channel') {
            $('#channelSelectWrapper').removeClass('d-none');
            $('#userSelectWrapper').addClass('d-none');
            $('#channelId').prop('name', 'recipientId');
            $('#userId').prop('name', 'recipientId_user'); // Unset name to avoid submission
        } else {
            $('#channelSelectWrapper').addClass('d-none');
            $('#userSelectWrapper').removeClass('d-none');
            $('#channelId').prop('name', 'recipientId_channel'); // Unset name
            $('#userId').prop('name', 'recipientId');
        }
    }

    // Initial toggle on page load
    toggleRecipientFields();

    // Add change event listener
    $('input[name="recipientType"]').change(toggleRecipientFields);
});
</script>
