<?php
$user = current_user();
$current = basename($_SERVER['SCRIPT_NAME'] ?? '');
$pageTitle = $pageTitle ?? app_name();
$pageSubtitle = $pageSubtitle ?? 'Interni portal za prijavu i praćenje zahteva';
$authPage = $authPage ?? false;
$bodyClass = $bodyClass ?? ($authPage ? 'auth-view' : 'app-view');

// Logo koristi verziju zasnovanu na vremenu izmene fajla. Time se sprečava
// da pregledač ili CDN nastave da prikazuju stari SVG nakon zamene istog fajla.
$brandLogoRelativePath = 'assets/img/sos-decija-sela-srbija.svg';
$brandLogoAbsolutePath = dirname(__DIR__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $brandLogoRelativePath);
$brandLogoVersion = is_file($brandLogoAbsolutePath) ? (string)filemtime($brandLogoAbsolutePath) : '3.17.1';
$brandLogoUrl = url($brandLogoRelativePath) . '?v=' . rawurlencode($brandLogoVersion);
$activeTicketCount = 0;
$showActiveTicketStat = $user !== null && (is_system_admin($user) || user_has_additional_role($user));
$unreadNotificationCount = 0;
$recentNotifications = [];
$activeTicketView = '';
if ($user && $current === 'tickets.php') {
    $activeTicketView = ticket_list_view($user, $_GET['view'] ?? null);
}
$sessionTimeoutEnabled = (bool)$user;
$sessionTimeoutBodyAttributes = '';
if ($sessionTimeoutEnabled) {
    $sessionTimeoutBodyAttributes = ' data-session-timeout="enabled"'
        . ' data-session-idle-seconds="' . e((string)session_idle_timeout_seconds()) . '"'
        . ' data-session-warning-seconds="' . e((string)session_warning_duration_seconds()) . '"'
        . ' data-session-activity-throttle-seconds="' . e((string)session_activity_throttle_seconds()) . '"'
        . ' data-session-last-activity-at="' . e((string)session_last_user_activity_at()) . '"'
        . ' data-session-started-at="' . e((string)session_started_at()) . '"'
        . ' data-session-csrf="' . e(csrf_token()) . '"'
        . ' data-session-activity-url="' . e(url('session_activity.php')) . '"'
        . ' data-session-extend-url="' . e(url('session_extend.php')) . '"'
        . ' data-session-logout-url="' . e(url('logout.php?csrf=' . rawurlencode(csrf_token()))) . '"'
        . ' data-session-login-url="' . e(url('login.php')) . '"'
        . ' data-session-expired-login-url="' . e(url('login.php?session=expired')) . '"';
}

if (!$authPage && $user) {
    if ($showActiveTicketStat) {
        try {
            [$menuAccessSql, $menuAccessParams] = ticket_access_sql($user);
            $menuCountStmt = db()->prepare("SELECT COUNT(*) FROM tickets t WHERE $menuAccessSql AND t.status IN ('open', 'in_progress', 'waiting')");
            $menuCountStmt->execute($menuAccessParams);
            $activeTicketCount = (int)$menuCountStmt->fetchColumn();
        } catch (Throwable $e) {
            $activeTicketCount = 0;
        }
    }
    $unreadNotificationCount = unread_notification_count((int)$user['id']);
    $recentNotifications = recent_notifications((int)$user['id'], 6);
}
?>
<!doctype html>
<html lang="sr-Latn-RS">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <meta name="robots" content="noindex,nofollow">
    <meta name="theme-color" content="#1c325d">
    <title><?= e($pageTitle) ?></title>
    <link rel="stylesheet" href="<?= e(url('assets/css/style.css')) ?>?v=3.26.0&amp;layout=3.26.0">
    <script src="<?= e(url('assets/js/app.js')) ?>?v=3.25.0" defer></script>
    <?php if ($sessionTimeoutEnabled): ?>
        <?php
        $sessionTimeoutScriptPath = dirname(__DIR__) . '/assets/js/session-timeout.js';
        $sessionTimeoutScriptVersion = is_file($sessionTimeoutScriptPath) ? (string)filemtime($sessionTimeoutScriptPath) : '3.21.1';
        ?>
        <script src="<?= e(url('assets/js/session-timeout.js')) ?>?v=<?= e(rawurlencode($sessionTimeoutScriptVersion)) ?>" defer></script>
    <?php endif; ?>
</head>
<body class="<?= e($bodyClass) ?>"<?= $sessionTimeoutBodyAttributes ?>>
<?php if ($authPage): ?>
    <main class="login-shell">
        <section class="login-hero" aria-label="Informacije o portalu">
            <div class="hero-linije" aria-hidden="true"></div>
            <div class="hero-cestice" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span><span></span></div>
            <div class="hero-brend">
                <div class="brand-mark brand-mark-large">
                    <img class="brand-logo" src="<?= e($brandLogoUrl) ?>" alt="SOS Dečija sela Srbija">
                </div>
                <div class="hero-naziv">
                    <strong>Fondacija SOS Dečija sela Srbija</strong>
                    <span>Interni portal</span>
                </div>
            </div>
            <div class="hero-sadrzaj">
                <span class="login-eyebrow">Interni servisni portal</span>
                <h1>Podrška zaposlenima, jasna evidencija i brža obrada zahteva.</h1>
                <p>Jedno mesto za prijavu, praćenje i administraciju ICT zahteva, održavanja prostora, vozila i ostalih internih potreba.</p>
                <div class="hero-tagovi">
                    <span>ICT podrška</span><span>Održavanje</span><span>Vozila</span><span>Oprema</span>
                </div>
            </div>
            <p class="hero-podnozje">&copy; <span data-godina></span> Fondacija SOS Dečija sela Srbija · Sva prava zadržana.</p>
        </section>
        <section class="login-panel">
            <div class="login-card-wrap">
                <?php foreach (flashes() as $flash): ?>
                    <div class="alert alert-<?= e($flash['type']) ?>" <?= $flash['type'] === 'success' ? 'data-auto-dismiss="25000"' : '' ?>><?= e($flash['message']) ?></div>
                <?php endforeach; ?>
<?php else: ?>
    <noscript><div class="noscript-box"><strong>JavaScript je onemogućen</strong><span>Osnovne funkcije rade, ali mobilni meni i tema zahtevaju JavaScript.</span></div></noscript>
    <div class="sidebar-overlay" id="sidebarOverlay" aria-hidden="true"></div>
    <div class="app-shell">
        <aside class="sidebar" id="primarySidebar" aria-label="Primarna navigacija">
            <div class="sidebar-linije" aria-hidden="true"></div>
            <div class="sidebar-cestice" aria-hidden="true"><span></span><span></span><span></span><span></span><span></span></div>
            <a class="sidebar-brend" href="<?= e(url('dashboard.php')) ?>">
                <div class="brand-mark">
                    <img class="brand-logo" src="<?= e($brandLogoUrl) ?>" alt="SOS Dečija sela Srbija">
                </div>
                <div class="sidebar-brend-tekst">
                    <strong><?= e(app_org()) ?></strong>
                    <span>Interni portal</span>
                </div>
            </a>
            <?php if ($user): ?>
                <nav class="sidebar-nav">
                    <div class="nav-sekcija-naslov">Moj prostor</div>
                    <a class="nav-link <?= e(is_active_page(['dashboard.php'])) ?>" href="<?= e(url('dashboard.php')) ?>" <?= $current === 'dashboard.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">⌂</span><span>Moj panel</span></a>
                    <?php if (can_create_ticket($user)): ?><a class="nav-link <?= e(is_active_page(['ticket_create.php'])) ?>" href="<?= e(url('ticket_create.php')) ?>" <?= $current === 'ticket_create.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">＋</span><span>Novi zahtev</span></a><?php endif; ?>
                    <a class="nav-link <?= $activeTicketView === 'mine' ? 'aktivan' : '' ?>" href="<?= e(url('tickets.php?view=mine')) ?>" <?= $activeTicketView === 'mine' ? 'aria-current="page"' : '' ?>><span class="nav-icon">≡</span><span>Moji tiketi</span></a>
                    <?php if (user_has_additional_role($user)): ?>
                        <a class="nav-link <?= $activeTicketView === 'assigned' ? 'aktivan' : '' ?>" href="<?= e(url('tickets.php?view=assigned')) ?>" <?= $activeTicketView === 'assigned' ? 'aria-current="page"' : '' ?>><span class="nav-icon">⇥</span><span>Tiketi za koje sam zadužen</span></a>
                    <?php endif; ?>
                    <?php if (is_system_admin($user)): ?>
                        <a class="nav-link <?= $activeTicketView === 'all' ? 'aktivan' : '' ?>" href="<?= e(url('tickets.php?view=all')) ?>" <?= $activeTicketView === 'all' ? 'aria-current="page"' : '' ?>><span class="nav-icon">☷</span><span>Svi zahtevi</span></a>
                    <?php endif; ?>
                    <a class="nav-link <?= e(is_active_page(['notifications.php'])) ?>" href="<?= e(url('notifications.php')) ?>" <?= $current === 'notifications.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">🔔</span><span>Obaveštenja</span></a>
                    <a class="nav-link <?= e(is_active_page(['account.php'])) ?>" href="<?= e(url('account.php')) ?>" <?= $current === 'account.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">⚙</span><span>Podaci o nalogu</span></a>
                    <?php if (is_system_admin($user) || can_manage_equipment($user)): ?>
                        <div class="nav-sekcija-naslov">Administracija</div>
                        <?php if (is_system_admin($user)): ?>
                        <a class="nav-link <?= e(is_active_page(['users.php'])) ?>" href="<?= e(url('users.php')) ?>" <?= $current === 'users.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">◎</span><span>Korisnici</span></a>
                        <?php endif; ?>
                        <a class="nav-link <?= e(is_active_page(['equipment.php'])) ?>" href="<?= e(url('equipment.php')) ?>" <?= $current === 'equipment.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">▣</span><span>Oprema</span></a>
                        <?php if (is_system_admin($user)): ?>
                        <a class="nav-link <?= e(is_active_page(['ticket_settings.php'])) ?>" href="<?= e(url('ticket_settings.php')) ?>" <?= $current === 'ticket_settings.php' ? 'aria-current="page"' : '' ?>><span class="nav-icon">⚙</span><span>Podešavanje zahteva</span></a>
                        <?php endif; ?>
                    <?php endif; ?>
                </nav>
            <?php endif; ?>
            <?php if ($user): ?>
                <div class="sidebar-user-card">
                    <?= user_avatar_html($user, 'avatar') ?>
                    <div>
                        <strong><?= e($user['name']) ?></strong>
                        <small><?= e(user_roles_compact_summary($user)) ?></small>
                    </div>
                </div>
            <?php endif; ?>
            <div class="sidebar-podnozje">&copy; <span data-godina></span> <?= e(app_org()) ?></div>
        </aside>
        <main class="sadrzaj">
            <header class="topbar">
                <button type="button" class="mob-toggle" id="mobileMenu" aria-controls="primarySidebar" aria-expanded="false" aria-label="Otvori navigaciju">☰</button>
                <div class="topbar-naslov">
                    <?= e($pageTitle) ?>
                    <small><?= e($pageSubtitle) ?></small>
                </div>
                <div class="topbar-akcije">
                    <button type="button" class="icon-button" id="themeToggle" aria-label="Promeni temu" title="Promeni temu">☾</button>
                    <?php if ($user): ?>
                        <div class="notif-menu">
                            <button type="button" class="icon-button notif-button" id="notifButton" aria-haspopup="true" aria-expanded="false" aria-controls="notifDropdown" aria-label="Obaveštenja" title="Obaveštenja">
                                <span aria-hidden="true">🔔</span>
                                <?php if ($unreadNotificationCount > 0): ?><span class="notif-bedz"><?= (int)$unreadNotificationCount ?></span><?php endif; ?>
                            </button>
                            <div class="notif-dropdown" id="notifDropdown" role="menu" aria-labelledby="notifButton">
                                <div class="notif-dropdown-head">
                                    <strong>Obaveštenja</strong>
                                    <span><?= (int)$unreadNotificationCount ?> nepročitano</span>
                                </div>
                                <?php if (!$recentNotifications): ?>
                                    <p class="notif-empty">Trenutno nema obaveštenja.</p>
                                <?php else: ?>
                                    <div class="notif-list">
                                        <?php foreach ($recentNotifications as $notification): ?>
                                            <a class="notif-item <?= (int)$notification['is_read'] === 0 ? 'neprocitano' : '' ?>" href="<?= e(url('notifications.php?open=' . (int)$notification['id'] . '&csrf=' . rawurlencode(csrf_token()))) ?>" role="menuitem">
                                                <strong><?= e($notification['title']) ?></strong>
                                                <span><?= e(limit_text($notification['message'], 90)) ?></span>
                                                <small><?= e(format_datetime($notification['created_at'])) ?></small>
                                            </a>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                <div class="notif-footer">
                                    <a href="<?= e(url('notifications.php')) ?>">Prikaži sva</a>
                                    <?php if ($unreadNotificationCount > 0): ?>
                                        <form method="post" action="<?= e(url('notifications.php')) ?>">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="action" value="mark_all">
                                            <button type="submit">Označi kao pročitano</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <div class="topbar-user-menu">
                            <button type="button" class="korisnik-chip" id="userMenuButton" aria-haspopup="true" aria-expanded="false" aria-controls="userDropdown" title="<?= e($user['email']) ?>">
                                <?= user_avatar_html($user, 'avatar') ?>
                                <span class="korisnik-ime"><?= e($user['name']) ?><small><?= e(user_roles_compact_summary($user)) ?></small></span>
                                <span class="user-menu-chevron" aria-hidden="true">⌄</span>
                            </button>
                            <div class="user-dropdown" id="userDropdown" role="menu" aria-labelledby="userMenuButton">
                                <div class="user-dropdown-header">
                                    <?= user_avatar_html($user, 'avatar avatar-lg') ?>
                                    <div>
                                        <strong><?= e($user['name']) ?></strong>
                                        <span><?= e(user_menu_badge_label($user)) ?></span>
                                        <small><?= e($user['email']) ?></small>
                                    </div>
                                </div>
                                <?php if ($showActiveTicketStat): ?>
                                    <div class="user-menu-stat">
                                        <span>Aktivni zahtevi</span>
                                        <strong><?= (int)$activeTicketCount ?></strong>
                                    </div>
                                <?php endif; ?>
                                <nav class="user-menu-links" aria-label="Korisnički meni">
                                    <a role="menuitem" href="<?= e(url('dashboard.php')) ?>"><span>⌂</span> Moj panel</a>
                                    <?php if (can_create_ticket($user)): ?><a role="menuitem" href="<?= e(url('ticket_create.php')) ?>"><span>＋</span> Novi zahtev</a><?php endif; ?>
                                    <a role="menuitem" href="<?= e(url('tickets.php?view=mine')) ?>"><span>≡</span> Moji tiketi</a>
                                    <?php if (user_has_additional_role($user)): ?><a role="menuitem" href="<?= e(url('tickets.php?view=assigned')) ?>"><span>⇥</span> Tiketi za koje sam zadužen</a><?php endif; ?>
                                    <?php if (is_system_admin($user)): ?><a role="menuitem" href="<?= e(url('tickets.php?view=all')) ?>"><span>☷</span> Svi zahtevi</a><?php endif; ?>
                                    <a role="menuitem" href="<?= e(url('notifications.php')) ?>"><span>🔔</span> Obaveštenja</a>
                                    <a role="menuitem" href="<?= e(url('account.php')) ?>"><span>⚙</span> Podaci o nalogu</a>
                                    <?php if (is_system_admin($user)): ?>
                                        <a role="menuitem" href="<?= e(url('users.php')) ?>"><span>◎</span> Administracija korisnika</a>
                                    <?php endif; ?>
                                    <?php if (can_manage_equipment($user)): ?>
                                        <a role="menuitem" href="<?= e(url('equipment.php')) ?>"><span>▣</span> Oprema zaposlenih</a>
                                    <?php endif; ?>
                                    <?php if (is_system_admin($user)): ?>
                                        <a role="menuitem" href="<?= e(url('ticket_settings.php')) ?>"><span>⚙</span> Podešavanje zahteva</a>
                                    <?php endif; ?>
                                </nav>
                                <div class="user-dropdown-footer">
                                    <a class="button button-light" href="<?= e(url('logout.php?csrf=' . rawurlencode(csrf_token()))) ?>">Odjava</a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </header>
            <section class="stranica">
                <?php foreach (flashes() as $flash): ?>
                    <div class="alert alert-<?= e($flash['type']) ?>" <?= $flash['type'] === 'success' ? 'data-auto-dismiss="25000"' : '' ?>><?= e($flash['message']) ?></div>
                <?php endforeach; ?>
<?php endif; ?>
