<?php
/**
 * Common HTML header and navigation bar.
 * Expects: $activeTheme, $currentUser, $auth, $i18n, $settings, $moduleRegistry
 */

// Intelephense type hints for injected include-scope variables
/** @var I18n          $i18n           */
/** @var Settings      $settings       */
/** @var Module        $moduleRegistry */
/** @var array|null    $currentUser    */
/** @var string        $activeTheme    */

$lang     = $i18n->getLanguage();
$isAdmin  = $currentUser && in_array(ROLE_APP_ADMIN, $currentUser['roles'] ?? [], true);

$appTitle   = $settings->get('app_title', t('app.title'));
$appLogo    = $settings->get('app_logo', '');
$appFavicon = $settings->get('app_favicon', '');

/*
 * Le titre de l'onglet reprend le nom de l'application en suffixe. Une page
 * peut s'en dispenser en posant `$pageTitleNoApp = true` avant l'include :
 * le nom de l'installation figure deja en pied de page, et certaines pages —
 * les rapports du module de demonstration, exposes publiquement — n'ont pas a
 * le republier dans le titre de la fenetre.
 */
$pageTitle = isset($pageTitle)
    ? $pageTitle . (empty($pageTitleNoApp) ? ' — ' . htmlspecialchars($appTitle) : '')
    : htmlspecialchars($appTitle);

// Favicon MIME type map
$faviconMime = match(strtolower(pathinfo($appFavicon, PATHINFO_EXTENSION))) {
    'ico'  => 'image/x-icon',
    'svg'  => 'image/svg+xml',
    'webp' => 'image/webp',
    'jpg', 'jpeg' => 'image/jpeg',
    default => 'image/png',
};
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($lang) ?>" data-theme="<?= htmlspecialchars($activeTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $pageTitle ?></title>

    <?php if ($appFavicon): ?>
    <link rel="icon" type="<?= $faviconMime ?>" href="<?= htmlspecialchars($appFavicon) ?>">
    <?php endif; ?>

    <link rel="stylesheet" href="<?= htmlspecialchars($settings->get('cdn_font_awesome_css', '')) ?>" crossorigin="anonymous" referrerpolicy="no-referrer">
    <link rel="stylesheet" href="/assets/css/main.css?v=13">
    <link rel="stylesheet" href="/assets/css/themes/<?= htmlspecialchars($activeTheme) ?>.css" id="theme-css">

    <?php
    /* ── Thème custom : injection des couleurs + fontes depuis settings ──
       Les valeurs vivent dans la table settings (theme_custom_*). On émet :
       - <link> ou @font-face si fonte non-system (curated / uploaded)
       - <style> qui override les vars CSS du selector [data-theme="custom"] */
    if ($activeTheme === THEME_CUSTOM):
        $_themeSans = Themes::resolveFont(
            (string)$settings->get('theme_custom_font_sans', 'system'), 'sans'
        ) ?? Themes::resolveFont('system', 'sans');
        $_themeMono = Themes::resolveFont(
            (string)$settings->get('theme_custom_font_mono', 'system'), 'mono'
        ) ?? Themes::resolveFont('system', 'mono');

        // <link> Google Fonts si curated
        foreach ([$_themeSans, $_themeMono] as $_f):
            if (!empty($_f['css_url'])): ?>
    <link rel="stylesheet" href="<?= htmlspecialchars($_f['css_url']) ?>">
        <?php endif;
        endforeach;

        // @font-face pour les uploads + override des vars CSS
        $_customCss = '';
        if (!empty($_themeSans['font_face_src'])) $_customCss .= $_themeSans['font_face_src'] . "\n";
        if (!empty($_themeMono['font_face_src'])) $_customCss .= $_themeMono['font_face_src'] . "\n";
        $_customCss .= '[data-theme="custom"] {';
        foreach (Themes::COLOR_KEYS as $_k) {
            $_v = (string)$settings->get('theme_custom_color_' . $_k, '');
            if ($_v === '') continue;
            $_cssVar = '--color-' . str_replace('_', '-', $_k);
            $_customCss .= $_cssVar . ':' . $_v . ';';
        }
        $_customCss .= '--font-sans:' . $_themeSans['stack'] . ';';
        $_customCss .= '--font-mono:' . $_themeMono['stack'] . ';';
        $_customCss .= '}';
        ?>
    <style id="theme-custom-vars"><?= $_customCss ?></style>
    <?php endif; ?>
</head>
<?php
/* Oracle : une base est-elle selectionnee ? Pilote le menu lateral des rapports. */
$_hNav   = Session::get('oracle_selected_db');
$_oraNav = ($_hNav && function_exists('oracle_url'));
$_hSec   = $_oraNav ? ($_GET['report_section'] ?? '') : '';
$_hSub   = $_oraNav ? ($_GET['report_sub']     ?? '') : '';

/* PostgreSQL : meme principe — rail d'icones + indicateur de base dans la
   barre de taches. La section courante pilote l'etat actif du menu. */
$_pgNav  = Session::get('postgresql_selected_db');
$_pgOn   = ($_pgNav && function_exists('pg_url')
            && str_contains($_SERVER['SCRIPT_NAME'] ?? '', '/modules/postgresql/report.php'));
$_pgSec  = $_pgOn ? ($_GET['section'] ?? 'config') : '';
/* Groupes du rail : icone => sections (les sous-menus sont sans icone). */
$_pgMenu = [
    'config'   => ['icon' => '⚙', 'label' => 'postgresql.menu_config_group',
                   'items' => ['config'      => 'postgresql.report_config_tab',
                               'extensions'  => 'postgresql.report_ext_tab',
                               'performance' => 'postgresql.report_perf_tab']],
    'realtime' => ['icon' => '⚡', 'label' => 'postgresql.menu_realtime_group',
                   'items' => ['realtime' => 'postgresql.report_realtime_tab',
                               'sessions' => 'postgresql.report_sessions_tab']],
    /* Les deux rapports adossés à l'échantillonnage : l'ASH pour décortiquer
       les dernières heures, la Charge pour la tendance sur plusieurs jours. */
    'history'  => ['icon' => '📅', 'label' => 'postgresql.menu_history_group',
                   'items' => ['ash'     => 'postgresql.report_ash_tab',
                               'history' => 'postgresql.report_history_tab']],
];
?>
<body class="theme-<?= htmlspecialchars($activeTheme) ?><?= $_oraNav ? ' has-oracle-sidebar' : '' ?><?= $_pgOn ? ' has-pg-sidebar' : '' ?>">

<header class="site-header">
    <div class="container">
        <a class="site-title" href="/">
            <?php if ($appLogo): ?>
            <img src="<?= htmlspecialchars($appLogo) ?>"
                 alt="<?= htmlspecialchars($appTitle) ?>"
                 class="site-logo">
            <?php else: ?>
            <?= htmlspecialchars($appTitle) ?>
            <?php endif; ?>
        </a>

        <nav class="main-nav" aria-label="Main navigation">

            <!-- Left: liste des modules (classique) + indicateur base Oracle + toggle du menu lateral -->
            <div class="nav-left">
                <?php if ($_oraNav): ?>
                <button type="button" class="oracle-sidebar-toggle" id="oracle-sidebar-toggle"
                        title="<?= t('oracle.nav_reports') ?>" aria-label="<?= t('oracle.nav_reports') ?>">☰</button>
                <span class="oracle-nav-label">
                    🗄 <strong><?= htmlspecialchars($_hNav['name']) ?></strong>
                    <?php if (($_hNav['right'] ?? '') === 'dba'): ?>
                    <span class="badge badge-danger" style="font-size:.7em">DBA</span>
                    <?php else: ?>
                    <span class="badge badge-info" style="font-size:.7em"><?= t('oracle.right_consultation') ?></span>
                    <?php endif; ?>
                </span>
                <span class="oracle-nav-sep"></span>
                <?php endif; ?>
                <?php if ($_pgOn): ?>
                <button type="button" class="pg-sidebar-toggle" id="pg-sidebar-toggle"
                        title="<?= t('postgresql.nav_toggle') ?>" aria-label="<?= t('postgresql.nav_toggle') ?>">☰</button>
                <span class="pg-nav-label">
                    🗄 <strong><?= htmlspecialchars($_pgNav['name']) ?></strong>
                    <?php $_pgRight = $_pgNav['right'] ?? 'consultation'; ?>
                    <?php if ($_pgRight === 'dba'): ?>
                    <span class="badge badge-danger" style="font-size:.7em">DBA</span>
                    <?php else: ?>
                    <span class="badge badge-info" style="font-size:.7em"><?= t('postgresql.right_' . $_pgRight) ?></span>
                    <?php endif; ?>
                </span>
                <span class="pg-nav-sep"></span>
                <?php endif; ?>
                <?php foreach ($moduleRegistry->getNavLinks($currentUser) as $navLink): ?>
                <a href="<?= htmlspecialchars($navLink['url']) ?>"
                   title="<?= htmlspecialchars($navLink['label']) ?>"
                   class="nav-link <?= str_starts_with($_SERVER['REQUEST_URI'], parse_url($navLink['url'], PHP_URL_PATH)) ? 'active' : '' ?>">
                    <?php if (!empty($navLink['icon_img'])): ?>
                    <img src="<?= htmlspecialchars($navLink['icon_img']) ?>" class="nav-icon-img" alt="">
                    <?php elseif (!empty($navLink['icon_fa'])): ?>
                    <i class="fa-solid <?= htmlspecialchars($navLink['icon_fa']) ?>"></i>
                    <?php else: ?>
                    <span class="nav-emoji"><?= htmlspecialchars($navLink['icon']) ?></span>
                    <?php endif; ?>
                    <span class="nav-label"><?= htmlspecialchars($navLink['label']) ?></span>
                </a>
                <?php endforeach; ?>
            </div>

            <!-- Right: administration, profile, logout -->
            <div class="nav-right">
                <?php if ($isAdmin): ?>
                <a href="/admin/index.php"
                   class="nav-link <?= str_starts_with($_SERVER['REQUEST_URI'], '/admin/') ? 'active' : '' ?>"
                   title="<?= t('nav.admin') ?>">
                    <i class="fa-solid fa-screwdriver-wrench"></i>
                </a>
                <?php endif; ?>

                <?php if ($currentUser): ?>
                <a href="/doc"
                   class="nav-link <?= str_starts_with($_SERVER['REQUEST_URI'], '/doc') ? 'active' : '' ?>"
                   title="<?= t('nav.doc') ?>">
                    <i class="fa-solid fa-book"></i>
                </a>
                <a href="/profile.php"
                   class="nav-link <?= basename($_SERVER['PHP_SELF']) === 'profile.php' ? 'active' : '' ?>"
                   title="<?= t('nav.profile') ?>">
                    <i class="fa-solid fa-circle-user"></i>
                </a>
                <a href="/about.php" class="nav-link <?= basename($_SERVER['PHP_SELF']) === 'about.php' ? 'active' : '' ?>"
                   title="<?= t('nav.about') ?>">
                    <i class="fa-solid fa-circle-info"></i>
                </a>
                <a href="/logout.php" class="nav-link" title="<?= t('nav.logout') ?>">
                    <i class="fa-solid fa-right-from-bracket"></i>
                </a>
                <?php else: ?>
                <a href="/login.php"
                   class="nav-link <?= basename($_SERVER['PHP_SELF']) === 'login.php' ? 'active' : '' ?>"
                   title="<?= t('nav.login') ?>">
                    <i class="fa-solid fa-right-to-bracket"></i>
                </a>
                <?php endif; ?>
            </div>

        </nav>

        <div class="nav-tools">
            <!-- Language switcher -->
            <div class="dropdown">
                <button class="btn-tool" aria-label="<?= t('lang.label') ?>" aria-haspopup="true">
                    🌐 <?= strtoupper($lang) ?> ▾
                </button>
                <ul class="dropdown-menu">
                    <?php foreach (LANGUAGES as $code): ?>
                    <li>
                        <a href="?lang=<?= $code ?>"
                           class="<?= $code === $lang ? 'active' : '' ?>">
                            <?= t("lang.$code") ?>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <!-- Theme switcher -->
            <div class="dropdown">
                <button class="btn-tool" aria-label="<?= t('theme.label') ?>" aria-haspopup="true">
                    🎨 ▾
                </button>
                <ul class="dropdown-menu">
                    <?php foreach (THEMES as $themeKey): ?>
                    <li>
                        <a href="?theme=<?= $themeKey ?>"
                           class="<?= $themeKey === $activeTheme ? 'active' : '' ?>">
                            <?= t("theme.$themeKey") ?>
                        </a>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
    </div>
</header>

<?php if ($_oraNav): ?>
<!-- Menu lateral des rapports Oracle (collapsable) -->
<aside class="oracle-sidebar" id="oracle-sidebar" aria-label="<?= t('oracle.nav_reports') ?>">
    <nav class="oracle-sidebar-nav">
        <div class="oracle-dropdown" id="oci-menu-config">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'config' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-config', event)" title="<?= t('oracle.report_config') ?>">⚙</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.config') ?>" <?= ($_hSec==='config'&&$_hSub==='')?'class="active"':'' ?>><?= t('oracle.report_config') ?></a>
                <a href="<?= oracle_url('report.config.tablespaces') ?>" <?= ($_hSec==='config'&&$_hSub==='tablespaces')?'class="active"':'' ?>><?= t('oracle.ts_report') ?></a>
                <a href="<?= oracle_url('report.config.memory') ?>" <?= ($_hSec==='config'&&$_hSub==='memory')?'class="active"':'' ?>><?= t('oracle.mem_title') ?></a>
                <a href="<?= oracle_url('report.config.alertlog') ?>" <?= ($_hSec==='config'&&$_hSub==='alertlog')?'class="active"':'' ?>><?= t('oracle.alertlog_title') ?></a>
                <a href="<?= oracle_url('report.config.indicators') ?>" <?= ($_hSec==='config'&&$_hSub==='indicators')?'class="active"':'' ?>><?= t('oracle.indicators_title') ?></a>
                <a href="<?= oracle_url('report.config.stats') ?>" <?= ($_hSec==='config'&&$_hSub==='stats')?'class="active"':'' ?>><?= t('oracle.cfgstats_title') ?></a>
                <a href="<?= oracle_url('report.config.sqltune') ?>" <?= ($_hSec==='config'&&$_hSub==='sqltune')?'class="active"':'' ?>><?= t('oracle.cfgsqlt_title') ?></a>
                <?php
                $_rpShow = ((Session::get('oracle_selected_db')['right'] ?? '') === 'dba')
                        || (isset($auth) && $auth->hasAnyRole(ROLE_APP_ADMIN, 'oracle_admin'));
                if ($_rpShow):
                ?>
                <a href="<?= oracle_url('report.config.restorepoints') ?>" <?= ($_hSec==='config'&&$_hSub==='restorepoints')?'class="active"':'' ?>><?= t('oracle.restorepoints_title') ?></a>
                <a href="<?= oracle_url('report.config.audit') ?>" <?= ($_hSec==='config'&&$_hSub==='audit')?'class="active"':'' ?>><?= t('oracle.cfgaudit_title') ?></a>
                <?php endif; ?>
            </div>
        </div>
        <div class="oracle-dropdown" id="oci-menu-realtime">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'realtime' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-realtime', event)" title="<?= t('oracle.report_realtime') ?>">⚡</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.realtime') ?>" <?= ($_hSec==='realtime'&&$_hSub==='')?'class="active"':'' ?>><?= t('oracle.report_realtime') ?></a>
                <a href="<?= oracle_url('report.realtime.sessions') ?>" <?= ($_hSec==='realtime'&&$_hSub==='sessions')?'class="active"':'' ?>><?= t('oracle.sess_nav') ?></a>
                <a href="<?= oracle_url('report.realtime.locks') ?>" <?= ($_hSec==='realtime'&&$_hSub==='locks')?'class="active"':'' ?>><?= t('oracle.locks_title') ?></a>
            </div>
        </div>
        <div class="oracle-dropdown" id="oci-menu-history">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'history' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-history', event)" title="<?= t('oracle.report_history') ?>">📅</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.history') ?>" <?= ($_hSec==='history'&&$_hSub==='')?'class="active"':'' ?>><?= t('oracle.report_history') ?></a>
                <a href="<?= oracle_url('report.history.detail') ?>" <?= ($_hSec==='history'&&$_hSub==='detail')?'class="active"':'' ?>><?= t('oracle.ash_detail_nav') ?></a>
            </div>
        </div>
        <div class="oracle-dropdown" id="oci-menu-reports">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'reports' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-reports', event)" title="<?= t('oracle.reports_menu') ?>">📑</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.reports.ash') ?>" <?= ($_hSec==='reports'&&$_hSub==='ash')?'class="active"':'' ?>><?= t('oracle.reports_ash') ?></a>
                <a href="<?= oracle_url('report.reports.awr') ?>" <?= ($_hSec==='reports'&&$_hSub==='awr')?'class="active"':'' ?>><?= t('oracle.reports_awr') ?></a>
                <a href="<?= oracle_url('report.reports.sqlmon') ?>" <?= ($_hSec==='reports'&&$_hSub==='sqlmon')?'class="active"':'' ?>><?= t('oracle.reports_sqlmon') ?></a>
            </div>
        </div>
        <div class="oracle-dropdown" id="oci-menu-diag">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'diag' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-diag', event)" title="<?= t('oracle.diag_menu') ?>">🩺</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.diag.slowdown') ?>" <?= ($_hSec==='diag'&&$_hSub==='slowdown')?'class="active"':'' ?>><?= t('oracle.diag_slowdown_title') ?></a>
                <a href="<?= oracle_url('report.diag.ora1555') ?>" <?= ($_hSec==='diag'&&$_hSub==='ora1555')?'class="active"':'' ?>><?= t('oracle.diag_ora1555_title') ?></a>
                <a href="<?= oracle_url('report.diag.ora4030') ?>" <?= ($_hSec==='diag'&&$_hSub==='ora4030')?'class="active"':'' ?>><?= t('oracle.diag_ora4030_title') ?></a>
                <a href="<?= oracle_url('report.diag.ora4031') ?>" <?= ($_hSec==='diag'&&$_hSub==='ora4031')?'class="active"':'' ?>><?= t('oracle.diag_ora4031_title') ?></a>
            </div>
        </div>
        <div class="oracle-dropdown" id="oci-menu-dash">
            <button type="button" class="oracle-dropdown-btn <?= $_hSec === 'dash' ? 'active' : '' ?>"
                    onclick="ociToggle('oci-menu-dash', event)" title="<?= t('oracle.dash_menu') ?>">📊</button>
            <div class="oracle-dropdown-menu">
                <a href="<?= oracle_url('report.dash.backup_summary') ?>" <?= ($_hSec==='dash'&&$_hSub==='backup_summary')?'class="active"':'' ?>><?= t('oracle.dash_bksum_title') ?></a>
                <a href="<?= oracle_url('report.dash.licenses') ?>" <?= ($_hSec==='dash'&&$_hSub==='licenses')?'class="active"':'' ?>><?= t('oracle.dash_licenses_title') ?></a>
                <a href="<?= oracle_url('report.dash.scheduler') ?>" <?= ($_hSec==='dash'&&$_hSub==='scheduler')?'class="active"':'' ?>><?= t('oracle.dash_scheduler_title') ?></a>
                <a href="<?= oracle_url('report.dash.exports') ?>" <?= ($_hSec==='dash'&&$_hSub==='exports')?'class="active"':'' ?>><?= t('oracle.dash_exports_title') ?></a>
                <a href="<?= oracle_url('report.dash.stats') ?>" <?= ($_hSec==='dash'&&$_hSub==='stats')?'class="active"':'' ?>><?= t('oracle.dash_stats_title') ?></a>
                <a href="<?= oracle_url('report.dash.tde_wallets') ?>" <?= ($_hSec==='dash'&&$_hSub==='tde_wallets')?'class="active"':'' ?>><?= t('oracle.dash_tde_title') ?></a>
            </div>
        </div>
    </nav>
    <a href="<?= oracle_url('home') ?>" class="oracle-sidebar-home" title="<?= t('oracle.title') ?>">←</a>
</aside>
<?php endif; ?>

<?php if ($_pgOn): ?>
<!-- Rail d'icones des rapports PostgreSQL : une icone par groupe, sous-menus
     en texte seul. Replie par le burger place a cote du logo applicatif. -->
<aside class="pg-sidebar" id="pg-sidebar" aria-label="<?= t('postgresql.nav_reports') ?>">
    <nav class="pg-sidebar-nav">
        <?php foreach ($_pgMenu as $_gKey => $_g):
            $_gActive = array_key_exists($_pgSec, $_g['items']); ?>
        <div class="pg-dropdown" id="pg-menu-<?= $_gKey ?>">
            <button type="button" class="pg-dropdown-btn <?= $_gActive ? 'active' : '' ?>"
                    onclick="pgToggle('pg-menu-<?= $_gKey ?>', event)"
                    title="<?= htmlspecialchars(t($_g['label'])) ?>"><?= $_g['icon'] ?></button>
            <div class="pg-dropdown-menu">
                <?php foreach ($_g['items'] as $_sec => $_lbl): ?>
                <a href="<?= pg_url('report', ['section' => $_sec]) ?>"
                   <?= $_pgSec === $_sec ? 'class="active"' : '' ?>><?= t($_lbl) ?></a>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </nav>
</aside>
<?php endif; ?>
<?php unset($_hNav, $_oraNav, $_hSec, $_hSub, $_pgNav, $_pgOn, $_pgSec, $_pgMenu); ?>

<main class="site-main">
<div class="container">

<?php
// Display flash messages
foreach (['success', 'error', 'warning', 'info'] as $type) {
    $msg = Session::getFlash($type);
    if ($msg) {
        echo "<div class=\"alert alert-$type\" role=\"alert\">"
           . htmlspecialchars($msg)
           . '<button class="alert-close" onclick="this.parentElement.remove()">×</button>'
           . '</div>';
    }
}
?>
