<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

check_role('administrador');

$user = get_logged_in_user();

$page_title = 'Administrar Notificaciones';

// Handle bulk actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $notification_ids = isset($_POST['notification_ids']) ? $_POST['notification_ids'] : [];

    if (!empty($notification_ids)) {
        if ($action == 'mark_read') {
            $placeholders = str_repeat('?,', count($notification_ids) - 1) . '?';
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 1 WHERE id IN ($placeholders)");
            $stmt->execute($notification_ids);
            $success = 'Notificaciones marcadas como leídas.';
        } elseif ($action == 'mark_unread') {
            $placeholders = str_repeat('?,', count($notification_ids) - 1) . '?';
            $stmt = $pdo->prepare("UPDATE notifications SET is_read = 0 WHERE id IN ($placeholders)");
            $stmt->execute($notification_ids);
            $success = 'Notificaciones marcadas como no leídas.';
        } elseif ($action == 'delete') {
            $placeholders = str_repeat('?,', count($notification_ids) - 1) . '?';
            $stmt = $pdo->prepare("DELETE FROM notifications WHERE id IN ($placeholders)");
            $stmt->execute($notification_ids);
            $success = 'Notificaciones eliminadas.';
        }
    }
}

// Get all notifications (no pagination, no search)
$query = "SELECT n.*, u.first_name, u.last_name, r.name as role_name, c.name as career_name
          FROM notifications n
          JOIN users u ON n.user_id = u.id
          JOIN roles r ON u.role_id = r.id
          LEFT JOIN careers c ON n.career_id = c.id
          ORDER BY n.created_at DESC";

$stmt = $pdo->prepare($query);
$stmt->execute();
$notifications = $stmt->fetchAll();
$total_notifications = count($notifications);

// Count notifications by status
$read_count = 0;
$unread_count = 0;
foreach ($notifications as $notification) {
    if ($notification['is_read']) {
        $read_count++;
    } else {
        $unread_count++;
    }
}

$content = (isset($success) ? '<div class="alert alert-success">' . $success . '</div>' : '') . '
<div class="row">
    <div class="col-12">
        <div class="card">

            <style>
.notification-badge {
    font-size: 0.75rem;
    font-weight: 600;
    padding: 0.375rem 0.75rem;
    border-radius: 20px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: 2px solid;
    display: inline-block;
    min-width: 80px;
    text-align: center;
}

.notification-badge-info {
    background: #17a2b8;
    color: white;
    border-color: #17a2b8;
    box-shadow: 0 2px 4px rgba(23, 162, 184, 0.3);
}

.notification-badge-success {
    background: #28a745;
    color: white;
    border-color: #28a745;
    box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
}

.notification-badge-warning {
    background:  #ffc107;
    color: #212529;
    border-color: #ffc107;
    box-shadow: 0 2px 4px rgba(255, 193, 7, 0.3);
}

.notification-badge-danger {
    background: #dc3545;
    color: white;
    border-color: #dc3545;
    box-shadow: 0 2px 4px rgba(220, 53, 69, 0.3);
}

.status-badge {
    font-size: 0.7rem;
    font-weight: 500;
    padding: 0.25rem 0.5rem;
    border-radius: 12px;
    text-transform: uppercase;
    letter-spacing: 0.3px;
}

.status-badge-primary {
    background: #007bff;
    color: white;
}

.status-badge-secondary {
    background: linear-gradient(135deg, #6c757d, #495057);
    color: white;
}

.notification-counters {
    display: flex;
    gap: 0.5rem;
    align-items: center;
}

.notification-counter {
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
    font-size: 0.875rem;
    font-weight: 500;
    padding: 0.375rem 0.75rem;
    border-radius: 20px;
    border: 2px solid;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    min-width: 100px;
    justify-content: center;
    transition: all 0.3s ease;
}

.notification-counter-total {
    background: #17a2b8;
    color: white;
    border-color: #17a2b8;
    box-shadow: 0 2px 4px rgba(23, 162, 184, 0.3);
}

.notification-counter-read {
    background: #28a745;
    color: white;
    border-color: #28a745;
    box-shadow: 0 2px 4px rgba(40, 167, 69, 0.3);
}

.notification-counter-unread {
    background: #ffc107;
    color: #212529;
    border-color: #ffc107;
    box-shadow: 0 2px 4px rgba(255, 193, 7, 0.3);
}

.notification-counter:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.notification-counter i {
    font-size: 0.875rem;
}
</style>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Notificaciones del Sistema</h3>
                <div class="card-tools">
                    <div class="notification-counters">
                        <span class="notification-counter notification-counter-total">
                            <i class="fas fa-bell"></i> ' . $total_notifications . ' Total
                        </span>
                        <span class="notification-counter notification-counter-read">
                            <i class="fas fa-check-circle"></i> ' . $read_count . ' Leídas
                        </span>
                        <span class="notification-counter notification-counter-unread">
                            <i class="fas fa-envelope"></i> ' . $unread_count . ' No leídas
                        </span>
                    </div>
                </div>
            </div>

           

            <div class="card-body">
                <div class="table-responsive">
                        <table id="notificationsTable" class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Usuario</th>
                                    <th>Programa</th>
                                    <th>Tipo</th>
                                    <th>Título</th>
                                    <th>Mensaje</th>
                                    <th>Estado</th>
                                    <th>Fecha</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>';

foreach ($notifications as $notification) {
    $badge_class = '';
    switch ($notification['type']) {
        case 'info':
            $badge_class = 'notification-badge notification-badge-info';
            break;
        case 'success':
            $badge_class = 'notification-badge notification-badge-success';
            break;
        case 'warning':
            $badge_class = 'notification-badge notification-badge-warning';
            break;
        case 'danger':
            $badge_class = 'notification-badge notification-badge-danger';
            break;
    }

    $read_badge = $notification['is_read'] ? '<span class="status-badge status-badge-secondary">Leída</span>' : '<span class="status-badge status-badge-primary">No leída</span>';

    $content .= '<tr>
        <td>
            <strong>' . htmlspecialchars($notification['first_name'] . ' ' . $notification['last_name']) . '</strong><br>
            <small class="text-muted">' . ucfirst($notification['role_name']) . '</small>
        </td>
        <td>' . htmlspecialchars($notification['career_name'] ?: 'Todas las carreras') . '</td>
        <td>
            <span class="badge ' . $badge_class . '">' . ucfirst($notification['type']) . '</span>
        </td>
        <td>' . htmlspecialchars($notification['title'] ?: 'Sin título') . '</td>
        <td>
            <div style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                ' . htmlspecialchars($notification['message']) . '
            </div>
        </td>
        <td>' . $read_badge . '</td>
        <td>' . date('d/m/Y H:i', strtotime($notification['created_at'])) . '</td>
        <td>
            <div class="btn-group">
                
                
            
                <form method="post" style="display: inline;" onsubmit="return confirm(\'¿Eliminar esta notificación?\')">
                    <input type="hidden" name="notification_ids[]" value="' . $notification['id'] . '">
                    <button type="submit" name="action" value="delete" class="btn btn-danger btn-sm">
                        <i class="fas fa-trash"></i>
                    </button>
                </form>
            </div>
        </td>
    </tr>';
}

$content .= '</tbody>
                        </table>
                    </div>
            </div>
        </div>
    </div>
</div>';

$content .= '
<!-- Notification Detail Modal -->
<div class="modal fade" id="notificationModal" tabindex="-1" aria-labelledby="notificationModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="notificationModalLabel">Detalle de Notificación</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="notificationDetail">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable with Spanish language
    $(\'#notificationsTable\').DataTable({
        "language": {
            "lengthMenu": "Mostrar _MENU_ entradas por página",
            "zeroRecords": "No se encontraron resultados",
            "info": "Mostrando página _PAGE_ de _PAGES_",
            "infoEmpty": "No hay registros disponibles",
            "infoFiltered": "(filtrado de _MAX_ registros totales)",
            "search": "Buscar:",
            "paginate": {
                "first": "Primero",
                "last": "Último",
                "next": "Siguiente",
                "previous": "Anterior"
            },
            "loadingRecords": "Cargando...",
            "processing": "Procesando...",
            "emptyTable": "No hay datos disponibles en la tabla"
        },
        "columnDefs": [
            { "orderable": false, "targets": [7] } // Disable sorting for actions column
        ],
        "order": [[7, "desc"]] // Sort by date column descending by default
    });

});

function viewNotification(id) {
    console.log("Loading notification ID: " + id);
    $.get("view-notification.php?id=" + id, function(data) {
        console.log("Data received:", data);
        $("#notificationDetail").html(data);
        $("#notificationModal").modal("show");
    }).fail(function(xhr, status, error) {
        console.error("AJAX Error:", status, error);
        alert("Error al cargar los detalles de la notificación: " + error);
    });
}
</script>';

include '../includes/layout.php';
?>