<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';

/** 後台用站台主名稱（來自 fate/data/fate_ui_settings.json）。 */
function fate_admin_site_main_name(): string
{
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }
    $b = fate_public_site_branding();
    $cached = $b['title_main'] !== '' ? $b['title_main'] : 'FATE';

    return $cached;
}

/** @return array{title_main:string,title_sub:string} */
function fate_admin_site_branding(): array
{
    $b = fate_public_site_branding();

    return [
        'title_main' => $b['title_main'] !== '' ? $b['title_main'] : 'FATE',
        'title_sub' => $b['title_sub'] !== '' ? $b['title_sub'] : '',
    ];
}

function fate_admin_layout_title(string $pageLabel): string
{
    return fate_admin_site_main_name() . ' 後台 — ' . $pageLabel;
}

/**

 * @return list<array{id:string,href:string,label:string}>

 */

function fate_admin_nav_items(): array

{

    $items = [

        ['id' => 'home', 'href' => 'index.php', 'label' => '概覽'],

        ['id' => 'sync', 'href' => 'sync.php', 'label' => '同步店家'],

        ['id' => 'spa_api', 'href' => 'spa_api_key.php', 'label' => '新手村 API'],

        ['id' => 'add_store', 'href' => 'add_store.php', 'label' => '新增店家'],

        ['id' => 'approve_stores', 'href' => 'approve_stores.php', 'label' => '審核推薦店家'],

        ['id' => 'masseurs', 'href' => 'masseurs.php', 'label' => '推薦技師'],

        ['id' => 'site_modes', 'href' => 'site_modes.php', 'label' => '功能快速設定'],

        ['id' => 'ncoin', 'href' => 'ncoin.php', 'label' => '站內貨幣設定/紀錄'],

        ['id' => 'template', 'href' => 'template.php', 'label' => '網站與模版'],

        ['id' => 'adsense', 'href' => 'adsense.php', 'label' => 'Google AdSense'],

        ['id' => 'email', 'href' => 'email_settings.php', 'label' => '驗證信與發信'],

        ['id' => 'members', 'href' => 'members.php', 'label' => '會員管理'],

        ['id' => 'stats', 'href' => 'stats.php', 'label' => '瀏覽統計'],

    ];

    require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';
    if (fate_plugins_feature_available()) {
        array_splice($items, 9, 0, [['id' => 'plugins', 'href' => 'plugins.php', 'label' => '外掛管理']]);
    }

    return $items;

}



/** 後台頁面 → 站台前台首頁（相對路徑，適用 /admin 子目錄部署） */
function fate_admin_front_href(): string
{
    return '../';
}

/** 站台根目錄 static/（後台頁面以 ../static/ 引用） */
function fate_site_static_url(string $basename): string
{
    return fate_admin_front_href() . 'static/' . ltrim(str_replace('\\', '/', $basename), '/');
}

function fate_admin_asset_url(string $rel): string

{

    $scriptDir = dirname((string) ($_SERVER['SCRIPT_NAME'] ?? '/admin'));

    $scriptDir = str_replace('\\', '/', $scriptDir);

    $base = rtrim($scriptDir, '/');

    if ($base === '' || $base === '.') {

        $base = '/admin';

    }



    return $base . '/' . ltrim(str_replace('\\', '/', $rel), '/');

}



/**

 * @param array{title?:string,page?:string,active?:string,bare?:bool,body_class?:string} $opts

 */

function fate_admin_layout_start(array $opts): void

{
    $brand = fate_admin_site_branding();
    $siteMain = $brand['title_main'];

    $pageLabel = isset($opts['page']) && is_string($opts['page']) ? trim($opts['page']) : '';
    if ($pageLabel !== '') {
        $title = fate_admin_layout_title($pageLabel);
    } else {
        $title = isset($opts['title']) && is_string($opts['title']) ? trim($opts['title']) : '';
        if ($title === '') {
            $title = $siteMain . ' 後台';
        }
    }

    $active = $opts['active'] ?? '';

    $bare = !empty($opts['bare']);

    $bodyExtra = isset($opts['body_class']) && is_string($opts['body_class']) ? trim($opts['body_class']) : '';

    $cssPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'admin.css';

    $cssVer = is_file($cssPath) ? (string) filemtime($cssPath) : '1';



    header('Content-Type: text/html; charset=UTF-8');

    $bodyClass = 'admin-body' . ($bare ? ' admin-body--bare' : '') . ($bodyExtra !== '' ? ' ' . htmlspecialchars($bodyExtra, ENT_QUOTES, 'UTF-8') : '');

    ?>

<!DOCTYPE html>

<html lang="zh-Hant">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <meta name="robots" content="noindex,nofollow">

    <?php
    require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_favicon.php';
    fate_favicon_head_links();
    ?>

    <title><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></title>

    <link rel="stylesheet" href="<?= htmlspecialchars(fate_admin_asset_url('static/admin.css'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($cssVer, ENT_QUOTES, 'UTF-8') ?>">
    <?php
    $apiJsPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'admin_api.js';
    $apiJsVer = is_file($apiJsPath) ? (string) filemtime($apiJsPath) : '1';
    ?>
    <script src="<?= htmlspecialchars(fate_admin_asset_url('static/admin_api.js'), ENT_QUOTES, 'UTF-8') ?>?v=<?= htmlspecialchars($apiJsVer, ENT_QUOTES, 'UTF-8') ?>" defer></script>

</head>

<body class="<?= $bodyClass ?>">

    <div class="admin-shell<?= $bare ? ' admin-shell--auth' : '' ?>">

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

        <aside class="admin-side" aria-label="後台導覽">

            <div class="admin-side__brand">

                <a href="index.php"><?= htmlspecialchars($siteMain, ENT_QUOTES, 'UTF-8') ?><span> /admin</span></a>

            </div>

            <nav class="admin-nav">

                <?php foreach (fate_admin_nav_items() as $item): ?>

                    <a href="<?= htmlspecialchars($item['href'], ENT_QUOTES, 'UTF-8') ?>" class="<?= $active === $item['id'] ? 'on' : '' ?>"><?= htmlspecialchars($item['label'], ENT_QUOTES, 'UTF-8') ?></a>

                <?php endforeach; ?>

            </nav>

            <p class="admin-side__front">
                <a href="<?= htmlspecialchars(fate_admin_front_href(), ENT_QUOTES, 'UTF-8') ?>">← 回前台</a>
            </p>

            <?php if (fate_admin_is_logged_in()): ?>

                <div class="admin-side__foot">

                    <span class="admin-side__foot-user"><?= htmlspecialchars(fate_admin_member_display_label(), ENT_QUOTES, 'UTF-8') ?></span>

                    <span aria-hidden="true"> · </span>

                    <a href="logout.php">登出</a>

                </div>

            <?php endif; ?>

        </aside>

        <?php endif; ?>

        <main class="admin-main">

        <?php if ($bare): ?>

            <div class="auth-brand"><span class="auth-brand__title"><?= htmlspecialchars($siteMain, ENT_QUOTES, 'UTF-8') ?></span><span class="auth-brand__sub">後台</span></div>
            <p class="auth-front-link"><a href="<?= htmlspecialchars(fate_admin_front_href(), ENT_QUOTES, 'UTF-8') ?>">← 回前台</a></p>

        <?php endif; ?>

    <?php

}



function fate_admin_layout_end(): void

{

    ?>

        </main>

    </div>

</body>

</html>

    <?php

}


