<?php

declare(strict_types=1);

/**
 * 側欄：技師本週推薦榜 TOP10（定點／非定點 TAB）。
 *
 * @var PDO|null $pdo
 */

if (!isset($pdo) || !($pdo instanceof PDO)) {
    return;
}

require_once dirname(__DIR__, 3) . '/includes/fate_masseur_weekly_recommend.php';
require_once dirname(__DIR__, 3) . '/includes/fate_masseur_image.php';
require_once dirname(__DIR__, 3) . '/includes/fate_store_listing.php';

if (!fate_masseur_weekly_recommend_enabled()) {
    return;
}

$sidebarWeeklyWeek = fate_masseur_weekly_recommend_week_date();
$sidebarWeeklyLimit = fate_masseur_weekly_sidebar_rank_limit();
$sidebarWeeklyRange = fate_masseur_weekly_stats_range_label($sidebarWeeklyWeek);
$sidebarWeeklyTab = isset($sidebarWeeklyListingTab)
    ? fate_store_listing_normalize_tab((string) $sidebarWeeklyListingTab)
    : FATE_STORE_LISTING_FIXED;

fate_masseur_weekly_recommend_ensure_table($pdo);
$sidebarWeeklyFixed = fate_masseur_weekly_rank_fetch($pdo, $sidebarWeeklyWeek, FATE_STORE_LISTING_FIXED, null, $sidebarWeeklyLimit);
$sidebarWeeklyMobile = fate_masseur_weekly_rank_fetch($pdo, $sidebarWeeklyWeek, FATE_STORE_LISTING_MOBILE, null, $sidebarWeeklyLimit);
$listingLabels = fate_store_listing_labels();
$genderSymbols = ['female' => '♀', 'male' => '♂', 'other' => '☻'];

/** @param list<array<string,mixed>> $rows */
$renderSidebarWeeklyRows = static function (array $rows) use ($genderSymbols): void {
    foreach ($rows as $row) {
        $mid = (int) ($row['masseur_id'] ?? 0);
        $storeId = (int) ($row['spa_store_id'] ?? 0);
        $mName = (string) ($row['masseur_name'] ?? '');
        $mGender = (string) ($row['gender'] ?? 'female');
        $recCount = (int) ($row['week_recommends'] ?? 0);
        $photoUrl = fate_masseur_resolve_photo_public_url((string) ($row['photo_rel'] ?? ''), $mGender);
        $href = $storeId > 0 ? ('store.php?id=' . $storeId . '#masseur-' . $mid) : 'masseur_weekly.php';

        $storeName = trim((string) ($row['store_name'] ?? ''));
        if ($storeName === '' && $storeId > 0) {
            $storeName = '店家 #' . $storeId;
        }
        $city = trim((string) ($row['city_name'] ?? ''));
        $district = trim((string) ($row['district_name'] ?? ''));
        $storeLoc = $city;
        if ($district !== '' && $district !== $city) {
            $storeLoc = trim($city . ' ' . $district);
        }

        $linkTitle = $storeName !== ''
            ? ($mName . ' · ' . $storeName)
            : $mName;
        ?>
        <li class="sidebar-weekly-rank__item">
            <a class="sidebar-weekly-rank__link" href="<?= htmlspecialchars($href, ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars($linkTitle, ENT_QUOTES, 'UTF-8') ?>">
                <span class="sidebar-weekly-rank__media" aria-hidden="true">
                    <?php if ($photoUrl !== null): ?>
                        <img class="sidebar-weekly-rank__avatar" src="<?= htmlspecialchars($photoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="" width="36" height="36" loading="lazy" decoding="async">
                    <?php else: ?>
                        <span class="sidebar-weekly-rank__avatar sidebar-weekly-rank__avatar--empty"><?= htmlspecialchars($genderSymbols[$mGender] ?? '♀', ENT_QUOTES, 'UTF-8') ?></span>
                    <?php endif; ?>
                </span>
                <span class="sidebar-weekly-rank__body">
                    <span class="sidebar-weekly-rank__name-row">
                        <span class="sidebar-weekly-rank__name"><?= htmlspecialchars($mName, ENT_QUOTES, 'UTF-8') ?></span>
                        <span class="sidebar-weekly-rank__gender" aria-hidden="true"><?= htmlspecialchars($genderSymbols[$mGender] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                    </span>
                    <?php if ($storeName !== ''): ?>
                        <span class="sidebar-weekly-rank__store" title="<?= htmlspecialchars($storeName, ENT_QUOTES, 'UTF-8') ?>">
                            <span class="sidebar-weekly-rank__store-label">店家</span>
                            <span class="sidebar-weekly-rank__store-name"><?= htmlspecialchars($storeName, ENT_QUOTES, 'UTF-8') ?></span>
                        </span>
                    <?php endif; ?>
                    <?php if ($storeLoc !== ''): ?>
                        <span class="sidebar-weekly-rank__loc"><?= htmlspecialchars($storeLoc, ENT_QUOTES, 'UTF-8') ?></span>
                    <?php endif; ?>
                </span>
                <span class="sidebar-weekly-rank__badge" aria-label="本週推薦 <?= (int) $recCount ?> 次">
                    <span class="sidebar-weekly-rank__badge-star" aria-hidden="true">⭐</span>
                    <span class="sidebar-weekly-rank__badge-n"><?= number_format($recCount) ?></span>
                </span>
            </a>
        </li>
        <?php
    }
};
?>
<div class="sidebar-card sidebar-card--masseur-weekly">
    <div class="sidebar-weekly-head">
        <p class="sidebar-title sidebar-title--weekly">技師週推榜</p>
        <?php if ($sidebarWeeklyRange !== ''): ?>
            <p class="sidebar-weekly-head__range" title="<?= htmlspecialchars($sidebarWeeklyRange, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($sidebarWeeklyRange, ENT_QUOTES, 'UTF-8') ?></p>
        <?php endif; ?>
    </div>
    <nav class="sidebar-weekly-tabs" aria-label="週推榜類型">
        <?php foreach ([FATE_STORE_LISTING_FIXED, FATE_STORE_LISTING_MOBILE] as $lk): ?>
            <button type="button"
                    class="sidebar-weekly-tabs__tab<?= $sidebarWeeklyTab === $lk ? ' is-active' : '' ?>"
                    data-sidebar-weekly-tab="<?= htmlspecialchars($lk, ENT_QUOTES, 'UTF-8') ?>"
                    aria-pressed="<?= $sidebarWeeklyTab === $lk ? 'true' : 'false' ?>">
                <?= htmlspecialchars($listingLabels[$lk] ?? $lk, ENT_QUOTES, 'UTF-8') ?>
            </button>
        <?php endforeach; ?>
    </nav>

    <?php foreach ([FATE_STORE_LISTING_FIXED => $sidebarWeeklyFixed, FATE_STORE_LISTING_MOBILE => $sidebarWeeklyMobile] as $lk => $rows): ?>
        <ol class="sidebar-weekly-rank<?= $sidebarWeeklyTab === $lk ? ' is-active' : '' ?>"
            data-sidebar-weekly-panel="<?= htmlspecialchars($lk, ENT_QUOTES, 'UTF-8') ?>"
            <?= $sidebarWeeklyTab !== $lk ? ' hidden' : '' ?>>
            <?php if ($rows === []): ?>
                <li class="sidebar-weekly-rank__empty">本週尚無資料</li>
            <?php else: ?>
                <?php $renderSidebarWeeklyRows($rows); ?>
            <?php endif; ?>
        </ol>
    <?php endforeach; ?>

    <div class="sidebar-actions sidebar-actions--weekly">
        <a class="sidebar-btn sidebar-btn--weekly" href="masseur_weekly.php">完整週榜 →</a>
    </div>
</div>
<script>
(function () {
    var root = document.querySelector('.sidebar-card--masseur-weekly');
    if (!root) return;
    var tabs = root.querySelectorAll('[data-sidebar-weekly-tab]');
    var panels = root.querySelectorAll('[data-sidebar-weekly-panel]');
    tabs.forEach(function (tab) {
        tab.addEventListener('click', function () {
            var id = tab.getAttribute('data-sidebar-weekly-tab');
            tabs.forEach(function (t) {
                var on = t === tab;
                t.classList.toggle('is-active', on);
                t.setAttribute('aria-pressed', on ? 'true' : 'false');
            });
            panels.forEach(function (p) {
                var on = p.getAttribute('data-sidebar-weekly-panel') === id;
                p.classList.toggle('is-active', on);
                if (on) p.removeAttribute('hidden'); else p.setAttribute('hidden', '');
            });
        });
    });
})();
</script>
