<?php

declare(strict_types=1);

/**
 * 技師本週推薦榜主內容。
 *
 * @var list<array<string,mixed>> $weeklyRankRows
 * @var list<string> $weeklyRankCities
 * @var list<string> $weeklyAvailableWeeks
 * @var list<array<string,mixed>> $memberWeeklyRecords
 * @var array{used:int,max:int,recommended_ids:list<int>} $memberWeeklyUsage
 * @var array{items:list<array<string,mixed>>,total:int} $adminWeeklyRecords
 * @var Closure $buildWeeklyQuery
 * @var string $listingFilter
 * @var string $cityFilter
 * @var string $viewWeek
 * @var string $currentWeek
 * @var string $weeklyStatsRangeLabel
 * @var bool $isCurrentWeek
 * @var bool $showAdminLog
 * @var bool $viewerIsStaff
 * @var int $adminRecordsPage
 * @var int $rankLimit
 * @var string $msgOk
 * @var string $msgBad
 * @var string $csrf
 * @var array{id:int,username:string,display_name:string,avatar_rel:string}|null $fatePublicMember
 * @var PDO|null $pdo
 */

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

$genderSymbols = ['female' => '♀', 'male' => '♂', 'other' => '☻'];
$isMobileTab = $listingFilter === FATE_STORE_LISTING_MOBILE;
$listingLabels = fate_store_listing_labels();
$memberId = is_array($fatePublicMember ?? null) ? (int) ($fatePublicMember['id'] ?? 0) : 0;
$memberLoggedIn = $memberId > 0;
$canInteract = $memberLoggedIn && $pdo instanceof PDO && fate_public_member_can_interact($pdo);
$loginNext = rawurlencode('masseur_weekly.php');

try {
    $prevWeek = (new DateTimeImmutable($viewWeek))->modify('-7 days')->format('Y-m-d');
    $nextWeek = (new DateTimeImmutable($viewWeek))->modify('+7 days')->format('Y-m-d');
} catch (Throwable) {
    $prevWeek = $viewWeek;
    $nextWeek = $viewWeek;
}
$canGoNextWeek = $nextWeek <= $currentWeek;
$weeklyAvailableWeeks = is_array($weeklyAvailableWeeks ?? null) && ($weeklyAvailableWeeks ?? []) !== []
    ? $weeklyAvailableWeeks
    : [$viewWeek];
?>
<section class="masseur-weekly-page" aria-labelledby="masseur-weekly-title">
    <header class="masseur-weekly-page__head">
        <h1 id="masseur-weekly-title" class="masseur-weekly-page__title">
            <?= $isCurrentWeek ? '技師本週推薦榜' : '技師週推薦榜（歷史）' ?>
        </h1>
        <?php if ($weeklyStatsRangeLabel !== ''): ?>
            <p class="masseur-weekly-page__sub">
                <?= htmlspecialchars($weeklyStatsRangeLabel, ENT_QUOTES, 'UTF-8') ?>
                <?php if ($isCurrentWeek): ?>
                    · 每週一 00:00 重置
                <?php else: ?>
                    · <span class="masseur-weekly-page__hist-badge">歷史週次</span>
                <?php endif; ?>
            </p>
        <?php endif; ?>
        <?php if ($isCurrentWeek && $memberLoggedIn): ?>
            <p class="masseur-weekly-page__quota" role="status">
                本週已推薦 <strong><?= (int) $memberWeeklyUsage['used'] ?></strong> / <?= (int) $memberWeeklyUsage['max'] ?> 位
            </p>
        <?php endif; ?>
    </header>

    <?php if ($msgOk !== ''): ?>
        <div class="sync-banner sync-banner--ok masseur-weekly-flash" role="status"><?= htmlspecialchars($msgOk, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>
    <?php if ($msgBad !== ''): ?>
        <div class="sync-banner sync-banner--bad masseur-weekly-flash" role="alert"><?= htmlspecialchars($msgBad, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <nav class="masseur-weekly-tabs" aria-label="店家類型">
        <?php foreach ([FATE_STORE_LISTING_FIXED, FATE_STORE_LISTING_MOBILE] as $lk): ?>
            <a class="masseur-weekly-tabs__tab<?= $listingFilter === $lk ? ' is-active' : '' ?>"
               href="<?= htmlspecialchars($buildWeeklyQuery(['listing' => $lk, 'page' => null, 'alog' => null, 'log' => null]), ENT_QUOTES, 'UTF-8') ?>"
               <?= $listingFilter === $lk ? ' aria-current="page"' : '' ?>>
                <?= htmlspecialchars($listingLabels[$lk] ?? $lk, ENT_QUOTES, 'UTF-8') ?> TOP<?= (int) $rankLimit ?>
            </a>
        <?php endforeach; ?>
    </nav>

    <div class="masseur-weekly-toolbar">
        <form method="get" action="masseur_weekly.php" class="masseur-weekly-filter masseur-weekly-filter--week">
            <?php if ($listingFilter !== FATE_STORE_LISTING_FIXED): ?>
                <input type="hidden" name="listing" value="<?= htmlspecialchars($listingFilter, ENT_QUOTES, 'UTF-8') ?>">
            <?php endif; ?>
            <?php if ($cityFilter !== ''): ?>
                <input type="hidden" name="city" value="<?= htmlspecialchars($cityFilter, ENT_QUOTES, 'UTF-8') ?>">
            <?php endif; ?>
            <label class="masseur-weekly-filter__label" for="masseur-weekly-week">週次</label>
            <select name="week" id="masseur-weekly-week" class="masseur-weekly-filter__select masseur-weekly-filter__select--week" onchange="this.form.submit()">
                <?php foreach ($weeklyAvailableWeeks as $wk): ?>
                    <?php
                    $wkLabel = fate_masseur_weekly_stats_range_label($wk);
                    if ($wk === $currentWeek) {
                        $wkLabel .= '（本週）';
                    }
                    ?>
                    <option value="<?= htmlspecialchars($wk, ENT_QUOTES, 'UTF-8') ?>"<?= $viewWeek === $wk ? ' selected' : '' ?>><?= htmlspecialchars($wkLabel, ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
            </select>
        </form>

        <?php if ($weeklyRankCities !== []): ?>
            <form method="get" action="masseur_weekly.php" class="masseur-weekly-filter">
                <?php if ($listingFilter !== FATE_STORE_LISTING_FIXED): ?>
                    <input type="hidden" name="listing" value="<?= htmlspecialchars($listingFilter, ENT_QUOTES, 'UTF-8') ?>">
                <?php endif; ?>
                <?php if ($viewWeek !== $currentWeek): ?>
                    <input type="hidden" name="week" value="<?= htmlspecialchars($viewWeek, ENT_QUOTES, 'UTF-8') ?>">
                <?php endif; ?>
                <label class="masseur-weekly-filter__label" for="masseur-weekly-city">縣市</label>
                <select name="city" id="masseur-weekly-city" class="masseur-weekly-filter__select" onchange="this.form.submit()">
                    <option value="">全部縣市</option>
                    <?php foreach ($weeklyRankCities as $c): ?>
                        <option value="<?= htmlspecialchars($c, ENT_QUOTES, 'UTF-8') ?>"<?= $cityFilter === $c ? ' selected' : '' ?>><?= htmlspecialchars($c, ENT_QUOTES, 'UTF-8') ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
        <?php endif; ?>

        <nav class="masseur-weekly-weeknav" aria-label="週次">
            <a class="masseur-weekly-weeknav__link" href="<?= htmlspecialchars($buildWeeklyQuery(['week' => $prevWeek, 'alog' => null, 'log' => null]), ENT_QUOTES, 'UTF-8') ?>">← 上週</a>
            <?php if (!$isCurrentWeek): ?>
                <a class="masseur-weekly-weeknav__link" href="<?= htmlspecialchars($buildWeeklyQuery(['week' => $currentWeek, 'alog' => null, 'log' => null]), ENT_QUOTES, 'UTF-8') ?>">本週</a>
            <?php endif; ?>
            <?php if ($canGoNextWeek): ?>
                <a class="masseur-weekly-weeknav__link" href="<?= htmlspecialchars($buildWeeklyQuery(['week' => $nextWeek, 'alog' => null, 'log' => null]), ENT_QUOTES, 'UTF-8') ?>">下週 →</a>
            <?php endif; ?>
        </nav>
    </div>

    <?php if ($weeklyRankRows === []): ?>
        <p class="masseur-weekly-empty">此週尚無<?= htmlspecialchars($listingLabels[$listingFilter] ?? '', ENT_QUOTES, 'UTF-8') ?>技師推薦紀錄。</p>
    <?php else: ?>
        <ol class="masseur-weekly-rank">
            <?php foreach ($weeklyRankRows as $ri => $row): ?>
                <?php
                $mid = (int) ($row['masseur_id'] ?? 0);
                $storeId = (int) ($row['spa_store_id'] ?? 0);
                $mName = (string) ($row['masseur_name'] ?? '');
                $mGender = (string) ($row['gender'] ?? 'female');
                $photoUrl = fate_masseur_resolve_photo_public_url((string) ($row['photo_rel'] ?? ''), $mGender);
                $storeName = (string) ($row['store_name'] ?? '');
                $city = (string) ($row['city_name'] ?? '');
                $district = (string) ($row['district_name'] ?? '');
                $loc = trim($city . ($district !== '' ? ' ' . $district : ''));
                $recCount = (int) ($row['week_recommends'] ?? 0);
                $viewerRecommended = in_array($mid, $memberWeeklyUsage['recommended_ids'] ?? [], true);
                ?>
                <li class="masseur-weekly-rank__item">
                    <span class="masseur-weekly-rank__num" aria-label="第 <?= (int) $ri + 1 ?> 名">#<?= (int) $ri + 1 ?></span>
                    <?php if ($photoUrl !== null): ?>
                        <img class="masseur-weekly-rank__avatar" src="<?= htmlspecialchars($photoUrl, ENT_QUOTES, 'UTF-8') ?>" alt="" width="56" height="56" loading="lazy">
                    <?php else: ?>
                        <span class="masseur-weekly-rank__avatar masseur-weekly-rank__avatar--empty" aria-hidden="true"><?= htmlspecialchars($genderSymbols[$mGender] ?? '♀', ENT_QUOTES, 'UTF-8') ?></span>
                    <?php endif; ?>
                    <div class="masseur-weekly-rank__body">
                        <p class="masseur-weekly-rank__name">
                            <?= htmlspecialchars($mName, ENT_QUOTES, 'UTF-8') ?>
                            <span class="masseur-weekly-rank__gender" aria-hidden="true"><?= htmlspecialchars($genderSymbols[$mGender] ?? '', ENT_QUOTES, 'UTF-8') ?></span>
                        </p>
                        <p class="masseur-weekly-rank__store">
                            <?php if ($storeId > 0): ?>
                                <a href="store.php?id=<?= $storeId ?>" class="text-accent-link"><?= htmlspecialchars($storeName !== '' ? $storeName : ('店家 #' . $storeId), ENT_QUOTES, 'UTF-8') ?></a>
                            <?php else: ?>
                                <?= htmlspecialchars($storeName, ENT_QUOTES, 'UTF-8') ?>
                            <?php endif; ?>
                            <?php if ($loc !== ''): ?>
                                <span class="masseur-weekly-rank__loc"> · <?= htmlspecialchars($loc, ENT_QUOTES, 'UTF-8') ?></span>
                            <?php endif; ?>
                        </p>
                        <p class="masseur-weekly-rank__count">本週推薦 <strong><?= number_format($recCount) ?></strong> 次</p>
                    </div>
                    <div class="masseur-weekly-rank__action">
                        <?php if ($isCurrentWeek && $canInteract && !$viewerRecommended && (int) $memberWeeklyUsage['used'] < (int) $memberWeeklyUsage['max']): ?>
                            <form method="post" action="api/masseur_action.php" class="masseur-weekly-rank__form">
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="weekly_recommend">
                                <input type="hidden" name="store_id" value="<?= $storeId ?>">
                                <input type="hidden" name="masseur_id" value="<?= $mid ?>">
                                <input type="hidden" name="return_to" value="<?= htmlspecialchars($buildWeeklyQuery([]), ENT_QUOTES, 'UTF-8') ?>">
                                <button type="submit" class="masseur-weekly-btn" title="本週推薦">⭐ 推薦</button>
                            </form>
                        <?php elseif ($isCurrentWeek && $viewerRecommended): ?>
                            <span class="masseur-weekly-btn is-active is-static">已推薦</span>
                        <?php elseif ($isCurrentWeek && !$memberLoggedIn): ?>
                            <a class="masseur-weekly-btn masseur-weekly-btn--link" href="login.php?next=<?= $loginNext ?>">登入推薦</a>
                        <?php endif; ?>
                    </div>
                </li>
            <?php endforeach; ?>
        </ol>
    <?php endif; ?>

    <?php if ($memberLoggedIn): ?>
        <section class="masseur-weekly-records" aria-labelledby="masseur-weekly-my-records">
            <h2 id="masseur-weekly-my-records" class="masseur-weekly-records__title">
                <?= $isCurrentWeek ? '我的本週推薦紀錄' : '我在此週的推薦紀錄' ?>
            </h2>
            <?php if ($memberWeeklyRecords === []): ?>
                <p class="masseur-weekly-empty masseur-weekly-empty--small">
                    <?php if ($isCurrentWeek): ?>
                        您本週尚未推薦任何技師。可至<a href="./" class="text-accent-link">探索列表</a>進入店家頁推薦。
                    <?php else: ?>
                        此週您沒有推薦紀錄。
                    <?php endif; ?>
                </p>
            <?php else: ?>
                <ul class="masseur-weekly-records__list">
                    <?php foreach ($memberWeeklyRecords as $rec): ?>
                        <?php
                        $mid = (int) ($rec['masseur_id'] ?? 0);
                        $storeId = (int) ($rec['spa_store_id'] ?? 0);
                        $at = (string) ($rec['created_at'] ?? '');
                        ?>
                        <li class="masseur-weekly-records__item">
                            <span class="masseur-weekly-records__name"><?= htmlspecialchars((string) ($rec['masseur_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></span>
                            <?php if ($storeId > 0): ?>
                                · <a href="store.php?id=<?= $storeId ?>#masseur-<?= $mid ?>" class="text-accent-link"><?= htmlspecialchars((string) ($rec['store_name'] ?? '店家'), ENT_QUOTES, 'UTF-8') ?></a>
                            <?php endif; ?>
                            <?php if ($at !== ''): ?>
                                <time class="masseur-weekly-records__time" datetime="<?= htmlspecialchars(substr($at, 0, 19), ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars(substr($at, 5, 11), ENT_QUOTES, 'UTF-8') ?></time>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </section>
    <?php endif; ?>

    <?php if ($viewerIsStaff): ?>
        <section class="masseur-weekly-admin" aria-labelledby="masseur-weekly-admin-log">
            <h2 id="masseur-weekly-admin-log" class="masseur-weekly-records__title">站方紀錄查詢</h2>
            <?php if (!$showAdminLog): ?>
                <p class="masseur-weekly-empty masseur-weekly-empty--small">
                    <a href="<?= htmlspecialchars($buildWeeklyQuery(['log' => 'all', 'alog' => 1]), ENT_QUOTES, 'UTF-8') ?>" class="text-accent-link">查看此週全部推薦紀錄</a>
                </p>
            <?php else: ?>
                <?php if (($adminWeeklyRecords['items'] ?? []) === []): ?>
                    <p class="masseur-weekly-empty masseur-weekly-empty--small">此週尚無推薦紀錄。</p>
                <?php else: ?>
                    <div class="masseur-weekly-admin-table-wrap">
                        <table class="masseur-weekly-admin-table">
                            <thead>
                                <tr>
                                    <th scope="col">時間</th>
                                    <th scope="col">會員</th>
                                    <th scope="col">技師</th>
                                    <th scope="col">店家</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($adminWeeklyRecords['items'] as $ar): ?>
                                    <tr>
                                        <td><?= htmlspecialchars(substr((string) ($ar['created_at'] ?? ''), 0, 16), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars((string) (($ar['display_name'] ?? '') !== '' ? $ar['display_name'] : ($ar['username'] ?? '')), ENT_QUOTES, 'UTF-8') ?></td>
                                        <td><?= htmlspecialchars((string) ($ar['masseur_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?> #<?= (int) ($ar['masseur_id'] ?? 0) ?></td>
                                        <td><?= htmlspecialchars((string) ($ar['store_name'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php
                    $adminTotal = (int) ($adminWeeklyRecords['total'] ?? 0);
                    $adminPages = max(1, (int) ceil($adminTotal / 50));
                    if ($adminPages > 1):
                        ?>
                        <nav class="masseur-weekly-admin-pager" aria-label="紀錄分頁">
                            <?php for ($ap = 1; $ap <= $adminPages; $ap++): ?>
                                <?php if ($ap === $adminRecordsPage): ?>
                                    <span class="masseur-weekly-admin-pager__cur"><?= $ap ?></span>
                                <?php else: ?>
                                    <a href="<?= htmlspecialchars($buildWeeklyQuery(['log' => 'all', 'alog' => $ap]), ENT_QUOTES, 'UTF-8') ?>"><?= $ap ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                        </nav>
                    <?php endif; ?>
                <?php endif; ?>
            <?php endif; ?>
        </section>
    <?php endif; ?>
</section>
