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

check_role('egresado');

$user = get_logged_in_user();

// Get graduate
$stmt = $pdo->prepare("SELECT * FROM graduates WHERE user_id = ?");
$stmt->execute([$user['id']]);
$graduate = $stmt->fetch();

if (!$graduate) {
    die('Graduate profile not found.');
}

$page_title = 'Mis Notificaciones - Egresado';

// Handle delete action
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_notification'])) {
    $notification_id = $_POST['delete_notification'];
    $stmt = $pdo->prepare("DELETE FROM notifications WHERE id = ? AND user_id = ?");
    $stmt->execute([$notification_id, $user['id']]);
    header('Location: /graduate/notifications');
    exit;
}

// Filters
$read_filter = isset($_GET['read']) ? $_GET['read'] : '';

// Pagination
$per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $per_page;

// Build query
$query = "SELECT n.*, c.name as career_name FROM notifications n LEFT JOIN careers c ON n.career_id = c.id WHERE n.user_id = ?";

$params = [$user['id']];

if ($read_filter !== '') {
    $query .= " AND is_read = ?";
    $params[] = (int)$read_filter;
}

$query .= " ORDER BY created_at DESC";

// Get total count
$count_query = str_replace("SELECT n.*, c.name as career_name", "SELECT COUNT(*) as total", $query);
$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_notifications = $count_stmt->fetch()['total'];
$total_pages = ceil($total_notifications / $per_page);

// Get notifications for current page
$query .= " LIMIT " . (int)$per_page . " OFFSET " . (int)$offset;
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$notifications = $stmt->fetchAll();

// Get statistics
$stats_query = "SELECT
    COUNT(*) as total,
    SUM(CASE WHEN is_read = 0 THEN 1 ELSE 0 END) as unread,
    SUM(CASE WHEN type = 'info' THEN 1 ELSE 0 END) as info_count,
    SUM(CASE WHEN type = 'success' THEN 1 ELSE 0 END) as success_count,
    SUM(CASE WHEN type = 'warning' THEN 1 ELSE 0 END) as warning_count,
    SUM(CASE WHEN type = 'danger' THEN 1 ELSE 0 END) as danger_count
    FROM notifications WHERE user_id = ?";

$stats = $pdo->prepare($stats_query);
$stats->execute([$user['id']]);
$stats = $stats->fetch();

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

        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Mis Notificaciones</h3>
                <div class="card-tools">
                    <span class="badge badge-info">' . $total_notifications . ' <strong>Total</strong></span>
                </div>
            </div>

            <!-- Filters -->
            <div class="card-header">
                <form method="get" class="row g-3">
                    <div class="col-md-4">
                        <select name="read" class="form-control">
                            <option value="">Todas las notificaciones</option>
                            <option value="0" ' . ($read_filter === '0' ? 'selected' : '') . '>No leídas</option>
                            <option value="1" ' . ($read_filter === '1' ? 'selected' : '') . '>Leídas</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> Filtrar</button>
                        <a href="/graduate/notifications" class="btn btn-secondary"><i class="fas fa-times"></i> Limpiar</a>
                    </div>
                </form>
            </div>

            

            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Carrera</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 = 'badge bg-info';
            break;
        case 'success':
            $badge_class = 'badge bg-success';
            break;
        case 'warning':
            $badge_class = 'badge bg-warning';
            break;
        case 'danger':
            $badge_class = 'badge bg-danger';
            break;
    }

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

    $content .= '<tr>
        <td>' . htmlspecialchars($notification['career_name'] ?: 'General') . '</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: 400px; 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">
                <button class="btn btn-danger btn-sm" onclick="deleteNotification(' . $notification['id'] . ', this)">
                    <i class="fas fa-trash"></i> Borrar
                </button>
            </div>
        </td>
    </tr>';
}

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

// Pagination
if ($total_pages > 1) {
    $content .= '<div class="row">
        <div class="col-12">
            <nav aria-label="Notifications pagination">
                <ul class="pagination justify-content-center">';

    // Previous button
    if ($page > 1) {
        $query_string = http_build_query(array_merge($_GET, ['page' => $page - 1]));
        $content .= '<li class="page-item"><a class="page-link" href="?'.$query_string.'">Anterior</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Anterior</span></li>';
    }

    // Page numbers
    $start_page = max(1, $page - 2);
    $end_page = min($total_pages, $page + 2);

    if ($start_page > 1) {
        $query_string = http_build_query(array_merge($_GET, ['page' => 1]));
        $content .= '<li class="page-item"><a class="page-link" href="?'.$query_string.'">1</a></li>';
        if ($start_page > 2) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
    }

    for ($i = $start_page; $i <= $end_page; $i++) {
        $query_string = http_build_query(array_merge($_GET, ['page' => $i]));
        if ($i == $page) {
            $content .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $content .= '<li class="page-item"><a class="page-link" href="?'.$query_string.'">' . $i . '</a></li>';
        }
    }

    if ($end_page < $total_pages) {
        $query_string = http_build_query(array_merge($_GET, ['page' => $total_pages]));
        if ($end_page < $total_pages - 1) {
            $content .= '<li class="page-item disabled"><span class="page-link">...</span></li>';
        }
        $content .= '<li class="page-item"><a class="page-link" href="?'.$query_string.'">' . $total_pages . '</a></li>';
    }

    // Next button
    if ($page < $total_pages) {
        $query_string = http_build_query(array_merge($_GET, ['page' => $page + 1]));
        $content .= '<li class="page-item"><a class="page-link" href="?'.$query_string.'">Siguiente</a></li>';
    } else {
        $content .= '<li class="page-item disabled"><span class="page-link">Siguiente</span></li>';
    }

    $content .= '</ul>
            </nav>
        </div>
    </div>';
}

$content .= '
<!-- Notification Detail Modal -->
<div class="modal fade" id="notificationModal" tabindex="-1" role="dialog" aria-labelledby="notificationModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <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 class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>

<!-- Edit Notification Modal -->
<div class="modal fade" id="editNotificationModal" tabindex="-1" role="dialog" aria-labelledby="editNotificationModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editNotificationModalLabel">Editar Notificación</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editNotificationForm">
                <div class="modal-body">
                    <input type="hidden" id="editNotificationId" name="notification_id">
                    <div class="form-group">
                        <label for="editTitle">Título</label>
                        <input type="text" class="form-control" id="editTitle" name="title" required>
                    </div>
                    <div class="form-group">
                        <label for="editMessage">Mensaje</label>
                        <textarea class="form-control" id="editMessage" name="message" rows="4" required></textarea>
                    </div>
                    <div class="form-group">
                        <label for="editType">Tipo</label>
                        <select class="form-control" id="editType" name="type">
                            <option value="info">Info</option>
                            <option value="success">Success</option>
                            <option value="warning">Warning</option>
                            <option value="danger">Danger</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Guardar Cambios</button>
                </div>
            </form>
        </div>
    </div>
</div>';

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

<script>

function viewNotification(id) {
    $.get("view-notification.php?id=" + id, function(data) {
        $("#notificationDetail").html(data);
        $("#notificationModal").modal("show");
    }).fail(function() {
        alert("Error al cargar la notificación");
    });
}

function markAsRead(notificationId, buttonElement) {
    if (confirm("¿Marcar esta notificación como leída?")) {
        $.post("mark-notification-read.php", {
            notification_id: notificationId
        }, function(data) {
            if (data.success) {
                // Update the button and status
                $(buttonElement).replaceWith('<span class="text-success"><i class="fas fa-check-circle"></i> Leída</span>');

                // Update the status badge in the same row
                $(buttonElement).closest('tr').find('td:nth-child(5)').html('<span class="badge badge-secondary">Leída</span>');

                // Update notification count in header if it exists
                updateNotificationCount();
            } else {
                alert("Error al marcar la notificación como leída");
            }
        }, 'json').fail(function() {
            alert("Error de conexión");
        });
    }
}

function updateNotificationCount() {
    // This would require AJAX to update the count without page reload
    // For simplicity, we'll reload the page to show updated counts
    location.reload();
}

function deleteNotification(notificationId, buttonElement) {
    if (confirm("¿Estás seguro de que quieres borrar esta notificación?")) {
        $.post("delete-notification.php", {
            notification_id: notificationId
        }, function(data) {
            if (data.success) {
                // Remove the row from the table
                $(buttonElement).closest('tr').remove();
                // Update notification count in header if it exists
                updateNotificationCount();
            } else {
                alert("Error al borrar la notificación");
            }
        }, 'json').fail(function() {
            alert("Error de conexión");
        });
    }
}

function editNotification(notificationId) {
    // Load notification data via AJAX
    $.get("get-notification.php?id=" + notificationId, function(data) {
        if (data.success) {
            $('#editNotificationId').val(data.notification.id);
            $('#editTitle').val(data.notification.title);
            $('#editMessage').val(data.notification.message);
            $('#editType').val(data.notification.type);
            $('#editNotificationModal').modal('show');
        } else {
            alert("Error al cargar la notificación para editar");
        }
    }, 'json').fail(function() {
        alert("Error de conexión");
    });
}

$('#editNotificationForm').on('submit', function(e) {
    e.preventDefault();
    var formData = $(this).serialize();

    $.post("update-notification.php", formData, function(data) {
        if (data.success) {
            $('#editNotificationModal').modal('hide');
            location.reload(); // Reload to show updated data
        } else {
            alert("Error al actualizar la notificación");
        }
    }, 'json').fail(function() {
        alert("Error de conexión");
    });
});
</script>