<?php

declare(strict_types=1);

/**
 * 手機版：整合頂欄導覽與側欄會員區，固定於螢幕下方。
 */

require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';

function fate_mobile_member_bar_stylesheet_tag(string $hrefPrefix = './'): string
{
    $cssFs = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'fate-mobile-bar.css';
    $ver = is_file($cssFs) ? (string) filemtime($cssFs) : '1';
    $href = rtrim($hrefPrefix, '/') . '/static/fate-mobile-bar.css?v=' . rawurlencode($ver);

    return '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">';
}

function fate_mobile_type_stylesheet_tag(string $hrefPrefix = './'): string
{
    $cssFs = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'fate-mobile-type.css';
    $ver = is_file($cssFs) ? (string) filemtime($cssFs) : '1';
    $href = rtrim($hrefPrefix, '/') . '/static/fate-mobile-type.css?v=' . rawurlencode($ver);

    return '<link rel="stylesheet" href="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '">';
}

function fate_mobile_frontend_stylesheet_tags(string $hrefPrefix = './'): string
{
    return fate_mobile_member_bar_stylesheet_tag($hrefPrefix) . "\n    "
        . fate_mobile_type_stylesheet_tag($hrefPrefix);
}

function fate_mobile_member_bar_script_tag(string $hrefPrefix = './'): string
{
    $jsFs = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'static' . DIRECTORY_SEPARATOR . 'fate-mobile-bar.js';
    $ver = is_file($jsFs) ? (string) filemtime($jsFs) : '1';
    $href = rtrim($hrefPrefix, '/') . '/static/fate-mobile-bar.js?v=' . rawurlencode($ver);

    return '<script src="' . htmlspecialchars($href, ENT_QUOTES, 'UTF-8') . '" defer></script>';
}

/** @return list<array{id:string,label:string,href:string,active:bool}> */
function fate_mobile_member_bar_nav_items(
    string $urlPrefix,
    bool $forumVisible,
    bool $boardModVisible,
    string $boardModHref,
    bool $loggedIn,
    bool $adminNavVisible,
    string $loginNextQ,
    bool $profileActive,
    bool $forumAdminVisible = false,
    string $forumAdminHref = ''
): array {
    $prefix = rtrim($urlPrefix, '/') . '/';
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    $isForum = str_contains($script, '/forum/');
    $isHome = !$isForum && (basename($script) === 'index.php' || $script === '' || str_ends_with($script, '/'));
    $isMemberProfile = str_contains($script, 'member_profile.php');
    $isForumAdmin = str_contains($script, '/forum/admin/');

    $hasSearchQ = $isHome
        && isset($_GET['q'])
        && trim((string) $_GET['q']) !== '';

    $items = [
        [
            'id' => 'explore',
            'label' => '探索',
            'href' => $prefix,
            'active' => $isHome && !$hasSearchQ,
        ],
        [
            'id' => 'search',
            'label' => '搜尋',
            'href' => '',
            'active' => $hasSearchQ,
            'action' => 'search',
        ],
    ];
    if ($forumVisible) {
        $items[] = [
            'id' => 'forum',
            'label' => '討論區',
            'href' => $prefix . 'forum/',
            'active' => $isForum && !$isMemberProfile && !$isForumAdmin,
        ];
    }
    if ($loggedIn) {
        $items[] = [
            'id' => 'account',
            'label' => '帳號',
            'href' => $prefix . 'member_profile.php',
            'active' => $isMemberProfile,
        ];
    } else {
        $items[] = [
            'id' => 'login',
            'label' => '登入',
            'href' => $prefix . 'login.php?next=' . $loginNextQ,
            'active' => str_contains($script, 'login.php'),
        ];
    }
    if ($boardModVisible && $boardModHref !== '') {
        $items[] = [
            'id' => 'board_mod',
            'label' => '版主',
            'href' => $boardModHref,
            'active' => str_contains($script, 'board_mod.php'),
        ];
    }
    if ($forumAdminVisible && $forumAdminHref !== '') {
        $items[] = [
            'id' => 'forum_admin',
            'label' => '論壇管理',
            'href' => $forumAdminHref,
            'active' => $isForumAdmin,
        ];
    }
    if ($adminNavVisible) {
        $items[] = [
            'id' => 'admin',
            'label' => '後台',
            'href' => $prefix . 'admin/',
            'active' => str_contains($script, '/admin/') && !$isForumAdmin,
        ];
    }

    return $items;
}

/**
 * @return array{action:string,q:string,hidden:array<string,string>}
 */
function fate_mobile_member_bar_search_form(string $urlPrefix): array
{
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    $isForum = str_contains($script, '/forum/');
    $isHome = !$isForum && (basename($script) === 'index.php' || $script === '' || str_ends_with($script, '/'));
    $prefix = rtrim($urlPrefix, '/') . '/';

    $q = '';
    /** @var array<string,string> $hidden */
    $hidden = ['page' => '1'];

    if ($isHome) {
        $q = isset($_GET['q']) ? trim((string) $_GET['q']) : '';
        if (strlen($q) > 120) {
            $q = substr($q, 0, 120);
        }

        $city = isset($_GET['city']) ? trim((string) $_GET['city']) : '';
        if ($city !== '' && strlen($city) <= 120) {
            $hidden['city'] = $city;
        }

        $sort = isset($_GET['sort']) ? strtolower(trim((string) $_GET['sort'])) : 'rating';
        if (in_array($sort, ['rating', 'name', 'recent'], true) && $sort !== 'rating') {
            $hidden['sort'] = $sort;
        }

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_store_listing.php';
        $listing = isset($_GET['listing']) ? fate_store_listing_normalize_tab((string) $_GET['listing']) : FATE_STORE_LISTING_FIXED;
        if ($listing === FATE_STORE_LISTING_MOBILE) {
            $hidden['listing'] = 'mobile';
        }
    }

    return [
        'action' => $prefix . 'index.php',
        'q' => $q,
        'hidden' => $hidden,
    ];
}

/**
 * @param array<string,mixed> $options
 * @return array<string,mixed>
 */
function fate_mobile_member_bar_context(array $options = []): array
{
    $urlPrefix = isset($options['urlPrefix']) && is_string($options['urlPrefix']) ? $options['urlPrefix'] : './';
    $member = $options['member'] ?? ($GLOBALS['fatePublicMember'] ?? null);
    if (!is_array($member)) {
        $member = null;
    }

    $pdo = $options['pdo'] ?? ($GLOBALS['pdo'] ?? null);
    if (!$pdo instanceof PDO) {
        $pdo = null;
    }

    $forumVisible = !empty($options['forumVisible'] ?? ($GLOBALS['fateForumNavVisible'] ?? false));
    if (!$forumVisible && $pdo instanceof PDO) {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_plugins.php';
        $forumVisible = fate_store_forum_plugin_active();
    }

    $adminNavVisible = !empty($options['adminNavVisible'] ?? ($GLOBALS['fateAdminNavVisible'] ?? false));
    $boardModVisible = !empty($options['boardModVisible']);
    $boardModHref = isset($options['boardModHref']) && is_string($options['boardModHref']) ? $options['boardModHref'] : '';

    $loginNext = isset($options['loginNext']) && is_string($options['loginNext']) && trim($options['loginNext']) !== ''
        ? trim($options['loginNext'])
        : fate_public_login_next_from_request($urlPrefix === '../' ? '../' : './');
    $loginNextQ = rawurlencode($loginNext);

    $prefix = rtrim($urlPrefix, '/') . '/';
    $avatarUrl = null;
    $memberLabel = '';
    $memberUsername = '';
    $memberNcoin = null;
    $loggedIn = $member !== null;

    if ($loggedIn) {
        $avatarUrl = fate_member_profile_avatar_url((string) ($member['avatar_rel'] ?? ''));
        if ($avatarUrl !== null && str_starts_with($avatarUrl, './') && str_starts_with($urlPrefix, '../')) {
            $avatarUrl = '../' . substr($avatarUrl, 2);
        }
        $memberLabel = fate_public_member_display_label($member);
        $memberUsername = (string) ($member['username'] ?? '');
        if ($pdo instanceof PDO) {
            require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_member_account.php';
            $memberNcoin = fate_member_read_ncoin($pdo, (int) ($member['id'] ?? 0), $memberUsername);
        }
    }

    $profileActive = str_contains(str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? '')), 'member_profile.php');

    require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';
    $brand = fate_public_site_branding();
    $forumAdminVisible = !empty($options['forumAdminVisible']);
    $forumAdminHref = isset($options['forumAdminHref']) && is_string($options['forumAdminHref']) ? $options['forumAdminHref'] : '';

    $searchForm = fate_mobile_member_bar_search_form($urlPrefix);

    require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_ncoin_settings.php';
    $ncoinName = fate_ncoin_display_name();

    return [
        'urlPrefix' => $urlPrefix,
        'prefix' => $prefix,
        'searchForm' => $searchForm,
        'brandMain' => (string) ($brand['title_main'] ?? 'FATE'),
        'brandSub' => (string) ($brand['title_sub'] ?? ''),
        'member' => $member,
        'loggedIn' => $loggedIn,
        'avatarUrl' => $avatarUrl,
        'memberLabel' => $memberLabel,
        'memberUsername' => $memberUsername,
        'memberNcoin' => $memberNcoin,
        'ncoinName' => $ncoinName,
        'forumVisible' => $forumVisible,
        'adminNavVisible' => $adminNavVisible,
        'loginNextQ' => $loginNextQ,
        'profileActive' => $profileActive,
        'navItems' => fate_mobile_member_bar_nav_items(
            $urlPrefix,
            $forumVisible,
            $boardModVisible,
            $boardModHref,
            $loggedIn,
            $adminNavVisible,
            $loginNextQ,
            $profileActive,
            $forumAdminVisible,
            $forumAdminHref
        ),
    ];
}

/** @param array<string,mixed> $options */
function fate_mobile_member_bar_emit_footer(array $options = []): void
{
    if (!empty($GLOBALS['fate_mobile_member_bar_emitted'])) {
        return;
    }
    $GLOBALS['fate_mobile_member_bar_emitted'] = true;

    $urlPrefix = isset($options['urlPrefix']) && is_string($options['urlPrefix']) ? $options['urlPrefix'] : './';

    if (!array_key_exists('forumVisible', $options)) {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_plugins.php';
        $options['forumVisible'] = fate_store_forum_plugin_active();
    }
    if (!array_key_exists('adminNavVisible', $options)) {
        require_once __DIR__ . DIRECTORY_SEPARATOR . 'fate_admin_nav_visibility.php';
        $options['adminNavVisible'] = fate_admin_nav_visible_for_frontend();
    }
    if (!array_key_exists('pdo', $options) && isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) {
        $options['pdo'] = $GLOBALS['pdo'];
    }
    if (!array_key_exists('member', $options)) {
        $options['member'] = $GLOBALS['fatePublicMember'] ?? null;
        if ($options['member'] === null) {
            $options['member'] = fate_public_member_current();
        }
    }
    if (!isset($options['loginNext']) || !is_string($options['loginNext']) || trim($options['loginNext']) === '') {
        $options['loginNext'] = fate_public_login_next_from_request($urlPrefix === '../' ? '../' : './');
    }

    fate_mobile_member_bar_render($options);
    echo fate_mobile_member_bar_script_tag($urlPrefix);
}

/** @param array<string,mixed> $options */
function fate_mobile_member_bar_render(array $options = []): void
{
    if (!empty($options['skip'])) {
        return;
    }
    $ctx = fate_mobile_member_bar_context($options);
    $partial = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'default' . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'mobile_member_bar.php';
    if (!is_file($partial)) {
        return;
    }
    extract($ctx, EXTR_SKIP);
    require $partial;
}
