<?php



declare(strict_types=1);



require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'dashboard_icons.php';

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_dashboard.php';



fate_admin_require_login();



$pdo = null;

$dbErr = null;

try {

    require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'pdo.php';

    if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {

        $pdo = $GLOBALS['pdo'];

    }

} catch (Throwable $e) {

    $dbErr = $e->getMessage();

}



$dash = fate_admin_dashboard_collect($pdo);

if ($dbErr !== null) {

    $dash['db_err'] = $dbErr;

    $dash['db_ok'] = false;

}



$statCards = fate_admin_dashboard_stat_cards($dash);

$actionGroups = fate_admin_dashboard_action_groups();

$setupFlash = isset($_GET['setup']) && $_GET['setup'] === 'ok';



$brand = is_array($dash['branding'] ?? null) ? $dash['branding'] : fate_admin_site_branding();

$siteTitle = (string) ($brand['title_main'] ?? fate_admin_site_main_name());

$siteTag = trim((string) ($brand['title_sub'] ?? ''));

$frontHref = fate_admin_front_href();

$templateLabel = (string) ($dash['template'] ?? 'default');

$templateSource = fate_admin_dashboard_template_source_label($dash);

$dbOk = !empty($dash['db_ok']);



$tz = new DateTimeZone('Asia/Taipei');

$now = new DateTime('now', $tz);

$weekdays = ['日', '一', '二', '三', '四', '五', '六'];

$dateLabel = $now->format('Y年n月j日') . '（' . $weekdays[(int) $now->format('w')] . '）';



$monogram = $siteTitle !== '' ? mb_substr($siteTitle, 0, 1, 'UTF-8') : 'F';



fate_admin_layout_start(['page' => '概覽', 'active' => 'home', 'body_class' => 'admin-body--home']);

?>

        <div class="dash">

            <section class="dash-hero-card" aria-label="歡迎">

                <div class="dash-hero-card__glow" aria-hidden="true"></div>

                <div class="dash-hero-card__inner">

                    <div class="dash-hero-card__lead">

                        <span class="dash-monogram" aria-hidden="true"><?= htmlspecialchars($monogram, ENT_QUOTES, 'UTF-8') ?></span>

                        <div class="dash-hero-card__copy">

                            <p class="dash-hero-card__eyebrow"><?= htmlspecialchars($dateLabel, ENT_QUOTES, 'UTF-8') ?></p>

                            <h1 class="dash-hero-card__title">

                                <?= htmlspecialchars((string) ($dash['admin_label'] ?? '管理員'), ENT_QUOTES, 'UTF-8') ?>，歡迎回來

                            </h1>

                            <p class="dash-hero-card__sub">

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

                                <?php if ($siteTag !== ''): ?>

                                    <span class="dash-hero-card__tag"><?= htmlspecialchars($siteTag, ENT_QUOTES, 'UTF-8') ?></span>

                                <?php endif; ?>

                            </p>

                        </div>

                    </div>

                    <div class="dash-hero-card__aside">

                        <div class="dash-pills">

                            <span class="dash-pill<?= $dbOk ? ' dash-pill--ok' : ' dash-pill--bad' ?>">

                                <?= $dbOk ? '資料庫正常' : '資料庫異常' ?>

                            </span>

                            <span class="dash-pill dash-pill--muted">

                                模版 <code><?= htmlspecialchars($templateLabel, ENT_QUOTES, 'UTF-8') ?></code>

                            </span>

                        </div>

                        <div class="dash-hero-card__actions">

                            <a class="btn btn--ghost dash-btn-icon" href="<?= htmlspecialchars($frontHref, ENT_QUOTES, 'UTF-8') ?>">

                                <?= fate_admin_dashboard_icon('external') ?>

                                <span>前往前台</span>

                            </a>

                            <a class="btn dash-btn-icon dash-btn-icon--primary" href="sync.php">

                                <?= fate_admin_dashboard_icon('sync') ?>

                                <span>同步店家</span>

                            </a>

                        </div>

                    </div>

                </div>

            </section>



            <?php if ($setupFlash): ?>

                <div class="msg ok dash-flash">店家快照表已就緒，可前往<a href="sync.php">同步店家</a>。</div>

            <?php endif; ?>



            <?php if (!empty($dash['db_err'])): ?>

                <div class="msg bad dash-flash">資料庫：<code><?= htmlspecialchars((string) $dash['db_err'], ENT_QUOTES, 'UTF-8') ?></code></div>

            <?php endif; ?>



            <?php

            $alerts = is_array($dash['alerts'] ?? null) ? $dash['alerts'] : [];

            if ($alerts !== []):

            ?>

                <section class="dash-card dash-card--alerts" aria-label="待處理提醒">

                    <header class="dash-card__head">

                        <h2 class="dash-card__title">待處理</h2>

                        <span class="dash-card__badge"><?= count($alerts) ?></span>

                    </header>

                    <ul class="dash-alert-list">

                        <?php foreach ($alerts as $alert):

                            if (!is_array($alert)) {

                                continue;

                            }

                            $level = ($alert['level'] ?? '') === 'bad' ? 'bad' : 'warn';

                            $iconName = $level === 'bad' ? 'alert-bad' : 'alert-warn';

                            ?>

                            <li class="dash-alert-item dash-alert-item--<?= htmlspecialchars($level, ENT_QUOTES, 'UTF-8') ?>">

                                <span class="dash-alert-item__icon"><?= fate_admin_dashboard_icon($iconName) ?></span>

                                <div class="dash-alert-item__body">

                                    <p class="dash-alert-item__text"><?= htmlspecialchars((string) ($alert['text'] ?? ''), ENT_QUOTES, 'UTF-8') ?></p>

                                    <?php if (!empty($alert['href']) && !empty($alert['label'])): ?>

                                        <a class="dash-alert-item__cta" href="<?= htmlspecialchars((string) $alert['href'], ENT_QUOTES, 'UTF-8') ?>">

                                            <?= htmlspecialchars((string) $alert['label'], ENT_QUOTES, 'UTF-8') ?>

                                            <?= fate_admin_dashboard_icon('chevron') ?>

                                        </a>

                                    <?php endif; ?>

                                </div>

                            </li>

                        <?php endforeach; ?>

                    </ul>

                </section>

            <?php endif; ?>



            <?php if ($statCards !== []): ?>

                <section class="dash-card" aria-labelledby="dash-stats-title">

                    <header class="dash-card__head">

                        <h2 id="dash-stats-title" class="dash-card__title">數據一覽</h2>

                    </header>

                    <div class="dash-stats">

                        <?php foreach ($statCards as $i => $card):

                            if (!is_array($card)) {

                                continue;

                            }

                            $tone = isset($card['tone']) && is_string($card['tone']) ? $card['tone'] : 'muted';

                            $iconId = isset($card['icon']) && is_string($card['icon']) ? $card['icon'] : 'dot';

                            ?>

                            <a class="dash-stat dash-stat--<?= htmlspecialchars($tone, ENT_QUOTES, 'UTF-8') ?>"

                               href="<?= htmlspecialchars((string) ($card['href'] ?? '#'), ENT_QUOTES, 'UTF-8') ?>"

                               style="--dash-i: <?= (int) $i ?>">

                                <span class="dash-stat__icon" aria-hidden="true"><?= fate_admin_dashboard_icon($iconId) ?></span>

                                <span class="dash-stat__label"><?= htmlspecialchars((string) ($card['label'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>

                                <span class="dash-stat__value"><?= htmlspecialchars((string) ($card['value'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></span>

                                <span class="dash-stat__hint"><?= htmlspecialchars((string) ($card['hint'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>

                                <span class="dash-stat__arrow" aria-hidden="true"><?= fate_admin_dashboard_icon('chevron') ?></span>

                            </a>

                        <?php endforeach; ?>

                    </div>

                </section>

            <?php endif; ?>



            <div class="dash-columns">

                <section class="dash-card dash-card--actions" aria-labelledby="dash-actions-title">

                    <header class="dash-card__head">

                        <h2 id="dash-actions-title" class="dash-card__title">常用操作</h2>

                    </header>

                    <?php foreach ($actionGroups as $group):

                        if (!is_array($group) || empty($group['items'])) {

                            continue;

                        }

                        ?>

                        <div class="dash-action-group">

                            <h3 class="dash-action-group__title"><?= htmlspecialchars((string) ($group['title'] ?? ''), ENT_QUOTES, 'UTF-8') ?></h3>

                            <ul class="dash-action-grid">

                                <?php foreach ($group['items'] as $item):

                                    if (!is_array($item)) {

                                        continue;

                                    }

                                    $itemId = isset($item['id']) && is_string($item['id']) ? $item['id'] : 'dot';

                                    ?>

                                    <li>

                                        <a class="dash-action-card" href="<?= htmlspecialchars((string) ($item['href'] ?? '#'), ENT_QUOTES, 'UTF-8') ?>">

                                            <span class="dash-action-card__icon" aria-hidden="true"><?= fate_admin_dashboard_icon($itemId) ?></span>

                                            <span class="dash-action-card__text">

                                                <span class="dash-action-card__label"><?= htmlspecialchars((string) ($item['label'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>

                                                <span class="dash-action-card__desc"><?= htmlspecialchars((string) ($item['desc'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>

                                            </span>

                                            <span class="dash-action-card__arrow" aria-hidden="true"><?= fate_admin_dashboard_icon('chevron') ?></span>

                                        </a>

                                    </li>

                                <?php endforeach; ?>

                            </ul>

                        </div>

                    <?php endforeach; ?>

                </section>



                <section class="dash-card dash-card--sys" aria-labelledby="dash-sys-title">

                    <header class="dash-card__head">

                        <h2 id="dash-sys-title" class="dash-card__title">系統資訊</h2>

                    </header>

                    <dl class="dash-sys-list">

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('globe') ?></span>站台</dt>

                            <dd>

                                <a href="<?= htmlspecialchars($frontHref, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($siteTitle, ENT_QUOTES, 'UTF-8') ?></a>

                                <?php if ($siteTag !== ''): ?>

                                    <span class="dash-meta__muted"> — <?= htmlspecialchars($siteTag, ENT_QUOTES, 'UTF-8') ?></span>

                                <?php endif; ?>

                            </dd>

                        </div>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('template') ?></span>前台模版</dt>

                            <dd>

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

                                <span class="dash-meta__muted">（<?= htmlspecialchars($templateSource, ENT_QUOTES, 'UTF-8') ?>）</span>

                                · <a href="template.php">設定</a>

                            </dd>

                        </div>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('api') ?></span>新手村 API</dt>

                            <dd>

                                <code class="dash-sys-row__code"><?= htmlspecialchars(defined('FATE_SPA_API_BASE') ? (string) FATE_SPA_API_BASE : '—', ENT_QUOTES, 'UTF-8') ?></code>

                                · <a href="spa_api_key.php">金鑰</a>

                            </dd>

                        </div>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('db') ?></span>會員表</dt>

                            <dd>

                                <code><?= htmlspecialchars(fate_admin_member_auth_ready() ? FATE_MEMBER_DATABASE . '.' . FATE_MEMBER_TABLE : '—', ENT_QUOTES, 'UTF-8') ?></code>

                                · <a href="members.php">管理</a>

                            </dd>

                        </div>

                        <?php

                        $stores = is_array($dash['stores'] ?? null) ? $dash['stores'] : [];

                        if (!empty($stores['ok'])):

                        ?>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('stores') ?></span>店家快照</dt>

                            <dd>

                                <?= isset($stores['count']) ? htmlspecialchars(number_format((int) $stores['count']), ENT_QUOTES, 'UTF-8') . ' 筆' : '—' ?>

                                <?php if (!empty($stores['last_synced'])): ?>

                                    <span class="dash-meta__muted"> · 同步 <?= htmlspecialchars((string) $stores['last_synced'], ENT_QUOTES, 'UTF-8') ?></span>

                                <?php endif; ?>

                            </dd>

                        </div>

                        <?php if (isset($stores['max_unix']) && $stores['max_unix'] !== null): ?>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('sync') ?></span>來源版本</dt>

                            <dd><code>data_as_of_unix <?= (int) $stores['max_unix'] ?></code></dd>

                        </div>

                        <?php endif; ?>

                        <?php endif; ?>

                        <?php

                        $traffic = is_array($dash['traffic'] ?? null) ? $dash['traffic'] : [];

                        $visitor = is_array($traffic['visitor'] ?? null) ? $traffic['visitor'] : null;

                        if ($visitor !== null):

                        ?>

                        <div class="dash-sys-row">

                            <dt><span class="dash-sys-row__icon"><?= fate_admin_dashboard_icon('visitors') ?></span>訪客</dt>

                            <dd>

                                今日 <?= htmlspecialchars(number_format((int) ($visitor['today_unique'] ?? 0)), ENT_QUOTES, 'UTF-8') ?>

                                · 在線 <?= htmlspecialchars(number_format((int) ($visitor['online_now'] ?? 0)), ENT_QUOTES, 'UTF-8') ?>

                                <?php if (!empty($visitor['peak_online'])): ?>

                                    <span class="dash-meta__muted"> · 峰值 <?= htmlspecialchars(number_format((int) $visitor['peak_online']), ENT_QUOTES, 'UTF-8') ?></span>

                                <?php endif; ?>

                                · <a href="stats.php">詳情</a>

                            </dd>

                        </div>

                        <?php endif; ?>

                    </dl>

                </section>

            </div>

        </div>

<?php

fate_admin_layout_end();


