<?php

declare(strict_types=1);

/**
 * 會員頁 — 收藏技師分頁。
 *
 * @var list<array<string,mixed>> $memberFavorites
 * @var bool $memberFavoritesPublic
 * @var int $memberFavoritesCount
 * @var array $favMasseurTagPayload
 * @var bool $favReviewsEnabled
 * @var bool $favCanInteract
 * @var bool $favForumActive
 * @var bool $favCanViewReviews
 * @var bool $favCanViewTags
 * @var bool $favTagInteract
 * @var bool $favHasTags
 * @var bool $favTagsFormalOnly
 * @var bool $favCanAccessTagsFormal
 * @var string $favReturnTo
 * @var int $favReviewsPerPage
 * @var Closure(int,int):string $buildFavReviewPageUrl
 * @var array{id:int,username:string,display_name:string,avatar_rel:string} $member
 * @var string $csrf
 */

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

$favGenders = fate_masseur_gender_labels();
$favPublicUrl = 'member_favorites_public.php?member=' . (int) ($member['id'] ?? 0);

?>
<div class="member-profile-tab-panel__inner">
    <div class="member-fav-head">
        <div>
            <h3 class="member-profile-tab-subtitle">收藏技師</h3>
            <p class="sub member-profile-hint">記錄您感興趣的技師；可標記是否已體驗，並使用標籤與文字評論分享心得。</p>
        </div>
        <form method="post" action="member_profile.php?tab=favorites" class="member-fav-public-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="action" value="favorites_public">
            <label>
                <input type="checkbox" name="is_public" value="1"<?= !empty($memberFavoritesPublic) ? ' checked' : '' ?>>
                對外公開收藏清單
            </label>
            <button type="submit" class="member-profile-btn member-profile-btn--sm">儲存設定</button>
        </form>
    </div>
    <?php if (!empty($memberFavoritesPublic)): ?>
        <p class="member-fav-public-link">公開連結：<a href="<?= htmlspecialchars($favPublicUrl, ENT_QUOTES, 'UTF-8') ?>" class="text-accent-link"><?= htmlspecialchars($favPublicUrl, ENT_QUOTES, 'UTF-8') ?></a></p>
    <?php endif; ?>

    <?php if ($memberFavorites === []): ?>
        <p class="member-profile-empty">尚無收藏的技師。至店家頁的「推薦技師」區塊，點選 ♥ 即可加入收藏。</p>
    <?php else: ?>
        <ul class="member-fav-list">
            <?php foreach ($memberFavorites as $fav): ?>
                <?php
                $mid = (int) ($fav['masseur_id'] ?? 0);
                $mName = (string) ($fav['name'] ?? '');
                $mGender = (string) ($fav['gender'] ?? 'female');
                $mGenderLabel = $favGenders[$mGender] ?? '女';
                $mPhoto = fate_masseur_resolve_photo_public_url((string) ($fav['photo_rel'] ?? ''), $mGender);
                $mHasPhoto = $mPhoto !== null;
                $storeId = (int) ($fav['spa_store_id'] ?? 0);
                $storeName = trim((string) ($fav['store_name'] ?? ''));
                $cityName = trim((string) ($fav['city_name'] ?? ''));
                $districtName = trim((string) ($fav['district_name'] ?? ''));
                $loc = $cityName;
                if ($districtName !== '') {
                    $loc = ($loc !== '' ? $loc . ' ' : '') . $districtName;
                }
                $favDate = substr((string) ($fav['favorited_at'] ?? ''), 0, 10);
                $isExperienced = (int) ($fav['is_experienced'] ?? 0) === 1;
                $expDate = substr((string) ($fav['experienced_at'] ?? ''), 0, 10);
                $mReviewCount = 0;
                $mReviews = [];
                $mReviewPage = isset($_GET['rpage_' . $mid]) ? max(1, (int) $_GET['rpage_' . $mid]) : 1;
                $mReviewPages = 1;
                $mReviewPagerOn = false;
                if ($favCanViewReviews && $pdo instanceof PDO) {
                    try {
                        $rcSt = $pdo->prepare(
                            'SELECT COUNT(*) FROM `fate_masseur_reviews` WHERE `masseur_id` = ? AND `is_hidden` = 0'
                        );
                        $rcSt->execute([$mid]);
                        $mReviewCount = (int) $rcSt->fetchColumn();
                    } catch (Throwable) {
                        $mReviewCount = 0;
                    }
                    $mReviewPages = $mReviewCount > 0
                        ? max(1, (int) ceil($mReviewCount / $favReviewsPerPage))
                        : 1;
                    if ($mReviewPage > $mReviewPages) {
                        $mReviewPage = $mReviewPages;
                    }
                    $mReviewPagerOn = $mReviewCount > $favReviewsPerPage;
                    if ($mReviewCount > 0) {
                        $mReviews = fate_masseur_reviews_for(
                            $pdo,
                            $mid,
                            false,
                            $favReviewsPerPage,
                            ($mReviewPage - 1) * $favReviewsPerPage
                        );
                    }
                }
                ?>
                <li class="member-fav-card" id="fav-<?= $mid ?>">
                    <div class="member-fav-card__top">
                        <div class="member-fav-card__avatar member-fav-card__avatar--<?= htmlspecialchars($mGender, ENT_QUOTES, 'UTF-8') ?>">
                            <?php if ($mHasPhoto): ?>
                                <img src="<?= htmlspecialchars($mPhoto, ENT_QUOTES, 'UTF-8') ?>" alt="" loading="lazy" decoding="async">
                            <?php else: ?>
                                <span aria-hidden="true"><?= $mGender === 'male' ? '♂' : ($mGender === 'female' ? '♀' : '☻') ?></span>
                            <?php endif; ?>
                        </div>
                        <div class="member-fav-card__body">
                            <p class="member-fav-card__name"><?= htmlspecialchars($mName, ENT_QUOTES, 'UTF-8') ?>
                                <span class="masseur-card__gender"><?= htmlspecialchars($mGenderLabel, ENT_QUOTES, 'UTF-8') ?></span>
                            </p>
                            <?php if ($storeId > 0 && $storeName !== ''): ?>
                                <p class="member-fav-card__store">
                                    <a href="store.php?id=<?= $storeId ?>"><?= htmlspecialchars($storeName, ENT_QUOTES, 'UTF-8') ?></a>
                                    <?php if ($loc !== ''): ?> · <?= htmlspecialchars($loc, ENT_QUOTES, 'UTF-8') ?><?php endif; ?>
                                </p>
                            <?php endif; ?>
                            <p class="member-fav-card__meta">
                                收藏 <?= htmlspecialchars($favDate, ENT_QUOTES, 'UTF-8') ?>
                                <?php if ($isExperienced && $expDate !== ''): ?>
                                    · 已體驗 <?= htmlspecialchars($expDate, ENT_QUOTES, 'UTF-8') ?>
                                <?php endif; ?>
                                · ♥ <?= (int) ($fav['favorite_count'] ?? 0) ?> 人收藏
                            </p>
                        </div>
                        <div class="member-fav-card__side">
                            <form method="post" action="member_profile.php?tab=favorites" class="member-fav-exp-form">
                                <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                <input type="hidden" name="action" value="favorite_experienced">
                                <input type="hidden" name="masseur_id" value="<?= $mid ?>">
                                <?php if ($isExperienced): ?>
                                    <input type="hidden" name="experienced" value="0">
                                    <button type="submit" class="member-fav-exp-btn is-done" title="改為未體驗">已體驗</button>
                                <?php else: ?>
                                    <input type="hidden" name="experienced" value="1">
                                    <button type="submit" class="member-fav-exp-btn" title="標記為已體驗">未體驗</button>
                                <?php endif; ?>
                            </form>
                            <?php if ($favCanInteract): ?>
                                <form method="post" action="api/masseur_action.php" class="member-fav-unfav-form">
                                    <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="action" value="favorite">
                                    <input type="hidden" name="store_id" value="<?= $storeId ?>">
                                    <input type="hidden" name="masseur_id" value="<?= $mid ?>">
                                    <input type="hidden" name="return_to" value="<?= htmlspecialchars($favReturnTo, ENT_QUOTES, 'UTF-8') ?>">
                                    <button type="submit" class="member-profile-btn member-profile-btn--ghost member-profile-btn--sm">取消收藏</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    </div>

                    <?php if ($favCanViewTags): ?>
                        <div class="member-fav-card__tags">
                            <?php fate_masseur_tag_render_row($mid, $storeId, $favMasseurTagPayload, $favTagInteract, $csrf, 'api/masseur_action.php', $favReturnTo); ?>
                        </div>
                    <?php elseif ($favHasTags && !empty($favTagsFormalOnly) && empty($favCanAccessTagsFormal) && $pdo instanceof PDO): ?>
                        <p class="masseur-formal-locked masseur-formal-locked--tags"><?= htmlspecialchars(fate_masseur_formal_only_view_message($pdo, (int) ($member['id'] ?? 0), '技師標籤'), ENT_QUOTES, 'UTF-8') ?></p>
                    <?php elseif ($favHasTags && !$favCanInteract): ?>
                        <p class="masseur-formal-locked masseur-formal-locked--tags">完成 Email 驗證後可點選標籤。</p>
                    <?php endif; ?>

                    <?php if ($favForumActive): ?>
                        <p class="masseur-forum-hint">討論區已啟用：請至店家頁使用技師旁的「討論」發表看法。</p>
                    <?php elseif ($favReviewsEnabled && $favCanViewReviews): ?>
                        <div class="member-fav-card__reviews">
                            <details class="masseur-reviews-fold"<?= isset($_GET['rpage_' . $mid]) ? ' open' : '' ?>>
                                <summary class="masseur-reviews-summary">評論 <span class="masseur-reviews-summary__n"><?= $mReviewCount ?></span> 則</summary>
                                <div class="masseur-reviews-body">
                                    <?php if ($mReviews === []): ?>
                                        <p class="masseur-review-empty">尚無評論。</p>
                                    <?php else: ?>
                                        <ul class="masseur-review-list">
                                            <?php foreach ($mReviews as $rv): ?>
                                                <?php $rvAvatar = fate_member_profile_avatar_url((string) ($rv['author_avatar'] ?? '')); ?>
                                                <li class="masseur-review">
                                                    <span class="masseur-review__avatar">
                                                        <?php if ($rvAvatar !== null): ?>
                                                            <img src="<?= htmlspecialchars($rvAvatar, ENT_QUOTES, 'UTF-8') ?>" alt="" loading="lazy" decoding="async">
                                                        <?php else: ?>
                                                            <span aria-hidden="true"><?= htmlspecialchars(mb_substr((string) ($rv['author_name'] ?? '會'), 0, 1), ENT_QUOTES, 'UTF-8') ?></span>
                                                        <?php endif; ?>
                                                    </span>
                                                    <div class="masseur-review__main">
                                                        <span class="masseur-review__author"><?= htmlspecialchars((string) ($rv['author_name'] ?? '會員'), ENT_QUOTES, 'UTF-8') ?></span>
                                                        <span class="masseur-review__date"><?= htmlspecialchars(substr((string) ($rv['created_at'] ?? ''), 0, 10), ENT_QUOTES, 'UTF-8') ?></span>
                                                        <p class="masseur-review__body"><?= nl2br(htmlspecialchars((string) ($rv['body'] ?? ''), ENT_QUOTES, 'UTF-8')) ?></p>
                                                    </div>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                        <?php if ($mReviewPagerOn && $mReviewPages > 1): ?>
                                            <nav class="masseur-review-pager" aria-label="<?= htmlspecialchars($mName, ENT_QUOTES, 'UTF-8') ?> 評論分頁">
                                                <?php if ($mReviewPage > 1): ?>
                                                    <a class="masseur-btn masseur-btn--sm" href="<?= htmlspecialchars($buildFavReviewPageUrl($mid, $mReviewPage - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                                                <?php endif; ?>
                                                <span class="masseur-review-pager__info">第 <?= $mReviewPage ?> / <?= $mReviewPages ?> 頁</span>
                                                <?php if ($mReviewPage < $mReviewPages): ?>
                                                    <a class="masseur-btn masseur-btn--sm" href="<?= htmlspecialchars($buildFavReviewPageUrl($mid, $mReviewPage + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                                                <?php endif; ?>
                                            </nav>
                                        <?php endif; ?>
                                    <?php endif; ?>

                                    <?php if ($favCanInteract): ?>
                                        <form method="post" action="api/masseur_action.php" class="masseur-review-form">
                                            <input type="hidden" name="csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>">
                                            <input type="hidden" name="action" value="review">
                                            <input type="hidden" name="store_id" value="<?= $storeId ?>">
                                            <input type="hidden" name="masseur_id" value="<?= $mid ?>">
                                            <input type="hidden" name="return_to" value="<?= htmlspecialchars($favReturnTo, ENT_QUOTES, 'UTF-8') ?>">
                                            <textarea name="body" rows="2" maxlength="1000" placeholder="留下您的評論…" required></textarea>
                                            <button type="submit" class="masseur-btn masseur-btn--sm">送出評論</button>
                                        </form>
                                    <?php else: ?>
                                        <p class="masseur-note masseur-note--sm"><?= htmlspecialchars($pdo instanceof PDO ? fate_public_member_interact_denied_message($pdo) : '完成 Email 驗證後即可評論。', ENT_QUOTES, 'UTF-8') ?></p>
                                    <?php endif; ?>
                                </div>
                            </details>
                        </div>
                    <?php endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>
</div>
