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

$pageTitle = t('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-stopwatch"></i> <?= t('Mensajes Programados') ?></h2>
    <a href="create_message.php" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i> <?= t('Nuevo Mensaje') ?>
    </a>
</div>

<?php if (isset($_GET['success'])): ?>
    <div class="alert alert-success"><?= t('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"><?= t('No hay mensajes programados') ?></p>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th><?= t('ID') ?></th>
                            <th><?= t('Destinatario') ?></th>
                            <th><?= t('Plataforma') ?></th>
                            <th><?= t('Fecha de Envío') ?></th>
                            <th><?= t('Tipo') ?></th>
                            <th><?= t('Estado') ?></th>
                            <th><?= t('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"><?= t('Recurrente') ?></span>
                                <?php else: ?>
                                    <span class="badge bg-secondary"><?= t('Ú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'
                                } ?>">
                                    <?= t($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="<?= t('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="<?= t('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="<?= t('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('<?= t('¿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="<?= t('Cancelar') ?>">
                                                <i class="bi bi-x-circle"></i>
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    
                                    <form method="POST" class="d-inline" onsubmit="return confirm('<?= t('¿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="<?= t('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'; ?>
