<?php
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/session_check.php';
checkSession();
require_once __DIR__ . '/includes/message_handler.php';
require_once __DIR__ . '/includes/schedule_actions.php';

$pageTitle = 'Mensajes Programados';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $scheduleId = (int) $_POST['schedule_id'];
    $action = $_POST['action'];
    
    $result = handleScheduleAction($scheduleId, $action);
    
    header('Location: scheduled_messages.php');
    exit;
}

$userId = getCurrentUserId();
$messages = getScheduledMessages(isAdmin() ? null : $userId);

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

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2><i class="bi bi-clock"></i> Mensajes Programados</h2>
    <a href="create_message.php" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i> Nuevo Mensaje
    </a>
</div>

<?php if (isset($_GET['success'])): ?>
    <div class="alert alert-success">Mensaje creado exitosamente</div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body">
        <?php if (empty($messages)): ?>
            <p class="text-muted text-center py-4">No hay mensajes programados</p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Destinatario</th>
                            <th>Plataforma</th>
                            <th>Fecha de Envío</th>
                            <th>Tipo</th>
                            <th>Estado</th>
                            <th>Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($messages as $msg): ?>
                        <tr>
                            <td>#<?= $msg['id'] ?></td>
                            <td><?= htmlspecialchars($msg['recipient_name']) ?></td>
                            <td>
                                <?php if ($msg['platform'] === 'discord'): ?>
                                    <i class="bi bi-discord platform-discord"></i> Discord
                                <?php else: ?>
                                    <i class="bi bi-telegram platform-telegram"></i> Telegram
                                <?php endif; ?>
                            </td>
                            <td><?= date('d/m/Y H:i', strtotime($msg['send_time'])) ?></td>
                            <td>
                                <?php if ($msg['is_recurring']): ?>
                                    <span class="badge bg-info">Recurrente</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">Único</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-<?= match($msg['status']) {
                                    'pending' => 'warning',
                                    'processing' => 'info',
                                    'sent' => 'success',
                                    'failed' => 'danger',
                                    'disabled' => 'secondary',
                                    'cancelled' => 'dark',
                                    default => 'light'
                                } ?>">
                                    <?= $msg['status'] ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <?php if ($msg['status'] === 'pending'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="schedule_id" value="<?= $msg['id'] ?>">
                                            <input type="hidden" name="action" value="disable">
                                            <button type="submit" class="btn btn-outline-warning" title="Deshabilitar">
                                                <i class="bi bi-pause"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($msg['status'] === 'disabled'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="schedule_id" value="<?= $msg['id'] ?>">
                                            <input type="hidden" name="action" value="enable">
                                            <button type="submit" class="btn btn-outline-success" title="Habilitar">
                                                <i class="bi bi-play"></i>
                                            </button>
                                        </form>
                                    <?php elseif ($msg['status'] === 'failed'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="schedule_id" value="<?= $msg['id'] ?>">
                                            <input type="hidden" name="action" value="retry">
                                            <button type="submit" class="btn btn-outline-info" title="Reintentar">
                                                <i class="bi bi-arrow-clockwise"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <?php if ($msg['status'] !== 'sent'): ?>
                                        <form method="POST" class="d-inline" onsubmit="return confirm('¿Cancelar este mensaje?');">
                                            <input type="hidden" name="schedule_id" value="<?= $msg['id'] ?>">
                                            <input type="hidden" name="action" value="cancel">
                                            <button type="submit" class="btn btn-outline-secondary" title="Cancelar">
                                                <i class="bi bi-x-circle"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <form method="POST" class="d-inline" onsubmit="return confirm('¿Eliminar este mensaje?');">
                                        <input type="hidden" name="schedule_id" value="<?= $msg['id'] ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="btn btn-outline-danger" title="Eliminar">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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