<?php
// Este archivo contiene solo la lógica para renderizar el cuerpo de la tabla de mensajes programados.
// Se espera que sea incluido por scheduled_messages.php o llamado vía AJAX.

// Asegurarse de que las dependencias necesarias estén cargadas si se llama directamente vía AJAX
if (!defined('SCHEDULED_MESSAGES_LOADED')) {
    require_once __DIR__ . '/db.php';
    // La función getDayNames se define aquí para auto-contención
    function getDayNames($daysString) {
        if (empty($daysString)) return '<span data-translate="true">No especificado</span>';
        $dayMap = [
            0 => '<span data-translate="true">Domingo</span>', 
            1 => '<span data-translate="true">Lunes</span>', 
            2 => '<span data-translate="true">Martes</span>', 
            3 => '<span data-translate="true">Miércoles</span>',
            4 => '<span data-translate="true">Jueves</span>', 
            5 => '<span data-translate="true">Viernes</span>', 
            6 => '<span data-translate="true">Sábado</span>'
        ];
        $days = explode(',', $daysString);
        $names = array_map(fn($day) => $dayMap[(int)$day] ?? '', $days);
        return implode(', ', array_filter($names));
    }

    // Si no se ha cargado $messages, cargarla aquí (para llamadas AJAX directas)
    if (!isset($messages)) {
        $stmt = $pdo->prepare(
            "SELECT 
                s.id as schedule_id, 
                s.send_time, 
                s.status,
                s.is_recurring,
                s.recurring_days,
                s.recurring_time,
                m.id as message_id,
                m.content,
                r.name as recipient_name,
                r.type as recipient_type,
                r.platform,
                u.username as creator_username
             FROM schedules s
             JOIN messages m ON s.message_id = m.id
             LEFT JOIN recipients r ON s.recipient_id = r.id
             JOIN users u ON m.user_id = u.id
             WHERE s.status IN ('draft', 'pending', 'failed', 'processing', 'disabled')
             ORDER BY s.created_at DESC"
        );
        $stmt->execute();
        $messages = $stmt->fetchAll();
    }
}
?>

<?php if (empty($messages)):
    ?>
    <tr>
        <td colspan="7" class="text-center text-muted" data-translate="true">No hay mensajes aquí.</td>
    </tr>
<?php else:
    ?>
    <?php foreach ($messages as $msg):
        ?>
        <tr>
            <td>
                <?php if (!empty($msg['platform'])): ?>
                    <span class="badge <?= $msg['platform'] === 'discord' ? 'bg-primary' : 'bg-info text-dark' ?>">
                        <i class="bi bi-<?= $msg['platform'] === 'discord' ? 'discord' : 'telegram' ?>"></i> 
                        <?= htmlspecialchars(ucfirst($msg['platform'])) ?>
                    </span>
                <?php else: ?>
                    <span class="badge bg-secondary" data-translate="true">N/A</span>
                <?php endif; ?>
            </td>
            <td><?= !empty($msg['recipient_name']) ? htmlspecialchars($msg['recipient_name']) . ' <span class="text-muted" data-translate="true">(' . $msg['recipient_type'] . ')</span>' : '<span class="text-muted" data-translate="true">No asignado</span>' ?></td>
            <td>
                <div class="message-preview">
                    <?= substr(strip_tags($msg['content']), 0, 100); ?>...
                </div>
            </td>
            <td>
                <?php if ($msg['is_recurring'] == 1):
                    echo '<span data-translate="true">Semanal:</span> ' . getDayNames($msg['recurring_days']) . ' <span data-translate="true">a las</span> ' . substr($msg['recurring_time'], 0, 5);
                else:
                    echo $msg['send_time'] ? date('d/m/Y H:i', strtotime($msg['send_time'])) : '-';
                endif; ?>
            </td>
            <td>
                <?php 
                    $statusBadges = [
                        'pending' => 'info text-dark', 'draft' => 'secondary', 'failed' => 'danger',
                        'processing' => 'warning text-dark', 'disabled' => 'light text-dark'
                    ];
                    $badgeClass = $statusBadges[$msg['status']] ?? 'light';
                ?>
                <span class="badge bg-<?= $badgeClass ?>"><?= ucfirst($msg['status']) ?></span>
            </td>
            <td><?= htmlspecialchars($msg['creator_username']) ?></td>
            <td class="text-center">
                <div class="d-flex justify-content-center gap-1">
                    <a href="preview_message.php?id=<?= $msg['message_id'] ?>" target="_blank" class="btn btn-sm btn-info" title="Previsualizar" data-translate-title="true">
                        <i class="bi bi-eye"></i>
                    </a>
                    <a href="create_message.php?schedule_id=<?= $msg['schedule_id'] ?>&action=edit" class="btn btn-sm btn-primary" title="Editar" data-translate-title="true">
                        <i class="bi bi-pencil-square"></i>
                    </a>
                    <form action="includes/schedule_actions.php" method="POST" class="d-inline">
                        <input type="hidden" name="schedule_id" value="<?= $msg['schedule_id'] ?>">
                        <input type="hidden" name="message_id" value="<?= $msg['message_id'] ?>">

                        <?php if (in_array($msg['status'], ['pending', 'disabled'])): ?>
                            <button type="submit" name="action" value="<?= $msg['status'] === 'pending' ? 'disable' : 'enable' ?>" class="btn btn-sm btn-secondary" data-translate-title="true" title="<?= $msg['status'] === 'pending' ? 'Deshabilitar' : 'Habilitar' ?>">
                                <i class="bi <?= $msg['status'] === 'pending' ? 'bi-pause-circle' : 'bi-play-circle' ?>"></i>
                            </button>
                        <?php endif; ?>

                        <?php if ($msg['status'] === 'failed'): ?>
                        <button type="submit" name="action" value="retry" class="btn btn-sm btn-warning text-dark" title="Reintentar Envío" data-translate-title="true">
                            <i class="bi bi-arrow-repeat"></i>
                        </button>
                        <?php endif; ?>

                        <?php if ($msg['status'] === 'processing'): ?>
                            <button type="submit" name="action" value="cancel" class="btn btn-sm btn-warning" title="Cancelar Envío" data-translate-title="true" data-confirm-message="¿Estás seguro de que quieres cancelar este envío?" data-translate-confirm="true" onclick="return confirm(this.getAttribute('data-confirm-message'));">
                                <i class="bi bi-x-circle"></i>
                            </button>
                        <?php endif; ?>

                        <button type="submit" name="action" value="delete" class="btn btn-sm btn-danger" title="Borrar" data-translate-title="true" data-confirm-message="¿Estás seguro de que quieres borrar este mensaje?" data-translate-confirm="true" onclick="return confirm(this.getAttribute('data-confirm-message'));">
                                <i class="bi bi-trash"></i>
                        </button>
                    </form>
                </div>
            </td>
        </tr>
    <?php endforeach; ?>
<?php endif; ?>