<?php

declare(strict_types=1);

/**
 * 是否於前台顯示「管理後台」連結：
 * - 已用前台會員登入且 role 為 admin（Session：`fate_site_is_admin`）
 * - 或已用 /admin 登入（Cookie／Session：`fate_admin`）
 *
 * 請在 fate_public_session_start() 之後呼叫（需能讀取 fate_site Session）。
 */
function fate_admin_nav_visible_for_frontend(): bool
{
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }

    if (session_status() === PHP_SESSION_ACTIVE && session_name() === 'fate_site') {
        if (!empty($_SESSION['fate_site_is_admin'])) {
            return $cached = true;
        }
        // 一般會員且無後台 Cookie：勿關 Session，避免模版輸出後 partial 再 start 而觸發 setcookie
        if (!isset($_COOKIE['fate_admin']) || $_COOKIE['fate_admin'] === '') {
            return $cached = false;
        }
        if (headers_sent()) {
            return $cached = false;
        }
        session_write_close();
    } elseif (session_status() === PHP_SESSION_ACTIVE && session_name() === 'fate_admin') {
        return $cached = isset($_SESSION['fate_admin_member_id']) && (int) $_SESSION['fate_admin_member_id'] > 0;
    } elseif (session_status() === PHP_SESSION_ACTIVE) {
        if (!headers_sent()) {
            session_write_close();
        }
    }

    if (session_status() !== PHP_SESSION_NONE) {
        return $cached = false;
    }

    if (!isset($_COOKIE['fate_admin']) || $_COOKIE['fate_admin'] === '') {
        return $cached = false;
    }

    if (headers_sent()) {
        return $cached = false;
    }

    require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_member_session_bridge.php';
    fate_admin_session_start();
    $ok = fate_admin_is_logged_in();
    session_write_close();

    return $cached = $ok;
}
