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

// Obtener el ID del usuario actual
$currentUserId = $_SESSION['user_id'] ?? null;

// Obtener mensajes programados solo del usuario actual
$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.platform as recipient_platform, -- Añadimos la plataforma
        u.username as creator_username
     FROM schedules s
     JOIN messages m ON s.message_id = m.id
     JOIN recipients r ON s.recipient_id = r.id -- Usamos la nueva tabla 'recipients'
     JOIN users u ON m.user_id = u.id
     WHERE m.user_id = ?
     AND s.status IN ('draft', 'pending', 'failed')
     ORDER BY s.created_at DESC"
);
$stmt->execute([$currentUserId]);
$messages = $stmt->fetchAll();

// Función auxiliar para convertir días de recurrencia a nombres
function getDayNames($daysString) {
    // Verificar si el valor es nulo o no es una cadena
    if ($daysString === null || !is_string($daysString)) {
        return '';
    }
    
    // Eliminar espacios en blanco y verificar si está vacío
    $daysString = trim($daysString);
    if (empty($daysString)) {
        return '';
    }
    
    $dayMap = [
        0 => 'Domingo',
        1 => 'Lunes',
        2 => 'Martes',
        3 => 'Miércoles',
        4 => 'Jueves',
        5 => 'Viernes',
        6 => 'Sábado'
    ];
    
    $days = explode(',', $daysString);
    $names = [];
    
    foreach ($days as $day) {
        $day = trim($day);
        if (is_numeric($day) && isset($dayMap[(int)$day])) {
            $names[] = $dayMap[(int)$day];
        }
    }
    
    return !empty($names) ? implode(', ', $names) : '';
}

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

<div class="container-fluid">
    <h1 class="mt-4" data-translate="true">Dashboard</h1>
    <p data-translate="true">Bienvenido, <?php echo htmlspecialchars($_SESSION['username']); ?>!</p>
    <p data-translate="true">Este es el panel principal. Desde aquí podrás gestionar tus notificaciones de Discord.</p>

    <div class="card shadow-sm mt-4">
        <div class="card-header">
            <h5 class="mb-0" data-translate="true">Tus Mensajes Programados</h5>
        </div>
        <div class="card-body">
            <?php if (empty($messages)): ?>
                <p class="text-muted" data-translate="true">No tienes mensajes programados actualmente.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Contenido</th>
                                <th>Destinatario</th>
                                <th>Programación</th>
                                <th>Estado</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($messages as $msg): ?>
                                <tr>
                                    <td>
                                        <div class="message-preview">
                                            <?php echo substr(strip_tags($msg['content']), 0, 80) . (strlen(strip_tags($msg['content'])) > 80 ? '...' : ''); ?>
                                        </div>
                                    </td>
                                    <td>
                                        <?php 
                                        echo htmlspecialchars($msg['recipient_name']); 
                                        if (!empty($msg['recipient_platform'])) {
                                            $badge_class = $msg['recipient_platform'] === 'discord' ? 'bg-primary' : 'bg-info';
                                            echo ' <span class="badge ' . $badge_class . '">' . htmlspecialchars(ucfirst($msg['recipient_platform'])) . '</span>';
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php 
                                        if ($msg['is_recurring']) {
                                            echo 'Recurrente: ' . getDayNames($msg['recurring_days']) . ' a las ' . 
                                                 date('H:i', strtotime($msg['recurring_time']));
                                        } else {
                                            echo date('d/m/Y H:i', strtotime($msg['send_time']));
                                        }
                                        ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $statusClass = '';
                                        switch($msg['status']) {
                                            case 'pending':
                                                $statusClass = 'text-warning';
                                                break;
                                            case 'sent':
                                                $statusClass = 'text-success';
                                                break;
                                            case 'failed':
                                                $statusClass = 'text-danger';
                                                break;
                                            case 'draft':
                                            default:
                                                $statusClass = 'text-muted';
                                        }
                                        ?>
                                        <span class="<?php echo $statusClass; ?>">
                                            <?php echo ucfirst(htmlspecialchars($msg['status'])); ?>
                                        </span>
                                    </td>
                                    <td>
                                        <form action="create_message.php" method="GET" class="d-inline">
                                            <input type="hidden" name="schedule_id" value="<?php echo $msg['schedule_id']; ?>">
                                            
                                            <a href="preview_message.php?id=<?php echo $msg['message_id']; ?>" target="_blank" class="btn btn-sm btn-info" title="Previsualizar">
                                                <i class="bi bi-eye"></i>
                                            </a>

                                            <button type="submit" name="action" value="edit" class="btn btn-sm btn-primary" title="Editar">
                                                <i class="bi bi-pencil-square"></i>
                                            </button>
                                        </form>

                                        <form action="includes/schedule_actions.php" method="POST" class="d-inline">
                                            <input type="hidden" name="schedule_id" value="<?php echo $msg['schedule_id']; ?>">
                                            <input type="hidden" name="message_id" value="<?php echo $msg['message_id']; ?>">

                                            <button type="submit" 
                                                    name="action" 
                                                    value="delete" 
                                                    class="btn btn-sm btn-danger" 
                                                    title="Eliminar"
                                                    onclick="return confirm('¿Estás seguro de que quieres borrar este mensaje? Esta acción es irreversible.');">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.message-preview {
    max-height: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}
</style>

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