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

try {
    $query = "
        SELECT 
            sm.id as sent_message_id, 
            sm.platform_message_id,
            s.sent_at,
            m.content,
            u.username as creator_username,
            r.name as recipient_name,
            r.type as recipient_type,
            r.platform,
            r.platform_id
         FROM sent_messages sm
         JOIN schedules s ON sm.schedule_id = s.id
         JOIN messages m ON s.message_id = m.id
         JOIN users u ON m.user_id = u.id
         JOIN recipients r ON sm.recipient_id = r.id
         ORDER BY s.sent_at DESC
    ";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $sentMessages = $stmt->fetchAll();
    
} catch (PDOException $e) {
    error_log("Error al consultar mensajes enviados: " . $e->getMessage());
    $sentMessages = [];
    $db_error = "Error de base de datos: " . $e->getMessage();
}

$pageTitle = 'Mensajes Enviados';
require_once __DIR__ . '/templates/header.php';
?>

<div class="container-fluid">
    <h1 class="mt-4" data-translate="true">Mensajes Enviados</h1>

<?php if (isset($db_error)): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($db_error) ?></div>
<?php endif; ?>

<?php 
// Obtener la plataforma del mensaje que se está eliminando (si está presente en la URL)
$platform = $_GET['platform'] ?? 'Discord';  // Por defecto a Discord para mantener compatibilidad
$platform = ucfirst(strtolower($platform));  // Asegurar que la primera letra sea mayúscula
?>

<?php if (isset($_GET['success']) && $_GET['success'] === 'deleted'): ?>
    <div class="alert alert-success"><span data-translate="true">Mensaje eliminado de</span> <?= htmlspecialchars($platform) ?> <span data-translate="true">con éxito</span>.</div>
<?php elseif (isset($_GET['error'])): ?>
    <div class="alert alert-danger">
        <?php
        $errorMessage = '<span data-translate="true">Ocurrió un error desconocido.</span>';
        if ($_GET['error'] === 'delete_failed') {
            $errorMessage = "<span data-translate='true'>No se pudo eliminar el mensaje de</span> {$platform}.";
            if (isset($_GET['message'])) {
                $errorMessage .= ' ' . htmlspecialchars($_GET['message']);
            }
        }
        echo htmlspecialchars($errorMessage);
        ?>
    </div>
<?php endif; ?>

    <div class="card shadow-sm" id="sent-messages-table">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th data-translate="true">Plataforma</th>
                            <th data-translate="true">Destinatario</th>
                            <th data-translate="true">Contenido (Previo)</th>
                            <th data-translate="true">Fecha de Envío</th>
                            <th data-translate="true">Creado por</th>
                            <th class="text-center" data-translate="true">Acciones</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($sentMessages)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted" data-translate="true">No se han enviado mensajes todavía.</td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($sentMessages as $msg): ?>
                                <tr>
                                    <td>
                                        <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>
                                    </td>
                                    <td><?= htmlspecialchars($msg['recipient_name']) . ' <span class="text-muted">(' . $msg['recipient_type'] . ')</span>' ?></td>
                                    <td class="text-break">
                                        <div class="message-preview text-content">
                                            <?= substr(strip_tags($msg['content']), 0, 100) ?>...
                                        </div>
                                    </td>
                                    <td><?= date('d/m/Y H:i', strtotime($msg['sent_at'])) ?></td>
                                    <td><?= htmlspecialchars($msg['creator_username']) ?></td>
                                    <td class="text-center">
                                        <div class="d-flex gap-2 justify-content-center">
                                            <form action="create_message.php" method="POST" class="d-inline">
                                                <input type="hidden" name="action" value="reuse">
                                                <input type="hidden" name="messageContent" value="<?= htmlspecialchars($msg['content'], ENT_QUOTES, 'UTF-8') ?>">
                                                <button type="submit" class="btn btn-sm btn-secondary" title="Reutilizar este mensaje" data-translate-title="true">
                                                    <i class="bi bi-recycle"></i>
                                                </button>
                                            </form>
                                            
                                            <?php if (!empty($msg['platform_message_id'])): ?>
                                                <?php if ($msg['platform'] === 'discord'): ?>
                                                    <form action="includes/discord_actions.php" method="POST" onsubmit="return confirm(this.querySelector('[data-translate-confirm]').getAttribute('data-translate-confirm'));" class="d-inline">
                                                        <input type="hidden" name="action" value="delete_message">
                                                        <input type="hidden" name="sent_message_id" value="<?= $msg['sent_message_id'] ?>">
                                                        <input type="hidden" name="platform_message_id" value="<?= htmlspecialchars($msg['platform_message_id'], ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="channel_id" value="<?= htmlspecialchars($msg['platform_id'], ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="confirm_message" value="¿Estás seguro de que quieres ELIMINAR este mensaje de Discord?" data-translate-confirm="¿Estás seguro de que quieres ELIMINAR este mensaje de Discord?">
                                                        <button type="submit" class="btn btn-sm btn-danger" title="Eliminar de Discord" data-translate-title="true">
                                                            <i class="bi bi-trash-fill"></i>
                                                        </button>
                                                    </form>
                                                <?php elseif ($msg['platform'] === 'telegram'): ?>
                                                    <form action="includes/telegram_actions.php" method="POST" onsubmit="return confirm(this.querySelector('[data-translate-confirm]').getAttribute('data-translate-confirm'));" class="d-inline">
                                                        <input type="hidden" name="action" value="delete_message">
                                                        <input type="hidden" name="sent_message_id" value="<?= $msg['sent_message_id'] ?>">
                                                        <input type="hidden" name="platform_message_id" value="<?= htmlspecialchars($msg['platform_message_id'], ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="chat_id" value="<?= htmlspecialchars($msg['platform_id'], ENT_QUOTES, 'UTF-8') ?>">
                                                        <input type="hidden" name="confirm_message" value="¿Estás seguro de que quieres ELIMINAR este mensaje de Telegram?" data-translate-confirm="¿Estás seguro de que quieres ELIMINAR este mensaje de Telegram?">
                                                        <button type="submit" class="btn btn-sm btn-danger" title="Eliminar de Telegram" data-translate-title="true">
                                                            <i class="bi bi-trash-fill"></i>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<style>
.message-preview {
    max-height: 80px;
    overflow-y: auto;
    padding: 8px;
    background-color: var(--bs-light);
    border: 1px solid var(--bs-border-color);
    border-radius: 5px;
    font-size: 0.9em;
    min-width: 200px;
}

[data-bs-theme="dark"] .message-preview {
    background-color: var(--bs-dark-bg-subtle);
    border-color: var(--bs-border-color-translucent);
    color: var(--bs-body-color);
}
</style>

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