<?php

declare(strict_types=1);

require_once __DIR__ . DIRECTORY_SEPARATOR . 'auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'layout.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_page_counter.php';
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_visitor_tracker.php';

fate_admin_require_login();

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

$pdo = null;
$dbErr = null;
try {
    $pdo = fate_app_pdo($dbErr);
} catch (Throwable $e) {
    $dbErr = $e->getMessage();
    $pdo = null;
}

$visitorSaved = isset($_GET['visitor_saved']) && $_GET['visitor_saved'] === '1';
$visitLogSaved = isset($_GET['visit_log_saved']) && $_GET['visit_log_saved'] === '1';
$visitorFormErr = null;
$visitLogFormErr = null;
$visitLogMissing = false;

if ($pdo instanceof PDO) {
    $visitLogMissing = !fate_visit_log_table_exists($pdo);
}

if ($pdo instanceof PDO && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['visit_log_install'])) {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $visitLogFormErr = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $install = fate_visit_log_install($pdo);
        if (empty($install['ok'])) {
            $visitLogFormErr = '無法建立瀏覽紀錄表：' . ($install['message'] ?? '未知錯誤');
        } else {
            header('Location: stats.php?visit_log_saved=1', true, 302);
            exit;
        }
    }
}

if ($pdo instanceof PDO && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['visitor_window_save'])) {
    $csrf = isset($_POST['csrf']) && is_string($_POST['csrf']) ? $_POST['csrf'] : '';
    if (!fate_admin_csrf_check($csrf)) {
        $visitorFormErr = '工作階段逾期或驗證失敗，請重新整理後再試。';
    } else {
        $rawMin = isset($_POST['online_window_minutes']) ? (int) $_POST['online_window_minutes'] : 10;
        if (!fate_visitor_set_online_window_minutes($pdo, $rawMin)) {
            $visitorFormErr = '無法儲存線上視窗（資料表或權限異常）。';
        } else {
            header('Location: stats.php?visitor_saved=1', true, 302);
            exit;
        }
    }
}

$pageRows = [];
$pageTotalHits = 0;
$pageTableErr = null;

$storeRows = [];
$storeTotalHits = 0;
$storeRowCount = 0;
$storeTableErr = null;

$visitorSnap = null;
$visitorSnapErr = null;

if ($pdo instanceof PDO) {
    try {
        $pageRows = fate_page_hit_stats_fetch_all($pdo);
        $pageTotalHits = fate_page_hit_stats_total_hits($pdo);
    } catch (Throwable $e) {
        $pageTableErr = $e->getMessage();
    }
    try {
        $storeRows = fate_store_hit_stats_fetch_top($pdo, 80);
        $storeTotalHits = fate_store_hit_stats_total_hits($pdo);
        $storeRowCount = fate_store_hit_stats_row_count($pdo);
    } catch (Throwable $e) {
        $storeTableErr = $e->getMessage();
    }
    try {
        $visitorSnap = fate_visitor_admin_snapshot($pdo);
    } catch (Throwable $e) {
        $visitorSnapErr = $e->getMessage();
    }
}

$csrf = fate_admin_csrf_token();

fate_admin_layout_start(['page' => '瀏覽統計', 'active' => 'stats']);
?>
        <header class="page-head">
            <h1 class="page-title">瀏覽統計</h1>
            <p class="sub">
                每次瀏覽寫入 <code>fate_visit_log</code>（時間、IP、page_key、<strong>page_title</strong>、選填會員）；下方頁面／店家／訪客人數皆由此聚合。
                線上視窗與歷史峰值存於 <code>fate_visitor_settings</code>，瀏覽紀錄表為 <code>fate_visit_log</code>（建表：<code>fate/sql/install.sql</code>）。
                「本日」與「在線」以<strong>伺服器時區</strong>為準；反向代理請設 <code>FATE_BEHIND_PROXY=1</code>。
            </p>
        </header>

        <?php if ($dbErr !== null || !$pdo instanceof PDO): ?>
            <div class="msg bad">無法連線資料庫<?= $dbErr !== null ? '：<code>' . htmlspecialchars($dbErr, ENT_QUOTES, 'UTF-8') . '</code>' : '' ?>。</div>
        <?php else: ?>

            <?php if ($visitLogMissing): ?>
                <div class="msg bad">
                    尚未建立 <code>fate_visit_log</code>，前台頁腳會顯示「瀏覽統計表尚未建立」且無法累計瀏覽次數。
                    <form method="post" style="display:inline;margin-left:0.5rem;">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <button type="submit" name="visit_log_install" value="1" class="btn-link">一鍵建立資料表</button>
                    </form>
                    或 <a href="setup_visit_log_table.php">建立瀏覽紀錄表</a>（亦可匯入 <code>fate/sql/install.sql</code>）
                </div>
            <?php endif; ?>
            <?php if ($visitLogSaved): ?>
                <div class="msg ok">已建立或確認 <code>fate_visit_log</code>。</div>
            <?php endif; ?>
            <?php if ($visitLogFormErr !== null): ?>
                <div class="msg bad"><?= htmlspecialchars($visitLogFormErr, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

            <?php if ($visitorSaved): ?>
                <div class="msg ok">已更新「在線統計視窗」分鐘數。</div>
            <?php endif; ?>
            <?php if ($visitorFormErr !== null): ?>
                <div class="msg bad"><?= htmlspecialchars($visitorFormErr, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

            <h2 class="page-title" style="font-size:1.05rem;margin:0 0 0.35rem;">訪客與線上人數</h2>
            <p class="sub" style="margin-top:0;">不重複訪客與在線人數以紀錄表中的 IP（<code>client_ip</code>）去重；NAT 後多台裝置可能視為同一訪客。</p>

            <?php if ($visitorSnapErr !== null): ?>
                <div class="msg bad">無法讀取訪客統計：<code><?= htmlspecialchars($visitorSnapErr, ENT_QUOTES, 'UTF-8') ?></code></div>
            <?php elseif ($visitorSnap !== null): ?>
                <div class="card">
                    <dl class="row">
                        <div class="stat">
                            <dt>累計不重複訪客（獨立 IP／鍵）</dt>
                            <dd><?= htmlspecialchars(number_format($visitorSnap['total_unique']), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>本日來訪（今日曾有動線的不重複訪客）</dt>
                            <dd><?= htmlspecialchars(number_format($visitorSnap['today_unique']), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>目前在線（最近 <?= (int) $visitorSnap['window_minutes'] ?> 分鐘內）</dt>
                            <dd><?= htmlspecialchars(number_format($visitorSnap['online_now']), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>同時在線最高紀錄</dt>
                            <dd><?= htmlspecialchars(number_format($visitorSnap['peak_online']), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>峰值產生時間（伺服器時區）</dt>
                            <dd><?= $visitorSnap['peak_online_at'] !== null ? htmlspecialchars($visitorSnap['peak_online_at'], ENT_QUOTES, 'UTF-8') : '—' ?></dd>
                        </div>
                    </dl>
                </div>

                <div class="card">
                    <p class="sub" style="margin-top:0;"><strong>在線視窗</strong>：用於計算「目前在線」的不重複 IP 數（預設 10 分鐘）。修改後立即套用於後台顯示。</p>
                    <form method="post" action="stats.php" style="display:flex;flex-wrap:wrap;gap:0.65rem;align-items:flex-end;">
                        <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                        <input type="hidden" name="visitor_window_save" value="1">
                        <div>
                            <label for="online_window_minutes">在線統計視窗（分鐘，1–1440）</label>
                            <input type="number" name="online_window_minutes" id="online_window_minutes" min="1" max="1440" required
                                   value="<?= (int) $visitorSnap['window_minutes'] ?>"
                                   style="width:7rem;padding:0.45rem 0.55rem;border-radius:6px;border:1px solid var(--line);background:#161922;color:var(--fg);">
                        </div>
                        <button type="submit">儲存視窗</button>
                    </form>
                </div>
            <?php endif; ?>

            <h2 class="page-title" style="font-size:1.05rem;margin:1.35rem 0 0.35rem;">頁面統計</h2>
            <?php if ($pageTableErr !== null): ?>
                <div class="msg bad">無法讀取頁面統計：<code><?= htmlspecialchars($pageTableErr, ENT_QUOTES, 'UTF-8') ?></code></div>
            <?php else: ?>
                <div class="card">
                    <dl class="row">
                        <div class="stat">
                            <dt>頁面鍵瀏覽加總（紀錄筆數）</dt>
                            <dd><?= htmlspecialchars(number_format($pageTotalHits), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>不同 page_key 數</dt>
                            <dd><?= htmlspecialchars((string) count($pageRows), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                    </dl>
                </div>

                <?php if ($pageRows === []): ?>
                    <div class="msg warn">尚無頁面計數資料。請開啟前台首頁觸發寫入。</div>
                <?php else: ?>
                    <div class="card" style="padding:0;overflow:hidden;">
                        <div class="table-scroll">
                            <table class="table--stats">
                                <colgroup>
                                    <col class="col-key">
                                    <col class="col-title">
                                    <col class="col-hits">
                                    <col class="col-time">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th scope="col" class="col-key">page_key</th>
                                        <th scope="col" class="col-title">頁面 title</th>
                                        <th scope="col" class="col-hits">次數</th>
                                        <th scope="col" class="col-time" title="伺服器時區">最近紀錄</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($pageRows as $r): ?>
                                        <tr>
                                            <td class="col-key"><code><?= htmlspecialchars($r['page_key'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                            <td class="col-title"><?= !empty($r['page_title']) ? htmlspecialchars((string) $r['page_title'], ENT_QUOTES, 'UTF-8') : '—' ?></td>
                                            <td class="col-hits"><?= htmlspecialchars(number_format($r['hit_count']), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td class="col-time"><?= htmlspecialchars($r['updated_at'], ENT_QUOTES, 'UTF-8') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endif; ?>

            <h2 class="page-title" style="font-size:1.05rem;margin:1.35rem 0 0.35rem;">店家瀏覽（詳情頁）</h2>
            <p class="sub" style="margin-top:0;">對應 <code>page_key</code> 為 <code>store.{spa_store_id}</code> 的紀錄。</p>

            <?php if ($storeTableErr !== null): ?>
                <div class="msg bad">無法讀取店家統計：<code><?= htmlspecialchars($storeTableErr, ENT_QUOTES, 'UTF-8') ?></code></div>
            <?php else: ?>
                <div class="card">
                    <dl class="row">
                        <div class="stat">
                            <dt>店家詳情頁瀏覽加總（紀錄筆數）</dt>
                            <dd><?= htmlspecialchars(number_format($storeTotalHits), ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                        <div class="stat">
                            <dt>有資料的店家數</dt>
                            <dd><?= htmlspecialchars((string) $storeRowCount, ENT_QUOTES, 'UTF-8') ?></dd>
                        </div>
                    </dl>
                </div>

                <?php if ($storeRows === []): ?>
                    <div class="msg warn">尚無店家計數。</div>
                <?php else: ?>
                    <div class="card" style="padding:0;overflow:hidden;">
                        <div class="table-scroll">
                            <table class="table--stats table--stats--store">
                                <colgroup>
                                    <col class="col-key">
                                    <col class="col-title">
                                    <col class="col-hits">
                                    <col class="col-time">
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th scope="col" class="col-key">店家 ID</th>
                                        <th scope="col" class="col-title">店名（快照）</th>
                                        <th scope="col" class="col-hits">次數</th>
                                        <th scope="col" class="col-time" title="伺服器時區">最近紀錄</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($storeRows as $r): ?>
                                        <tr>
                                            <td class="col-key"><code><?= htmlspecialchars((string) $r['spa_store_id'], ENT_QUOTES, 'UTF-8') ?></code></td>
                                            <td class="col-title"><?= $r['store_name'] !== null ? htmlspecialchars($r['store_name'], ENT_QUOTES, 'UTF-8') : '—' ?></td>
                                            <td class="col-hits"><?= htmlspecialchars(number_format($r['hit_count']), ENT_QUOTES, 'UTF-8') ?></td>
                                            <td class="col-time"><?= htmlspecialchars($r['updated_at'], ENT_QUOTES, 'UTF-8') ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php if ($storeRowCount > 80): ?>
                        <p class="sub">僅顯示前 80 名（依次數排序）。</p>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>

            <div class="page-actions"><a class="btn" href="index.php">返回概覽</a></div>
        <?php endif; ?>
<?php
fate_admin_layout_end();
