<?php

declare(strict_types=1);

/**
 * 店家頁：文字評論區塊。
 * 依賴 store_main.php：$pdo、$sid、$fatePublicMember。
 */

if (!isset($pdo) || !$pdo instanceof PDO || !isset($sid) || (int) $sid <= 0) {
    return;
}

require_once dirname(__DIR__, 3) . '/includes/fate_plugins.php';
require_once dirname(__DIR__, 3) . '/includes/fate_store_reviews.php';
require_once dirname(__DIR__, 3) . '/includes/fate_member_tier.php';

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

if (fate_store_forum_plugin_active() || !fate_store_reviews_enabled()) {
    return;
}

$storeReviewStoreId = (int) $sid;
$storeReviewMemberId = is_array($fatePublicMember ?? null) ? (int) ($fatePublicMember['id'] ?? 0) : 0;
$storeReviewLoggedIn = $storeReviewMemberId > 0;
if ($storeReviewLoggedIn) {
    fate_public_member_ensure_admin_flag($pdo);
}
$storeReviewViewerIsStaff = $storeReviewLoggedIn && fate_masseur_member_is_site_staff($pdo);
$storeReviewCanInteract = $storeReviewLoggedIn && fate_public_member_can_interact($pdo);
$storeReviewCanView = true;
$storeReviewCanPost = $storeReviewViewerIsStaff || $storeReviewCanInteract;
$storeReviewCsrf = fate_public_member_csrf_token();
$storeReviewPage = max(1, (int) ($_GET['store_review_page'] ?? 1));
$storeReviewPerPage = fate_store_reviews_per_page();
$storeReviewCount = fate_store_reviews_count($pdo, $storeReviewStoreId);
$storeReviewPages = max(1, (int) ceil($storeReviewCount / $storeReviewPerPage));
if ($storeReviewPage > $storeReviewPages) {
    $storeReviewPage = $storeReviewPages;
}
$storeReviewOffset = ($storeReviewPage - 1) * $storeReviewPerPage;
$storeReviews = $storeReviewCanView
    ? fate_store_reviews_for($pdo, $storeReviewStoreId, false, $storeReviewPerPage, $storeReviewOffset)
    : [];
$storeReviewLoginNext = rawurlencode('store.php?id=' . $storeReviewStoreId . '#store-reviews');

$storeReviewFlashOk = isset($_SESSION['fate_store_review_flash_ok']) ? (string) $_SESSION['fate_store_review_flash_ok'] : '';
$storeReviewFlashBad = isset($_SESSION['fate_store_review_flash_bad']) ? (string) $_SESSION['fate_store_review_flash_bad'] : '';
unset($_SESSION['fate_store_review_flash_ok'], $_SESSION['fate_store_review_flash_bad']);

$storeReviewBuildPageUrl = static function (int $page) use ($storeReviewStoreId): string {
    $qs = http_build_query(array_filter([
        'id' => $storeReviewStoreId,
        'store_review_page' => $page > 1 ? $page : null,
    ], static fn($v) => $v !== null));

    return 'store.php?' . $qs . '#store-reviews';
};
?>
<section class="store-card-fate store-card-fate--block store-reviews" id="store-reviews" aria-label="店家評論">
    <h2 class="store-section-fate-h">店家評論</h2>

    <?php if ($storeReviewFlashOk !== ''): ?>
        <div class="member-profile-msg member-profile-msg--ok"><?= htmlspecialchars($storeReviewFlashOk, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>
    <?php if ($storeReviewFlashBad !== ''): ?>
        <div class="member-profile-msg member-profile-msg--bad"><?= htmlspecialchars($storeReviewFlashBad, ENT_QUOTES, 'UTF-8') ?></div>
    <?php endif; ?>

    <?php if ($storeReviews === []): ?>
        <p class="masseur-empty">尚無店家評論，歡迎搶頭香。</p>
    <?php else: ?>
        <ul class="masseur-review-list">
            <?php foreach ($storeReviews 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')) ?><?php if (!empty($rv['edited_by_admin'])): ?> <em class="masseur-review__edited">（管理員編輯）</em><?php endif; ?></p>
                    </div>
                </li>
            <?php endforeach; ?>
        </ul>
        <?php if ($storeReviewPages > 1): ?>
            <nav class="masseur-review-pager" aria-label="店家評論分頁">
                <?php if ($storeReviewPage > 1): ?>
                    <a class="masseur-btn masseur-btn--sm" href="<?= htmlspecialchars($storeReviewBuildPageUrl($storeReviewPage - 1), ENT_QUOTES, 'UTF-8') ?>">上一頁</a>
                <?php endif; ?>
                <span class="masseur-review-pager__info">第 <?= (int) $storeReviewPage ?> / <?= (int) $storeReviewPages ?> 頁（共 <?= (int) $storeReviewCount ?> 則）</span>
                <?php if ($storeReviewPage < $storeReviewPages): ?>
                    <a class="masseur-btn masseur-btn--sm" href="<?= htmlspecialchars($storeReviewBuildPageUrl($storeReviewPage + 1), ENT_QUOTES, 'UTF-8') ?>">下一頁</a>
                <?php endif; ?>
            </nav>
        <?php endif; ?>
    <?php endif; ?>

    <?php if ($storeReviewCanPost): ?>
        <form method="post" action="api/store_review_action.php" class="masseur-review-form">
            <input type="hidden" name="csrf" value="<?= htmlspecialchars($storeReviewCsrf, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="store_id" value="<?= $storeReviewStoreId ?>">
            <textarea name="body" rows="3" maxlength="1000" placeholder="分享您對這家店的看法…" required></textarea>
            <button type="submit" class="masseur-btn masseur-btn--sm">送出店家評論</button>
        </form>
    <?php elseif (!$storeReviewLoggedIn): ?>
        <p class="masseur-note masseur-note--sm">請先<a href="login.php?next=<?= $storeReviewLoginNext ?>" class="text-accent-link">登入</a>並完成 Email 驗證後即可評論。</p>
    <?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; ?>
</section>
