<?php
require_once __DIR__ . '/app.php';

function render_layout_start(string $pageTitle): void
{
    $userName = current_user_name();
    $userRole = current_user_role();
    $userId = current_user_id();
    $currentPage = basename($_SERVER['PHP_SELF']);
    $isManagement = is_management_role();
    $isAuditMenuOpen = in_array($currentPage, ['daftar_maklumat_audit.php', 'senarai_maklumat_audit.php', 'senarai_maklum_balas_audit.php'], true);
    $isUserMenuOpen = in_array($currentPage, ['daftar_pengguna.php', 'pengurusan_pendaftaran.php', 'senarai_pengguna.php', 'detail_pengguna.php', 'edit_pengguna.php', 'transaksi_log_pengguna.php', 'profile_pengguna.php', 'capaian_pengguna.php'], true);
    $unreadNotificationCount = get_unread_notification_count($GLOBALS['conn'], $userId);
    $recentNotifications = get_recent_notifications($GLOBALS['conn'], $userId, 8);
    $currentUrl = $_SERVER['REQUEST_URI'] ?? 'dashboard.php';
    ?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="Cache-Control" content="no-store, no-cache, must-revalidate, max-age=0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title><?= htmlspecialchars($pageTitle) ?></title>
    <script>
    (function () {
        const savedMode = localStorage.getItem('audit_theme_mode') || 'light';
        const systemDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
        const activeTheme = savedMode === 'auto' ? (systemDark ? 'dark' : 'light') : savedMode;
        document.documentElement.setAttribute('data-theme', activeTheme);
        document.documentElement.setAttribute('data-theme-mode', savedMode);
    })();
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="stylesheet" href="styles.css?v=<?= urlencode((string) @filemtime(__DIR__ . '/../styles.css')) ?>">
</head>
<body>
<div class="top-header">
    <div class="header-left">
        <button type="button" class="menu-toggle" onclick="toggleSidebar()" aria-label="Buka atau tutup menu">
            <i class="fa-solid fa-bars-staggered"></i>
        </button>
        <div class="logo-section">
            <div class="logo-mark"><img src="mainpp.png" alt="Logo MAINPP"></div>
            <span class="logo-text">Dashboard Audit MAINPP</span>
        </div>
    </div>
    <div class="header-right">
        <div class="notification-wrap">
            <button type="button" class="notification-btn" onclick="toggleNotificationPanel()">
                <i class="fa-solid fa-bell"></i>
                <?php if ($unreadNotificationCount > 0): ?>
                    <span class="notification-badge"><?= $unreadNotificationCount > 99 ? '99+' : $unreadNotificationCount ?></span>
                <?php endif; ?>
            </button>
            <div class="notification-panel" id="notification-panel">
                <div class="notification-panel-head">
                    <span>Notifikasi</span>
                    <?php if ($unreadNotificationCount > 0): ?>
                        <a href="mark_notification_read.php?all=1&redirect=<?= urlencode($currentUrl) ?>" class="notification-read-all" onclick="markHeaderNotificationsRead(event)">Tanda Semua Dibaca</a>
                    <?php endif; ?>
                </div>
                <div class="notification-panel-body" id="notification-panel-body">
                    <?php if (!empty($recentNotifications)): ?>
                        <?php foreach ($recentNotifications as $notification): ?>
                            <div class="notification-item <?= !empty($notification['is_read']) ? 'read' : 'unread' ?>">
                                <span class="notification-title"><?= htmlspecialchars($notification['title']) ?></span>
                                <span class="notification-message"><?= htmlspecialchars($notification['message']) ?></span>
                                <span class="notification-time"><?= htmlspecialchars(date('d/m/Y h:i A', strtotime((string) $notification['created_at']))) ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="notification-empty">Tiada notifikasi buat masa ini.</div>
                    <?php endif; ?>
                </div>
                <div class="notification-panel-foot">
                    <a href="notifications.php" class="notification-view-all">Lihat Semua Notifikasi</a>
                </div>
            </div>
        </div>
        <div class="theme-wrap">
            <button type="button" class="theme-btn" onclick="toggleThemePanel()" aria-label="Pilih theme">
                <i class="fa-solid fa-circle-half-stroke"></i>
                <span id="theme-current-label">Theme</span>
            </button>
            <div class="theme-panel" id="theme-panel">
                <div class="theme-panel-head">Theme Mode</div>
                <button type="button" class="theme-option-btn" data-theme-option="light" onclick="setThemeMode('light')">
                    <i class="fa-solid fa-sun"></i>
                    <span>Light</span>
                </button>
                <button type="button" class="theme-option-btn" data-theme-option="dark" onclick="setThemeMode('dark')">
                    <i class="fa-solid fa-moon"></i>
                    <span>Dark</span>
                </button>
                <button type="button" class="theme-option-btn" data-theme-option="auto" onclick="setThemeMode('auto')">
                    <i class="fa-solid fa-desktop"></i>
                    <span>Auto</span>
                </button>
            </div>
        </div>
        <div class="header-user-info">
            <div class="header-user-name"><?= htmlspecialchars($userName) ?></div>
            <div class="header-user-role"><?= htmlspecialchars($userRole) ?></div>
        </div>
        <a href="#" class="logout-btn" onclick="confirmLogout(); return false;">
            <i class="fa-solid fa-right-from-bracket"></i> Log Keluar
        </a>
    </div>
</div>

<div class="sidebar open" id="sidebar">
    <div class="sidebar-header">
        <div class="sidebar-title">Menu Utama</div>
    </div>
    <div class="sidebar-profile-section">
        <div>
            <span class="sidebar-profile-name"><?= htmlspecialchars($userName) ?></span>
            <span class="sidebar-profile-role"><?= htmlspecialchars($userRole) ?></span>
        </div>
    </div>
    <div class="sidebar-menu">
        <a href="dashboard.php" class="sidebar-item <?= $currentPage === 'dashboard.php' ? 'active' : '' ?>">
            <i class="fa-solid fa-house"></i>
            <span>Dashboard</span>
        </a>

        <div class="sidebar-item sidebar-toggle <?= $isAuditMenuOpen ? 'active' : '' ?>" onclick="toggleSubmenu('audit-submenu', 'audit-toggle-icon')">
            <div class="sidebar-toggle-left">
                <i class="fa-solid fa-folder-open"></i>
                <span>Maklumat Audit</span>
            </div>
            <i id="audit-toggle-icon" class="fa-solid fa-chevron-down toggle-icon <?= $isAuditMenuOpen ? 'rotate' : '' ?>"></i>
        </div>
        <div id="audit-submenu" class="submenu <?= $isAuditMenuOpen ? 'show' : '' ?>">
            <a href="daftar_maklumat_audit.php" class="sidebar-item <?= $currentPage === 'daftar_maklumat_audit.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-file-circle-plus"></i>
                <span>Daftar Maklumat Audit</span>
            </a>
            <a href="senarai_maklum_balas_audit.php" class="sidebar-item <?= $currentPage === 'senarai_maklum_balas_audit.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-comments"></i>
                <span>Senarai Maklum Balas Audit</span>
            </a>
            <a href="senarai_maklumat_audit.php" class="sidebar-item <?= $currentPage === 'senarai_maklumat_audit.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-list-check"></i>
                <span>Senarai Maklumat Audit</span>
            </a>
        </div>

        <div class="sidebar-item sidebar-toggle <?= $isUserMenuOpen ? 'active' : '' ?>" onclick="toggleSubmenu('user-submenu', 'user-toggle-icon')">
            <div class="sidebar-toggle-left">
                <i class="fa-solid fa-users-gear"></i>
                <span>Pengguna</span>
            </div>
            <i id="user-toggle-icon" class="fa-solid fa-chevron-down toggle-icon <?= $isUserMenuOpen ? 'rotate' : '' ?>"></i>
        </div>
        <div id="user-submenu" class="submenu <?= $isUserMenuOpen ? 'show' : '' ?>">
            <a href="daftar_pengguna.php" class="sidebar-item <?= $currentPage === 'daftar_pengguna.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-user-plus"></i>
                <span>Daftar Pengguna</span>
            </a>
            <a href="pengurusan_pendaftaran.php" class="sidebar-item <?= $currentPage === 'pengurusan_pendaftaran.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-user-check"></i>
                <span>Pengurusan Pendaftaran</span>
            </a>
            <a href="senarai_pengguna.php" class="sidebar-item <?= in_array($currentPage, ['senarai_pengguna.php', 'detail_pengguna.php', 'edit_pengguna.php'], true) ? 'active' : '' ?>">
                <i class="fa-solid fa-users"></i>
                <span>Senarai Pengguna</span>
            </a>
            <a href="capaian_pengguna.php" class="sidebar-item <?= $currentPage === 'capaian_pengguna.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-user-lock"></i>
                <span>Capaian Pengguna</span>
            </a>
            <a href="transaksi_log_pengguna.php" class="sidebar-item <?= $currentPage === 'transaksi_log_pengguna.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-clock-rotate-left"></i>
                <span>Transaksi Log Pengguna</span>
            </a>
            <a href="profile_pengguna.php" class="sidebar-item <?= $currentPage === 'profile_pengguna.php' ? 'active' : '' ?>">
                <i class="fa-solid fa-user-gear"></i>
                <span>Profile Pengguna</span>
            </a>
        </div>
    </div>
</div>

<div class="session-modal-backdrop" id="session-warning-backdrop">
    <div class="session-modal">
        <div class="session-modal-head">
            <i class="fa-solid fa-triangle-exclamation"></i>
            <span>Amaran Sesi Tamat</span>
        </div>
        <div class="session-modal-body">
            Sesi anda akan tamat dalam <span id="session-warning-countdown"><?= SESSION_GRACE_SECONDS ?></span> saat. Teruskan sesi?
        </div>
        <div class="session-modal-actions">
            <button type="button" class="secondary-btn" id="session-cancel-btn">Log Keluar</button>
            <button type="button" class="primary-btn" id="session-logout-btn">Teruskan Sesi</button>
        </div>
    </div>
</div>

<div class="main-content shifted" id="main-content">
    <?php
}

function render_layout_end(string $extraJs = ''): void
{
    $userId = current_user_id();
    $recentNotifications = get_recent_notifications($GLOBALS['conn'], $userId, 8);
    ?>
    <div class="footer">
        Hakcipta Terpelihara &copy; <b>2026 Majlis Agama Islam Negeri Pulau Pinang.</b>
    </div>
</div>

<div class="attachment-preview-backdrop" id="attachment-preview-backdrop" onclick="closeAttachmentPreview(event)">
    <div class="attachment-preview-modal" onclick="event.stopPropagation()">
        <div class="attachment-preview-header">
            <div class="attachment-preview-title" id="attachment-preview-title">Lampiran</div>
            <button type="button" class="attachment-preview-close" onclick="closeAttachmentPreview()">X</button>
        </div>
        <div class="attachment-preview-body" id="attachment-preview-body"></div>
    </div>
</div>

<script>
const browserNotifications = <?= json_encode(array_values(array_map(static function ($notification) {
    return [
        'id' => (int) ($notification['id'] ?? 0),
        'title' => (string) ($notification['title'] ?? ''),
        'message' => (string) ($notification['message'] ?? ''),
        'link' => (string) ($notification['link'] ?? ''),
        'is_read' => (int) ($notification['is_read'] ?? 0),
    ];
}, array_filter($recentNotifications, static fn($notification) => empty($notification['is_read'])))), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const currentNotificationUserId = <?= (int) $userId ?>;

function toggleSidebar() {
    document.getElementById('sidebar').classList.toggle('open');
    document.getElementById('main-content').classList.toggle('shifted');
}

function toggleNotificationPanel() {
    document.getElementById('notification-panel').classList.toggle('show');
    const themePanel = document.getElementById('theme-panel');
    if (themePanel) {
        themePanel.classList.remove('show');
    }
}

function toggleThemePanel() {
    const panel = document.getElementById('theme-panel');
    const notificationPanel = document.getElementById('notification-panel');
    if (notificationPanel) {
        notificationPanel.classList.remove('show');
    }
    if (panel) {
        panel.classList.toggle('show');
    }
}

function getActiveTheme(mode) {
    if (mode === 'auto') {
        return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    return mode;
}

function refreshThemeUi(mode) {
    const label = document.getElementById('theme-current-label');
    const labels = { light: 'Light', dark: 'Dark', auto: 'Auto' };
    if (label) {
        label.textContent = labels[mode] || 'Light';
    }
    document.querySelectorAll('.theme-option-btn').forEach((button) => {
        button.classList.toggle('active', button.dataset.themeOption === mode);
    });
}

function applyThemeMode(mode) {
    const safeMode = ['light', 'dark', 'auto'].includes(mode) ? mode : 'light';
    const activeTheme = getActiveTheme(safeMode);
    document.documentElement.setAttribute('data-theme', activeTheme);
    document.documentElement.setAttribute('data-theme-mode', safeMode);
    refreshThemeUi(safeMode);
}

function setThemeMode(mode) {
    localStorage.setItem('audit_theme_mode', mode);
    applyThemeMode(mode);
    const panel = document.getElementById('theme-panel');
    if (panel) {
        panel.classList.remove('show');
    }
}

function openAttachmentPreview(event, url, name) {
    event.preventDefault();

    const backdrop = document.getElementById('attachment-preview-backdrop');
    const title = document.getElementById('attachment-preview-title');
    const body = document.getElementById('attachment-preview-body');
    const safeName = name || 'Lampiran';
    const extension = safeName.split('.').pop().toLowerCase();
    const encodedUrl = encodeURI(url);

    title.textContent = safeName;
    body.innerHTML = '';

    if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(extension)) {
        const image = document.createElement('img');
        image.src = encodedUrl;
        image.alt = safeName;
        body.appendChild(image);
    } else if (extension === 'pdf') {
        const frame = document.createElement('iframe');
        frame.src = encodedUrl;
        frame.title = safeName;
        body.appendChild(frame);
    } else if (['mp4', 'webm', 'ogg'].includes(extension)) {
        const video = document.createElement('video');
        video.src = encodedUrl;
        video.controls = true;
        video.autoplay = true;
        body.appendChild(video);
    } else if (['mp3', 'wav', 'm4a'].includes(extension)) {
        const audio = document.createElement('audio');
        audio.src = encodedUrl;
        audio.controls = true;
        audio.autoplay = true;
        body.appendChild(audio);
    } else {
        body.innerHTML = `
            <div class="attachment-preview-fallback">
                <strong>${safeName}</strong>
                <p>Fail ini tidak boleh dipratonton terus dalam browser. Anda masih boleh muat turun fail ini.</p>
                <a href="${encodedUrl}" download><i class="fa-solid fa-download"></i> Muat Turun Fail</a>
            </div>
        `;
    }

    backdrop.classList.add('show');
}

function closeAttachmentPreview(event) {
    if (event && event.target !== event.currentTarget) {
        return;
    }

    const backdrop = document.getElementById('attachment-preview-backdrop');
    const body = document.getElementById('attachment-preview-body');
    if (body) {
        body.innerHTML = '';
    }
    if (backdrop) {
        backdrop.classList.remove('show');
    }
}

async function markHeaderNotificationsRead(event) {
    event.preventDefault();

    try {
        const response = await fetch('mark_notification_read.php?all=1&ajax=1', {
            method: 'GET',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            credentials: 'same-origin'
        });

        if (!response.ok) {
            window.location.href = event.currentTarget.href;
            return;
        }

        document.querySelectorAll('.notification-badge').forEach((badge) => badge.remove());
        document.querySelectorAll('.notification-read-all').forEach((link) => link.remove());
        document.querySelectorAll('.notification-item.unread').forEach((item) => {
            item.classList.remove('unread');
            item.classList.add('read');
        });

    } catch (error) {
        window.location.href = event.currentTarget.href;
    }
}

function toggleSubmenu(submenuId, iconId) {
    document.getElementById(submenuId).classList.toggle('show');
    document.getElementById(iconId).classList.toggle('rotate');
}

function confirmLogout() {
    if (confirm("Adakah anda pasti mahu log keluar?")) {
        window.location.href = "logout.php";
    }
}

(function () {
    const warningDelayMs = <?= SESSION_WARNING_SECONDS * 1000 ?>;
    const graceMs = <?= SESSION_GRACE_SECONDS * 1000 ?>;
    const sessionStartedAtMs = Date.now();
    let warningTimer = null;
    let countdownTimer = null;
    let logoutTimer = null;
    let modalOpen = false;
    const backdrop = document.getElementById('session-warning-backdrop');
    const countdownEl = document.getElementById('session-warning-countdown');
    const cancelBtn = document.getElementById('session-cancel-btn');
    const logoutBtn = document.getElementById('session-logout-btn');
    let remainingSeconds = <?= SESSION_GRACE_SECONDS ?>;

    function clearTimers() {
        if (warningTimer) clearTimeout(warningTimer);
        if (countdownTimer) clearInterval(countdownTimer);
        if (logoutTimer) clearTimeout(logoutTimer);
    }

    function scheduleWarning() {
        clearTimers();
        const elapsedMs = Date.now() - sessionStartedAtMs;
        const delayMs = Math.max(0, warningDelayMs - elapsedMs);
        warningTimer = setTimeout(openWarningModal, delayMs);
    }

    function openWarningModal() {
        modalOpen = true;
        remainingSeconds = <?= SESSION_GRACE_SECONDS ?>;
        countdownEl.textContent = remainingSeconds;
        backdrop.classList.add('show');

        countdownTimer = setInterval(() => {
            remainingSeconds -= 1;
            countdownEl.textContent = remainingSeconds;
        }, 1000);

        logoutTimer = setTimeout(() => {
            window.location.href = 'logout.php?reason=session_timeout';
        }, graceMs);
    }

    function closeWarningModal() {
        modalOpen = false;
        backdrop.classList.remove('show');
        scheduleWarning();
    }

    async function keepSessionAlive() {
        try {
            const response = await fetch('keepalive.php', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                credentials: 'same-origin'
            });
            const data = await response.json();
            if (!response.ok || !data.success) {
                throw new Error('Session keepalive failed');
            }
            return true;
        } catch (error) {
            window.location.href = 'login.php?error=session_expired';
            return false;
        }
    }

    cancelBtn.addEventListener('click', function () {
        window.location.href = 'logout.php?reason=session_warning';
    });

    logoutBtn.addEventListener('click', async function () {
        clearTimers();
        const extended = await keepSessionAlive();
        if (extended) {
            window.location.reload();
        }
    });

    scheduleWarning();
})();

document.addEventListener('click', function (event) {
    const wrap = document.querySelector('.notification-wrap');
    const panel = document.getElementById('notification-panel');
    if (wrap && panel && !wrap.contains(event.target)) {
        panel.classList.remove('show');
    }

    const themeWrap = document.querySelector('.theme-wrap');
    const themePanel = document.getElementById('theme-panel');
    if (themeWrap && themePanel && !themeWrap.contains(event.target)) {
        themePanel.classList.remove('show');
    }
});

(function initThemeMode() {
    const savedMode = localStorage.getItem('audit_theme_mode') || 'light';
    applyThemeMode(savedMode);

    if (window.matchMedia) {
        const media = window.matchMedia('(prefers-color-scheme: dark)');
        const onSystemThemeChange = function () {
            const mode = localStorage.getItem('audit_theme_mode') || 'light';
            if (mode === 'auto') {
                applyThemeMode('auto');
            }
        };

        if (media.addEventListener) {
            media.addEventListener('change', onSystemThemeChange);
        } else if (media.addListener) {
            media.addListener(onSystemThemeChange);
        }
    }
})();

(function () {
    if (!('Notification' in window) || browserNotifications.length === 0) {
        return;
    }

    const storagePrefix = 'audit_notification_seen_' + currentNotificationUserId + '_';

    function showBrowserNotifications() {
        browserNotifications.forEach((notification) => {
            const storageKey = storagePrefix + notification.id;
            if (localStorage.getItem(storageKey) === '1') {
                return;
            }

            const popup = new Notification(notification.title, {
                body: notification.message,
                icon: 'mainpp.png'
            });

            localStorage.setItem(storageKey, '1');
        });
    }

    if (Notification.permission === 'granted') {
        showBrowserNotifications();
        return;
    }

    if (Notification.permission === 'default') {
        Notification.requestPermission().then((permission) => {
            if (permission === 'granted') {
                showBrowserNotifications();
            }
        });
    }
})();
</script>
<?= $extraJs ?>
</body>
</html>
    <?php
}
