<?php

declare(strict_types=1);

/**
 * 訪客／線上人數：改由 fate_visit_log 依 IP（明文 client_ip）聚合；僅保留 fate_visitor_settings 存「在線視窗」與歷史峰值。
 *
 * fate_visitor_pulse() 已不再寫入資料庫（相容舊呼叫處，改為空操作）。
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_visit_log.php';

function fate_visitor_settings_table_ddl(): string
{
    return <<<'SQL'
CREATE TABLE IF NOT EXISTS fate_visitor_settings (
    id TINYINT UNSIGNED NOT NULL PRIMARY KEY,
    online_window_minutes SMALLINT UNSIGNED NOT NULL DEFAULT 10,
    peak_online INT UNSIGNED NOT NULL DEFAULT 0,
    peak_online_at DATETIME NULL
) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci
SQL;
}

function fate_visitor_ensure_tables(PDO $pdo): void
{
    static $done = false;
    if ($done) {
        return;
    }
    $pdo->exec(fate_visitor_settings_table_ddl());
    $pdo->exec(
        "INSERT IGNORE INTO fate_visitor_settings (id, online_window_minutes, peak_online, peak_online_at) VALUES (1, 10, 0, NULL)"
    );
    $done = true;
}

function fate_visitor_client_ip(): string
{
    return fate_visit_log_client_ip();
}

/**
 * @deprecated 已改為瀏覽紀錄表統計；保留為相容的空函式。
 */
function fate_visitor_pulse(?PDO $pdo): void
{
    /* fate_visit_log_append 於各頁面載入時已寫入 */
}

function fate_visitor_get_online_window_minutes(PDO $pdo): int
{
    fate_visitor_ensure_tables($pdo);
    $st = $pdo->query('SELECT online_window_minutes FROM fate_visitor_settings WHERE id = 1 LIMIT 1');
    $w = $st ? (int) $st->fetchColumn() : 10;

    return max(1, min(24 * 60, $w));
}

/** @return bool 是否成功 */
function fate_visitor_set_online_window_minutes(PDO $pdo, int $minutes): bool
{
    $minutes = max(1, min(24 * 60, $minutes));
    try {
        fate_visitor_ensure_tables($pdo);
        $st = $pdo->prepare('UPDATE fate_visitor_settings SET online_window_minutes = ? WHERE id = 1');
        $st->execute([$minutes]);

        return true;
    } catch (Throwable) {
        return false;
    }
}

function fate_visitor_count_online(PDO $pdo, int $windowMinutes): int
{
    return fate_visit_log_distinct_ip_in_window($pdo, $windowMinutes);
}

/**
 * @return array{
 *   total_unique:int,
 *   today_unique:int,
 *   online_now:int,
 *   window_minutes:int,
 *   peak_online:int,
 *   peak_online_at:?string
 * }
 */
function fate_visitor_admin_snapshot(PDO $pdo): array
{
    fate_visitor_ensure_tables($pdo);
    $window = fate_visitor_get_online_window_minutes($pdo);
    $startDay = date('Y-m-d 00:00:00');

    $totalUnique = fate_visit_log_distinct_ip_total($pdo);
    $todayUnique = fate_visit_log_distinct_ip_since_datetime($pdo, $startDay);
    $onlineNow = fate_visitor_count_online($pdo, $window);

    $meta = $pdo->query(
        'SELECT peak_online, DATE_FORMAT(peak_online_at, \'%Y-%m-%d %H:%i:%s\') AS peak_at
         FROM fate_visitor_settings WHERE id = 1 LIMIT 1'
    );
    $peakOnline = 0;
    $peakAt = null;
    if ($meta && ($row = $meta->fetch(PDO::FETCH_ASSOC)) && is_array($row)) {
        $peakOnline = isset($row['peak_online']) ? (int) $row['peak_online'] : 0;
        $peakAt = isset($row['peak_at']) && $row['peak_at'] !== null && $row['peak_at'] !== ''
            ? (string) $row['peak_at']
            : null;
    }

    if ($onlineNow > $peakOnline) {
        try {
            $up = $pdo->prepare(
                'UPDATE fate_visitor_settings SET peak_online = ?, peak_online_at = NOW() WHERE id = 1 AND ? > peak_online'
            );
            $up->execute([$onlineNow, $onlineNow]);
            $meta2 = $pdo->query(
                'SELECT peak_online, DATE_FORMAT(peak_online_at, \'%Y-%m-%d %H:%i:%s\') AS peak_at
                 FROM fate_visitor_settings WHERE id = 1 LIMIT 1'
            );
            if ($meta2 && ($row2 = $meta2->fetch(PDO::FETCH_ASSOC)) && is_array($row2)) {
                $peakOnline = isset($row2['peak_online']) ? (int) $row2['peak_online'] : $peakOnline;
                $peakAt = isset($row2['peak_at']) && $row2['peak_at'] !== null && $row2['peak_at'] !== ''
                    ? (string) $row2['peak_at']
                    : $peakAt;
            }
        } catch (Throwable) {
            /* 略過 */
        }
    }

    return [
        'total_unique' => $totalUnique,
        'today_unique' => $todayUnique,
        'online_now' => $onlineNow,
        'window_minutes' => $window,
        'peak_online' => $peakOnline,
        'peak_online_at' => $peakAt,
    ];
}
