<?php
// /elms/student/notifications.php
declare(strict_types=1);

$PAGE_TITLE = 'Notifications';
$ACTIVE = 'notifications';

require_once __DIR__ . '/../includes/student_auth.php';
require_once __DIR__ . '/../includes/elms_notifications.php';

$db = $mysqli ?? ($conn ?? null);

if (!$db instanceof mysqli) {
    http_response_code(500);
    exit('DB connection failed');
}

$db->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

$studentId = (int)($GLOBALS['STUDENT_ID'] ?? ($_SESSION['student_id'] ?? 0));

if ($studentId <= 0) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

if (isset($_GET['mark_all'])) {
    lms_mark_all_notifications_read($db, 'student', $studentId);
    header('Location: /elms/student/notifications.php?done=1');
    exit;
}

if (isset($_GET['read'])) {
    $nid = (int)$_GET['read'];
    lms_mark_notification_read($db, 'student', $studentId, $nid);

    $go = trim((string)($_GET['go'] ?? ''));
    if ($go !== '') {
        header('Location: ' . $go);
        exit;
    }
}

$notifications = lms_recent_notifications($db, 'student', $studentId, 30);
$unreadCount = lms_unread_notification_count($db, 'student', $studentId);

require_once __DIR__ . '/../includes/student_layout_top.php';
?>

<style>
    .notif-summary-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 16px;
        margin-bottom: 22px;
    }

    .notif-summary-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 18px;
        box-shadow: 0 8px 22px rgba(15,23,42,.045);
    }

    .notif-summary-icon {
        width: 40px;
        height: 40px;
        border-radius: 13px;
        background: #eff6ff;
        color: #034ea2;
        display: grid;
        place-items: center;
        font-size: 1.15rem;
        margin-bottom: 12px;
    }

    .notif-summary-value {
        font-size: 1.65rem;
        font-weight: 950;
        color: #111827;
        line-height: 1;
    }

    .notif-summary-label {
        margin-top: 7px;
        color: #7b8190;
        font-size: .78rem;
        font-weight: 850;
    }

    .notif-action-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 16px;
        box-shadow: 0 8px 22px rgba(15,23,42,.04);
        margin-bottom: 22px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
    }

    .notif-action-title {
        color: #12386f;
        font-size: 1.12rem;
        font-weight: 950;
        margin: 0;
    }

    .notif-action-sub {
        color: #7b8190;
        font-size: .84rem;
        font-weight: 650;
        margin-top: 4px;
    }

    .notif-list-shell {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        box-shadow: 0 8px 22px rgba(15,23,42,.045);
        overflow: hidden;
    }

    .notif-list-head {
        padding: 18px 20px;
        border-bottom: 1px solid #e5e7eb;
        background: linear-gradient(180deg, #fff, #fafbff);
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
    }

    .notif-list-title {
        margin: 0;
        color: #12386f;
        font-size: 1.05rem;
        font-weight: 950;
    }

    .notif-list-sub {
        color: #7b8190;
        font-size: .82rem;
        font-weight: 650;
        margin-top: 4px;
    }

    .notif-list {
        padding: 0 16px 14px;
    }

    .notif-row {
        display: grid;
        grid-template-columns: 48px minmax(0, 1fr) 150px 95px 42px;
        gap: 14px;
        align-items: center;
        padding: 16px 0;
        border-bottom: 1px solid #eef2f7;
    }

    .notif-row:last-child {
        border-bottom: 0;
    }

    .notif-row.unread {
        background: linear-gradient(90deg, rgba(239,246,255,.85), transparent 70%);
        margin-left: -16px;
        margin-right: -16px;
        padding-left: 16px;
        padding-right: 16px;
    }

    .notif-icon-v2 {
        width: 42px;
        height: 42px;
        border-radius: 14px;
        display: grid;
        place-items: center;
        background: #eff6ff;
        color: #034ea2;
        font-size: 1.05rem;
    }

    .notif-row.unread .notif-icon-v2 {
        background: #034ea2;
        color: #fff;
    }

    .notif-title-v2 {
        color: #263247;
        font-weight: 900;
        line-height: 1.35;
        margin-bottom: 4px;
    }

    .notif-message-v2 {
        color: #64748b;
        font-size: .84rem;
        line-height: 1.55;
        max-width: 860px;
    }

    .notif-time-label {
        color: #7b8190;
        font-size: .68rem;
        text-transform: uppercase;
        font-weight: 900;
        letter-spacing: .04em;
        margin-bottom: 3px;
    }

    .notif-time-value {
        color: #334155;
        font-weight: 750;
        font-size: .8rem;
        line-height: 1.35;
    }

    .notif-status-pill {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border-radius: 999px;
        padding: 6px 11px;
        font-size: .72rem;
        font-weight: 850;
        white-space: nowrap;
    }

    .notif-status-new {
        background: #fee2e2;
        color: #dc2626;
    }

    .notif-status-read {
        background: #f1f5f9;
        color: #64748b;
        border: 1px solid #e5e7eb;
    }

    .notif-open-btn {
        width: 34px;
        height: 34px;
        display: grid;
        place-items: center;
        border-radius: 50%;
        border: 1px solid #e5e7eb;
        color: #034ea2;
        background: #fff;
        transition: .15s ease;
    }

    .notif-open-btn:hover {
        background: #034ea2;
        color: #fff;
        border-color: #034ea2;
    }

    .notif-empty-v2 {
        background: #fff;
        border: 1px dashed #cbd5e1;
        border-radius: 18px;
        padding: 44px 18px;
        text-align: center;
        color: #7b8190;
    }

    .notif-empty-v2 i {
        font-size: 2.3rem;
        color: #cbd5e1;
        display: block;
        margin-bottom: 10px;
    }

    @media (max-width: 950px) {
        .notif-summary-grid {
            grid-template-columns: 1fr;
        }

        .notif-action-card {
            display: block;
        }

        .notif-action-card .notif-actions {
            margin-top: 14px;
        }

        .notif-row {
            grid-template-columns: 44px minmax(0, 1fr);
            gap: 12px;
            align-items: start;
        }

        .notif-row .notif-time-wrap,
        .notif-row .notif-status-wrap,
        .notif-row .notif-open-wrap {
            grid-column: 2;
        }

        .notif-open-btn {
            width: 100%;
            border-radius: 12px;
            height: 38px;
        }
    }
</style>

<div class="student-page-tabs">
    <a href="/elms/student/index.php">Dashboard</a>
    <a href="/elms/student/notifications.php" class="active">Notifications</a>
</div>

<?php if (isset($_GET['done'])): ?>
    <div class="alert alert-success rounded-4 border-0 shadow-sm mb-3">
        <i class="bi bi-check-circle me-1"></i>
        Notifications marked as read.
    </div>
<?php endif; ?>

<div class="notif-summary-grid">
    <div class="notif-summary-card">
        <div class="notif-summary-icon">
            <i class="bi bi-bell"></i>
        </div>
        <div class="notif-summary-value"><?= (int)count($notifications) ?></div>
        <div class="notif-summary-label">Recent Notifications</div>
    </div>

    <div class="notif-summary-card">
        <div class="notif-summary-icon">
            <i class="bi bi-envelope-exclamation"></i>
        </div>
        <div class="notif-summary-value"><?= (int)$unreadCount ?></div>
        <div class="notif-summary-label">Unread Notifications</div>
    </div>

    <div class="notif-summary-card">
        <div class="notif-summary-icon">
            <i class="bi bi-check2-all"></i>
        </div>
        <div class="notif-summary-value"><?= max(0, count($notifications) - (int)$unreadCount) ?></div>
        <div class="notif-summary-label">Read Notifications</div>
    </div>
</div>

<div class="notif-action-card">
    <div>
        <h2 class="notif-action-title">Notifications</h2>
        <div class="notif-action-sub">
            Keep track of assessment updates, releases, corrections and important ELMS messages.
        </div>
    </div>

    <div class="notif-actions d-flex flex-wrap gap-2">
        <a href="/elms/student/notifications.php?mark_all=1"
           class="btn btn-primary rounded-pill fw-bold px-4">
            <i class="bi bi-check2-all me-1"></i>
            Mark All Read
        </a>

        <a href="/elms/student/index.php"
           class="btn btn-outline-secondary rounded-pill fw-bold px-4">
            <i class="bi bi-arrow-left me-1"></i>
            Dashboard
        </a>
    </div>
</div>

<?php if (!$notifications): ?>

    <div class="notif-empty-v2">
        <i class="bi bi-bell-slash"></i>
        <h5 class="fw-bold">No notifications yet</h5>
        <p class="mb-0">Your ELMS updates will appear here.</p>
    </div>

<?php else: ?>

    <div class="notif-list-shell">
        <div class="notif-list-head">
            <div>
                <h2 class="notif-list-title">Notification History</h2>
                <div class="notif-list-sub">
                    Showing latest <?= (int)count($notifications) ?> notification(s).
                </div>
            </div>

            <span class="badge rounded-pill text-bg-light px-3 py-2">
                <?= (int)$unreadCount ?> unread
            </span>
        </div>

        <div class="notif-list">
            <?php foreach ($notifications as $n): ?>
                <?php
                    $isUnread = (int)($n['is_read'] ?? 0) === 0;

                    $link = trim((string)($n['link_url'] ?? ''));
                    if ($link === '') {
                        $link = '/elms/student/notifications.php';
                    }

                    $openUrl = '/elms/student/notifications.php?read=' . (int)$n['id'] . '&go=' . urlencode($link);

                    $createdAt = '';
                    if (!empty($n['created_at'])) {
                        $createdAt = date('d M Y, h:i A', strtotime((string)$n['created_at']));
                    }
                ?>

                <div class="notif-row <?= $isUnread ? 'unread' : '' ?>">
                    <div class="notif-icon-v2">
                        <i class="bi <?= h($n['icon'] ?: 'bi-bell') ?>"></i>
                    </div>

                    <div>
                        <div class="notif-title-v2">
                            <?= h($n['title'] ?? 'Notification') ?>
                        </div>

                        <?php if (!empty($n['message'])): ?>
                            <div class="notif-message-v2">
                                <?= h($n['message']) ?>
                            </div>
                        <?php else: ?>
                            <div class="notif-message-v2 text-muted">
                                No message content.
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="notif-time-wrap">
                        <div class="notif-time-label">Date / Time</div>
                        <div class="notif-time-value">
                            <?= h($createdAt ?: '—') ?>
                        </div>
                    </div>

                    <div class="notif-status-wrap">
                        <?php if ($isUnread): ?>
                            <span class="notif-status-pill notif-status-new">New</span>
                        <?php else: ?>
                            <span class="notif-status-pill notif-status-read">Read</span>
                        <?php endif; ?>
                    </div>

                    <div class="notif-open-wrap">
                        <a href="javascript:void(0)"
   class="notif-open-btn"
   title="Open notification"
   onclick="openNotifModal(
       '<?= h(addslashes($n['title'] ?? 'Notification')) ?>',
       '<?= h(addslashes($n['message'] ?? '')) ?>',
       '<?= h($createdAt ?: '—') ?>',
       '<?= h($openUrl) ?>'
   )">
    <i class="bi bi-arrow-right"></i>
</a>
                    </div>
                </div>

            <?php endforeach; ?>
        </div>
    </div>

<?php endif; ?>
<div class="modal fade" id="notifViewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 rounded-4">
            <div class="modal-header">
                <h5 class="modal-title fw-bold text-primary" id="notifModalTitle">Notification</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="text-muted small mb-2" id="notifModalDate"></div>
                <div id="notifModalMessage" style="white-space:pre-line;font-weight:700;color:#263247;"></div>
            </div>
        </div>
    </div>
</div>

<script>
function openNotifModal(title, message, dateText, readUrl) {
    document.getElementById('notifModalTitle').innerText = title || 'Notification';
    document.getElementById('notifModalMessage').innerText = message || 'No message content.';
    document.getElementById('notifModalDate').innerText = dateText || '';

    fetch(readUrl).catch(() => {});

    const modal = new bootstrap.Modal(document.getElementById('notifViewModal'));
    modal.show();
}
</script>
<?php require_once __DIR__ . '/../includes/student_layout_bottom.php'; ?>