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

// Fetch recipients
$discord_channels = [];
$discord_users = [];
$telegram_chats = [];
try {
    $stmt = $pdo->query("SELECT id, name, type, platform FROM recipients ORDER BY platform, type, name ASC");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        if ($row['platform'] === 'discord') {
            if ($row['type'] === 'channel') $discord_channels[] = $row;
            else $discord_users[] = $row;
        } elseif ($row['platform'] === 'telegram') {
            $telegram_chats[] = $row;
        }
    }
} catch (PDOException $e) {
    die("Error: No se pudieron cargar los destinatarios.");
}

// Fetch templates
$templates = [];
try {
    $stmt = $pdo->query("SELECT id, name FROM recurrent_messages ORDER BY name ASC");
    $templates = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    die("Error: No se pudieron cargar las plantillas.");
}

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

<div class="container-fluid">
    <h1 class="mt-4">Enviar Mensaje desde Plantilla</h1>

    <form action="includes/message_handler.php" method="POST" id="sendMessageForm">
        <input type="hidden" name="submit" value="send_from_template">

        <div class="row">
            <div class="col-md-6">
                <!-- Template Selection -->
                <div class="mb-3">
                    <label for="recurrent_message_id" class="form-label">1. Seleccionar Plantilla</label>
                    <select class="form-select" id="recurrent_message_id" name="recurrent_message_id" required>
                        <option value="" selected disabled>Elige una plantilla...</option>
                        <?php foreach ($templates as $template): ?>
                            <option value="<?php echo $template['id']; ?>"><?php echo htmlspecialchars($template['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Platform Selection -->
                <div class="mb-3">
                    <label class="form-label">2. Seleccionar Plataforma</label>
                    <div>
                        <input type="radio" class="btn-check" name="platform" id="platform_discord" value="discord" autocomplete="off" checked>
                        <label class="btn btn-outline-primary" for="platform_discord">Discord</label>

                        <input type="radio" class="btn-check" name="platform" id="platform_telegram" value="telegram" autocomplete="off">
                        <label class="btn btn-outline-primary" for="platform_telegram">Telegram</label>
                    </div>
                </div>

                <!-- Recipient Selection -->
                <div class="mb-3">
                    <label for="recipient_id" class="form-label">3. Seleccionar Destinatarios</label>
                    
                    <!-- Discord Channels -->
                    <select class="form-select recipient-select" id="recipient_id_discord_channel" name="recipient_id[]" multiple>
                        <optgroup label="Canales de Discord">
                            <?php foreach ($discord_channels as $c): ?><option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option><?php endforeach; ?>
                        </optgroup>
                    </select>

                    <!-- Discord Users -->
                    <select class="form-select recipient-select mt-2" id="recipient_id_discord_user" name="recipient_id[]" multiple>
                         <optgroup label="Usuarios de Discord">
                            <?php foreach ($discord_users as $u): ?><option value="<?php echo $u['id']; ?>"><?php echo htmlspecialchars($u['name']); ?></option><?php endforeach; ?>
                        </optgroup>
                    </select>

                    <!-- Telegram Chats -->
                    <select class="form-select recipient-select d-none mt-2" id="recipient_id_telegram" name="recipient_id[]" multiple>
                        <optgroup label="Chats de Telegram">
                            <?php foreach ($telegram_chats as $t): ?><option value="<?php echo $t['id']; ?>"><?php echo htmlspecialchars($t['name']); ?></option><?php endforeach; ?>
                        </optgroup>
                    </select>
                    <small class="form-text text-muted">Mantén Ctrl (o Cmd) para seleccionar varios. Solo se enviará a los de la plataforma elegida.</small>
                </div>
            </div>

            <div class="col-md-6">
                <!-- Schedule Options -->
                <div class="mb-3">
                    <label class="form-label">4. Programar Envío</label>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="scheduleType" id="scheduleNow" value="now" checked>
                        <label class="form-check-label" for="scheduleNow">Enviar ahora</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="scheduleType" id="scheduleLater" value="later">
                        <label class="form-check-label" for="scheduleLater">Programar para más tarde</label>
                    </div>
                </div>

                <div class="mb-3" id="scheduleLaterOptions" style="display: none;">
                    <label for="scheduleDateTime" class="form-label">Fecha y Hora</label>
                    <input type="datetime-local" class="form-control" id="scheduleDateTime" name="scheduleDateTime" min="<?php echo date('Y-m-d\TH:i'); ?>">
                </div>
            </div>
        </div>

        <button type="submit" class="btn btn-success"><i class="bi bi-send-fill me-1"></i> Enviar Mensaje</button>
    </form>
</div>

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

<script>
$(document).ready(function() {
    const platformDiscord = $('#platform_discord');
    const platformTelegram = $('#platform_telegram');
    const discordChannelSelect = $('#recipient_id_discord_channel');
    const discordUserSelect = $('#recipient_id_discord_user');
    const telegramSelect = $('#recipient_id_telegram');

    function togglePlatformView() {
        if (platformDiscord.is(':checked')) {
            discordChannelSelect.removeClass('d-none');
            discordUserSelect.removeClass('d-none');
            telegramSelect.addClass('d-none');
        } else {
            discordChannelSelect.addClass('d-none');
            discordUserSelect.addClass('d-none');
            telegramSelect.removeClass('d-none');
        }
    }

    platformDiscord.on('change', togglePlatformView);
    platformTelegram.on('change', togglePlatformView);
    togglePlatformView(); // Initial call

    // Toggle schedule options
    $('input[name="scheduleType"]').on('change', function() {
        $('#scheduleLaterOptions').toggle(this.value === 'later');
    });

    // Form validation
    $('#sendMessageForm').submit(function(e) {
        let selectedRecipients = 0;
        if (platformDiscord.is(':checked')) {
            selectedRecipients += discordChannelSelect.val().length;
            selectedRecipients += discordUserSelect.val().length;
        } else {
            selectedRecipients += telegramSelect.val().length;
        }

        if (selectedRecipients === 0) {
            e.preventDefault();
            alert('Debes seleccionar al menos un destinatario para la plataforma elegida.');
            return false;
        }
        return true;
    });
});
</script>
