<?php
// Filename: links.php
require 'config.php';

// ---- Safe guards ----
if (!function_exists('requireLogin')) {
    function requireLogin(): void {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        if (empty($_SESSION['user_id'])) { header('Location: login.php'); exit; }
    }
}
if (!function_exists('getSetting')) { function getSetting(string $key, $default = '') { return $default; } }
if (!function_exists('getHeaderTheme')) { function getHeaderTheme(): string { return 'linear-gradient(135deg, #3b82f6, #06b6d4)'; } }

requireLogin();
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$s_name = (string) getSetting('school_name', 'SAS');
$full_name = (string) ($_SESSION['full_name'] ?? 'User');

// --- DETERMINE ROLES ---
$roleRaw = $_SESSION['role'] ?? 'teacher';
if (is_array($roleRaw)) {
    $user_roles = array_values(array_filter(array_map('trim', $roleRaw)));
} else {
    $user_roles = array_filter(array_map('trim', explode(',', (string)$roleRaw)));
}
if (empty($user_roles)) $user_roles = ['teacher'];

// --- FETCH LINKS FROM DB ---
// We fetch ALL links, then filter by PHP for role security and grouping
try {
    $stmt = $pdo->query("SELECT * FROM important_links ORDER BY sort_order ASC, title ASC");
    $dbLinks = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $dbLinks = [];
}

// Transform DB data to match your previous array structure for compatibility
$links = [];
foreach ($dbLinks as $row) {
    // Parse target_roles string "admin,teacher" into array ['admin','teacher']
    $rolesArr = ($row['target_roles'] === '*') ? ['*'] : explode(',', $row['target_roles']);
    
    $links[] = [
        'id'    => (string)$row['id'], // Use DB ID for favorites logic
        'cat'   => $row['category'],
        'title' => $row['title'],
        'desc'  => $row['description'],
        'url'   => $row['url'],
        'icon'  => $row['icon'],
        'color' => $row['color'],
        'roles' => $rolesArr
    ];
}

// Basic URL sanitizer
function safeUrl(string $url): string {
    $url = trim($url);
    if ($url === '') return '#';
    if (!preg_match('~^https?://~i', $url)) return '#';
    return $url;
}

// Helper: role match
function linkAllowed(array $link, array $user_roles): bool {
    $allowed = $link['roles'] ?? ['*'];
    if (!is_array($allowed)) $allowed = ['*'];
    if (in_array('*', $allowed, true)) return true;
    foreach ($user_roles as $r) {
        if (in_array($r, $allowed, true)) return true;
    }
    return false;
}

// Filter links by role
$visibleLinks = array_values(array_filter($links, fn($l) => linkAllowed($l, $user_roles)));

// Group by category
$groups = [];
foreach ($visibleLinks as $l) {
    $cat = $l['cat'] ?? 'Others';
    if (!isset($groups[$cat])) $groups[$cat] = [];
    $groups[$cat][] = $l;
}

// Preferred category order (You can modify this list or make it dynamic later)
$catOrder = [
    'Favorites',
    'KPM SSO (Core)',
    'Teaching & Learning',
    'HR & Service',
    'Teacher Records',
    'Career & Movement',
    'School Administration',
    'Others'
];

// Sort categories
uksort($groups, function($a, $b) use ($catOrder) {
    $ia = array_search($a, $catOrder, true); if ($ia === false) $ia = 999;
    $ib = array_search($b, $catOrder, true); if ($ib === false) $ib = 999;
    return $ia <=> $ib;
});
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Important Links - <?= htmlspecialchars($s_name, ENT_QUOTES, 'UTF-8') ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; --text-dark: #1e293b; --text-gray: #64748b; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        .app-header { background: var(--primary-grad); padding: 20px 20px 110px 20px; border-radius: 0 0 35px 35px; color: white; position: relative; text-align: center; }
        .content-sheet { margin-top: -70px; padding: 0 20px; }
        .search-wrap{ position: sticky; top: 10px; z-index: 10; margin-bottom: 14px; }
        .search-box{ background: rgba(255,255,255,0.95); border: 1px solid #e2e8f0; border-radius: 16px; box-shadow: 0 6px 20px rgba(0,0,0,0.06); padding: 10px 12px; display:flex; gap:10px; align-items:center; backdrop-filter: blur(8px); }
        .search-box input{ border: none; outline: none; width: 100%; font-size: 0.95rem; background: transparent; }
        .section-title{ display:flex; align-items:center; justify-content:space-between; margin: 14px 4px 10px 4px; color: var(--text-dark); }
        .section-title h6{ margin:0; font-weight:800; font-size:0.95rem; }
        .section-title .small{ color: var(--text-gray); }
        .link-card { background: white; border-radius: 20px; padding: 15px; margin-bottom: 12px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 4px 15px rgba(0,0,0,0.03); transition: transform 0.2s, box-shadow 0.2s; text-decoration: none; color: inherit; border: 1px solid transparent; }
        .link-card:active { transform: scale(0.98); background: #f8fafc; }
        .link-card:hover { box-shadow: 0 8px 25px rgba(0,0,0,0.08); border-color: #e2e8f0; }
        .icon-box { width: 50px; height: 50px; border-radius: 14px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; flex-shrink: 0; margin-right: 15px; color: white; }
        .text-content h6 { margin: 0; font-weight: 800; color: var(--text-dark); }
        .text-content p { margin: 0; font-size: 0.8rem; color: var(--text-gray); }
        .right-actions{ display:flex; align-items:center; gap:10px; }
        .fav-btn{ width: 34px; height: 34px; border-radius: 12px; border: 1px solid #e2e8f0; background: #fff; display:flex; align-items:center; justify-content:center; color:#94a3b8; transition:0.2s; }
        .fav-btn.active{ color:#f59e0b; border-color:#fde68a; background:#fffbeb; }
        .arrow-icon { color: #cbd5e1; font-size: 1.2rem; }
        .hidden { display:none !important; }
        .section.kpm-sso { padding-top: 18px; }
        .section.kpm-sso .section-title { margin-top: 10px; }
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <a href="dashboard.php" class="text-white" aria-label="Back"><i class="bi bi-arrow-left fs-3"></i></a>
            <h5 class="fw-bold mb-0">MOE Portal</h5>
            <div style="width: 24px;"></div>
        </div>
        <p class="opacity-75 small mb-0">Quick access to essential MOE systems</p>
    </div>

    <div class="content-sheet">
        <div class="search-wrap">
            <div class="search-box">
                <i class="bi bi-search text-secondary"></i>
                <input id="searchInput" type="text" placeholder="Search links (e.g., idMe, HRMIS)..." autocomplete="off">
                <button id="clearBtn" class="btn btn-sm btn-light border" type="button" style="border-radius:12px;">Clear</button>
            </div>
        </div>

        <div id="favSection" class="hidden">
            <div class="section-title">
                <h6><i class="bi bi-star-fill me-2 text-warning"></i>Favorites</h6>
                <span class="small">Pinned</span>
            </div>
            <div id="favList"></div>
        </div>

        <?php foreach($groups as $cat => $items): ?>
          <div class="section <?= ($cat === 'KPM SSO (Core)') ? 'kpm-sso' : '' ?>" data-section="<?= htmlspecialchars($cat, ENT_QUOTES, 'UTF-8') ?>">
                <div class="section-title">
                    <h6><?= htmlspecialchars($cat, ENT_QUOTES, 'UTF-8') ?></h6>
                    <span class="small"><?= count($items) ?> link(s)</span>
                </div>
                <?php foreach($items as $link):
                    $url = safeUrl((string)($link['url'] ?? ''));
                    // Use DB ID if available, else fallback logic
                    $id = (string)($link['id'] ?? md5($url));
                ?>
                    <a href="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener noreferrer" class="link-card animate__animated animate__fadeInUp link-item"
                       data-id="<?= htmlspecialchars($id, ENT_QUOTES, 'UTF-8') ?>"
                       data-title="<?= htmlspecialchars((string)$link['title'], ENT_QUOTES, 'UTF-8') ?>"
                       data-desc="<?= htmlspecialchars((string)$link['desc'], ENT_QUOTES, 'UTF-8') ?>"
                       data-cat="<?= htmlspecialchars((string)$cat, ENT_QUOTES, 'UTF-8') ?>"
                       data-url="<?= htmlspecialchars($url, ENT_QUOTES, 'UTF-8') ?>"
                       data-icon="<?= htmlspecialchars((string)$link['icon'], ENT_QUOTES, 'UTF-8') ?>"
                       data-color="<?= htmlspecialchars((string)$link['color'], ENT_QUOTES, 'UTF-8') ?>">
                        <div class="d-flex align-items-center">
                            <div class="icon-box shadow-sm" style="background-color: <?= htmlspecialchars((string)$link['color'], ENT_QUOTES, 'UTF-8') ?>;">
                                <i class="bi <?= htmlspecialchars((string)$link['icon'], ENT_QUOTES, 'UTF-8') ?>"></i>
                            </div>
                            <div class="text-content">
                                <h6><?= htmlspecialchars((string)$link['title'], ENT_QUOTES, 'UTF-8') ?></h6>
                                <p><?= htmlspecialchars((string)$link['desc'], ENT_QUOTES, 'UTF-8') ?></p>
                            </div>
                        </div>
                        <div class="right-actions">
                            <button class="fav-btn" type="button" aria-label="Pin to favorites"><i class="bi bi-star-fill"></i></button>
                            <div class="arrow-icon"><i class="bi bi-box-arrow-up-right"></i></div>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php endforeach; ?>
    </div>

    <?php if (file_exists(__DIR__ . '/menu.php')) include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

    <script>
    (function(){
        const LS_KEY = 'sas_links_favorites_v1';
        const q = (sel, root=document) => root.querySelector(sel);
        const qa = (sel, root=document) => Array.from(root.querySelectorAll(sel));
        const searchInput = q('#searchInput');
        const clearBtn = q('#clearBtn');
        const favSection = q('#favSection');
        const favList = q('#favList');
        const cards = qa('.link-item');

        function loadFavs(){ try { return JSON.parse(localStorage.getItem(LS_KEY)) || []; } catch(e){ return []; } }
        function saveFavs(arr){ try { localStorage.setItem(LS_KEY, JSON.stringify(arr)); } catch(e){} }
        function setFavBtnState(card, isFav){ const btn = card.querySelector('.fav-btn'); if(btn) btn.classList.toggle('active', !!isFav); }

        function buildFavCardFromData(d){
            const a = document.createElement('a');
            a.href = d.url || '#'; a.target = '_blank'; a.rel = 'noopener noreferrer';
            a.className = 'link-card animate__animated animate__fadeInUp link-item';
            Object.keys(d).forEach(k => a.dataset[k] = d[k]);
            a.innerHTML = `<div class="d-flex align-items-center"><div class="icon-box shadow-sm" style="background-color:${d.color}"><i class="bi ${d.icon}"></i></div><div class="text-content"><h6>${d.title}</h6><p>${d.desc}</p></div></div><div class="right-actions"><button class="fav-btn active" type="button"><i class="bi bi-star-fill"></i></button><div class="arrow-icon"><i class="bi bi-box-arrow-up-right"></i></div></div>`;
            a.querySelector('.fav-btn').addEventListener('click', (ev) => { ev.preventDefault(); ev.stopPropagation(); toggleFav(d.id); });
            return a;
        }

        function renderFavorites(){
            const favs = loadFavs();
            favList.innerHTML = '';
            if(!favs.length){ favSection.classList.add('hidden'); return; }
            favSection.classList.remove('hidden');
            favs.forEach(id => {
                const card = cards.find(c => c.dataset.id === id);
                if(card) favList.appendChild(buildFavCardFromData(Object.assign({}, card.dataset)));
            });
        }

        function toggleFav(id){
            const favs = loadFavs();
            const idx = favs.indexOf(id);
            if(idx >= 0) favs.splice(idx, 1); else favs.unshift(id);
            saveFavs(favs);
            cards.forEach(card => { if(card.dataset.id === id) setFavBtnState(card, favs.includes(id)); });
            renderFavorites();
            applySearch(searchInput.value || '');
        }

        function applySearch(term){
            term = (term || '').trim().toLowerCase();
            const sections = qa('.section');
            const match = (c) => !term || (c.dataset.title+c.dataset.desc+c.dataset.cat).toLowerCase().includes(term);
            qa('#favList .link-item').forEach(c => c.classList.toggle('hidden', !match(c)));
            cards.forEach(c => c.classList.toggle('hidden', !match(c)));
            sections.forEach(s => s.classList.toggle('hidden', !qa('.link-item', s).some(c => !c.classList.contains('hidden'))));
            if(!favSection.classList.contains('hidden')) favSection.classList.toggle('hidden', !qa('#favList .link-item').some(c => !c.classList.contains('hidden')));
        }

        cards.forEach(card => {
            const btn = card.querySelector('.fav-btn');
            if(btn) btn.addEventListener('click', (ev) => { ev.preventDefault(); ev.stopPropagation(); toggleFav(card.dataset.id); });
        });

        const favs = loadFavs();
        cards.forEach(card => setFavBtnState(card, favs.includes(card.dataset.id)));
        renderFavorites();

        searchInput.addEventListener('input', () => applySearch(searchInput.value));
        clearBtn.addEventListener('click', () => { searchInput.value = ''; applySearch(''); searchInput.focus(); });
        applySearch('');
    })();
    </script>
</body>
</html>