<?php
if (!isset($fateIncludeStoreMap)) {
    $fateIncludeStoreMap = false;
}
if (!isset($storeMapLat)) {
    $storeMapLat = null;
    $storeMapLng = null;
}
if (!isset($storeMapEmbedUrl)) {
    $storeMapEmbedUrl = null;
}
$fateSkipLayoutTopbar = !empty($fateSkipLayoutTopbar);
if (!$fateSkipLayoutTopbar):
?>
<body>
    <header class="topbar">
        <div class="topbar-inner">
            <a class="brand" href="./"><?= htmlspecialchars($fateBrand['title_main'] ?? 'FATE', ENT_QUOTES, 'UTF-8') ?> <span><?= htmlspecialchars($fateBrand['title_sub'] ?? '店家探索', ENT_QUOTES, 'UTF-8') ?></span></a>
            <nav>
                <a href="./">探索列表</a>
                <?php
                if (!function_exists('fate_masseur_weekly_recommend_enabled')) {
                    require_once dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_rewards.php';
                }
                if (fate_masseur_weekly_recommend_enabled()):
                ?>
                    <a href="masseur_weekly.php">週推榜</a>
                <?php endif; ?>
                <?php if (!empty($fateAdminNavVisible)): ?>
                    <a href="admin/">管理後台</a>
                <?php endif; ?>
            </nav>
        </div>
    </header>
<?php else: ?>
<div class="minimal-page">
<?php endif; ?>

    <div class="layout-shell layout-shell--detail">
        <div class="layout">
            <div class="layout-main">
                <nav class="store-bc" aria-label="麵包屑">
                    <a href="./">探索</a>
                    <span class="store-bc__sep" aria-hidden="true">/</span>
                    <?php if (is_array($storeRow)): ?>
                        <?php
                        $bcName = trim((string) ($storeRow['store_name'] ?? ''));
                        echo htmlspecialchars($bcName !== '' ? $bcName : '店家 #' . $storeId, ENT_QUOTES, 'UTF-8');
                        ?>
                    <?php else: ?>
                        <span class="store-bc__cur">詳情</span>
                    <?php endif; ?>
                </nav>

                <?php if ($dbError !== null): ?>
                    <div class="store-panel store-panel--warn">
                        <p>無法連線資料庫：<code class="inline"><?= htmlspecialchars($dbError, ENT_QUOTES, 'UTF-8') ?></code></p>
                    </div>
                <?php elseif ($storeFetchError !== null): ?>
                    <div class="store-panel store-panel--warn">
                        <p>無法讀取店家資料：<code class="inline"><?= htmlspecialchars($storeFetchError, ENT_QUOTES, 'UTF-8') ?></code></p>
                    </div>
                <?php elseif ($storeId <= 0): ?>
                    <div class="store-panel store-panel--muted">
                        <p>請從<a href="./" class="text-accent-link">探索列表</a>選擇店家。</p>
                    </div>
                <?php elseif (!is_array($storeRow)): ?>
                    <div class="store-panel store-panel--muted">
                        <p>找不到編號 <strong><?= (int) $storeId ?></strong> 的店家，請返回<a href="./" class="text-accent-link">探索列表</a>。</p>
                    </div>
                <?php else: ?>
                    <?php
                    require_once __DIR__ . '/../../includes/fate_store_listing.php';
                    $row = $storeRow;
                    $sid = (int) ($row['spa_store_id'] ?? $storeId);
                    $name = trim((string) ($row['store_name'] ?? ''));
                    if ($name === '') {
                        $name = '店家 #' . $sid;
                    }
                    $isMobileListing = fate_store_listing_is_mobile($row);
                    $listingLabel = fate_store_listing_label(fate_store_listing_kind_from_row($row));
                    $city = trim((string) ($row['city_name'] ?? ''));
                    $dist = trim((string) ($row['district_name'] ?? ''));
                    $addr = fate_store_listing_location_text($row);
                    $rating = isset($row['place_rating']) && $row['place_rating'] !== '' && $row['place_rating'] !== null
                        ? (float) $row['place_rating']
                        : null;
                    $rCount = isset($row['place_ratings_total']) ? (int) $row['place_ratings_total'] : null;
                    $coverInfo = fate_store_cover_src(
                        isset($row['cover_photo_path']) ? (string) $row['cover_photo_path'] : null,
                        isset($row['photos_json']) ? (string) $row['photos_json'] : null
                    );
                    $heroImg = fate_spa_asset_url($coverInfo['path']);
                    $photoPaths = fate_store_photo_paths(isset($row['photos_json']) ? (string) $row['photos_json'] : null, 18);
                    $syncedAt = isset($row['synced_at']) ? trim((string) $row['synced_at']) : '';

                    $bhStart = isset($row['business_hours_start']) ? trim((string) $row['business_hours_start']) : '';
                    $bhEnd = isset($row['business_hours_end']) ? trim((string) $row['business_hours_end']) : '';
                    $hoursBlocks = fate_store_hours_blocks(
                        isset($row['business_hours_json']) ? (string) $row['business_hours_json'] : null,
                        $bhStart,
                        $bhEnd,
                        isset($row['place_opening_hours_raw']) ? (string) $row['place_opening_hours_raw'] : null
                    );

                    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
                    $httpHostRaw = isset($_SERVER['HTTP_HOST']) ? trim((string) $_SERVER['HTTP_HOST']) : '';
                    $requestUri = isset($_SERVER['REQUEST_URI']) ? (string) $_SERVER['REQUEST_URI'] : '';
                    $sharePageUrl = $httpHostRaw !== '' ? $scheme . '://' . $httpHostRaw . $requestUri : '';

                    require_once __DIR__ . '/../../includes/fate_crowd_reports.php';
                    $crowdMemberId = is_array($fatePublicMember ?? null) ? (int) ($fatePublicMember['id'] ?? 0) : 0;
                    $crowdReportCanInteract = $crowdMemberId > 0 && $pdo instanceof PDO && fate_public_member_can_interact($pdo);
                    $crowdReportCsrf = fate_public_member_csrf_token();
                    $storeCrowdBatch = $pdo instanceof PDO
                        ? fate_crowd_report_batch_payload($pdo, FATE_CROWD_ENTITY_STORE, [$sid], $crowdMemberId)
                        : [];
                    $storeCrowdData = $storeCrowdBatch[$sid] ?? [];
                    $crowdReturnTo = 'store.php?id=' . $sid;

                    $crowdFlashOk = isset($_SESSION['fate_crowd_flash_ok']) ? (string) $_SESSION['fate_crowd_flash_ok'] : '';
                    $crowdFlashBad = isset($_SESSION['fate_crowd_flash_bad']) ? (string) $_SESSION['fate_crowd_flash_bad'] : '';
                    unset($_SESSION['fate_crowd_flash_ok'], $_SESSION['fate_crowd_flash_bad']);

                    $photoUrls = [];
                    foreach ($photoPaths as $rel) {
                        $u = fate_spa_asset_url($rel);
                        if ($u !== null) {
                            $photoUrls[] = [
                                'url' => $u,
                                'rel' => $rel,
                            ];
                        }
                    }
                    $photoCount = count($photoUrls);

                    $fateInfoRow = static function (string $glyph, string $innerHtml): void {
                        echo '<div class="store-info-item-fate" role="listitem">';
                        echo '<span class="store-info-item-fate__glyph" aria-hidden="true">' . htmlspecialchars($glyph, ENT_QUOTES, 'UTF-8') . '</span>';
                        echo '<span class="store-info-item-fate__body">' . $innerHtml . '</span></div>';
                    };

                    $fateLineHref = static function (string $val): ?string {
                        $val = trim($val);
                        if ($val === '') {
                            return null;
                        }
                        if (preg_match('/^@?[a-zA-Z0-9.\-_]+$/', $val) === 1) {
                            return 'https://line.me/ti/p/~' . rawurlencode(ltrim($val, '@'));
                        }
                        if (filter_var($val, FILTER_VALIDATE_URL) && stripos($val, 'line.me') !== false) {
                            return $val;
                        }

                        return null;
                    };

                    $fateTgHref = static function (string $val): ?string {
                        if (strpos($val, 't.me/') !== false || strpos($val, '@') === 0) {
                            return strpos($val, '@') === 0 ? 'https://t.me/' . ltrim($val, '@') : $val;
                        }

                        return null;
                    };
                    ?>
                    <article class="store-detail<?= $isMobileListing ? ' store-detail--mobile' : ' store-detail--fixed' ?>">
                        <?php if ($crowdFlashOk !== ''): ?>
                            <div class="member-profile-msg member-profile-msg--ok"><?= htmlspecialchars($crowdFlashOk, ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>
                        <?php if ($crowdFlashBad !== ''): ?>
                            <div class="member-profile-msg member-profile-msg--bad"><?= htmlspecialchars($crowdFlashBad, ENT_QUOTES, 'UTF-8') ?></div>
                        <?php endif; ?>
                        <div class="store-card-fate">
                             <?php if ($heroImg !== null): ?>
                                 <img class="store-card-fate__cover" src="<?= htmlspecialchars($heroImg, ENT_QUOTES, 'UTF-8') ?>"
                                      onerror="this.onerror=null; this.src='<?= htmlspecialchars(fate_local_asset_url($coverInfo['path']) ?? '') ?>';"
                                      alt="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>" decoding="async" fetchpriority="high">
                             <?php else: ?>
                                <div class="store-card-fate__cover store-card-fate__cover--empty" aria-hidden="true">無封面</div>
                            <?php endif; ?>

                            <div class="store-card-fate__body">
                                <div class="store-header-row-fate">
                                    <div class="store-header-row-fate__title">
                                        <h1 class="store-title-fate"><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></h1>
                                        <?php if ($isMobileListing): ?>
                                            <p class="store-sub-fate"><span class="store-listing-badge store-listing-badge--mobile"><?= htmlspecialchars($listingLabel, ENT_QUOTES, 'UTF-8') ?></span></p>
                                        <?php elseif ($city !== '' || $dist !== ''): ?>
                                            <p class="store-sub-fate"><?= htmlspecialchars(trim($city . ($city !== '' && $dist !== '' ? ' · ' : '') . $dist), ENT_QUOTES, 'UTF-8') ?></p>
                                        <?php endif; ?>
                                        <?php if ($rating !== null): ?>
                                            <p class="store-rating-fate">
                                                <span class="store-rating-fate__star" aria-hidden="true">★</span>
                                                <?= htmlspecialchars(number_format($rating, 1), ENT_QUOTES, 'UTF-8') ?>
                                                <?php if ($rCount !== null && $rCount > 0): ?>
                                                    <span class="store-rating-fate__cnt">（<?= (int) $rCount ?> 則評分）</span>
                                                <?php endif; ?>
                                            </p>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($sharePageUrl !== ''): ?>
                                        <div class="store-share-fate">
                                            <button type="button" class="store-share-fate__btn" data-fate-share="copy" title="複製本頁連結">複製連結</button>
                                            <a class="store-share-fate__btn" href="https://www.facebook.com/sharer/sharer.php?u=<?= rawurlencode($sharePageUrl) ?>" target="_blank" rel="noopener noreferrer" title="分享到 Facebook">Facebook</a>
                                            <a class="store-share-fate__btn" href="https://social-plugins.line.me/lineit/share?url=<?= rawurlencode($sharePageUrl) ?>" target="_blank" rel="noopener noreferrer" title="分享到 LINE">LINE</a>
                                        </div>
                                    <?php endif; ?>
                                </div>

                                <?php
                                fate_crowd_report_render_block(
                                    FATE_CROWD_ENTITY_STORE,
                                    $sid,
                                    $storeCrowdData,
                                    $crowdReportCanInteract,
                                    $crowdReportCsrf,
                                    array_keys(fate_crowd_report_store_keys()),
                                    'api/crowd_report.php',
                                    $crowdReturnTo,
                                    'crowd-reports--store-detail'
                                );
                                ?>

                                <div class="store-info-fate" role="list">
                                    <?php
                                    if ($addr !== '') {
                                        if ($isMobileListing) {
                                            $fateInfoRow('區', htmlspecialchars($addr, ENT_QUOTES, 'UTF-8'));
                                        } else {
                                            $gpid = trim((string) ($row['google_place_id'] ?? ''));
                                            $mapsUrl = 'https://www.google.com/maps/search/?api=1&query=' . rawurlencode($addr);
                                            if ($gpid !== '') {
                                                $mapsUrl .= '&query_place_id=' . rawurlencode($gpid);
                                            }
                                            $fateInfoRow('址', '<a href="' . htmlspecialchars($mapsUrl, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($addr, ENT_QUOTES, 'UTF-8') . '</a>');
                                        }
                                    }

                                    $phoneVal = trim((string) ($row['phone'] ?? ''));
                                    if ($phoneVal !== '') {
                                        $tel = 'tel:' . preg_replace('/[^\d+]/', '', $phoneVal);
                                        $fateInfoRow('電', '<a href="' . htmlspecialchars($tel, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($phoneVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                    }
                                    $mobileVal = trim((string) ($row['mobile'] ?? ''));
                                    if ($mobileVal !== '') {
                                        $telM = 'tel:' . preg_replace('/[^\d+]/', '', $mobileVal);
                                        $fateInfoRow('手', '<a href="' . htmlspecialchars($telM, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($mobileVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                    }
                                    $lineVal = trim((string) ($row['line'] ?? ''));
                                    if ($lineVal !== '') {
                                        $lh = $fateLineHref($lineVal);
                                        if ($lh !== null) {
                                            $fateInfoRow('L', '<a href="' . htmlspecialchars($lh, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($lineVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                        } else {
                                            $fateInfoRow('L', htmlspecialchars($lineVal, ENT_QUOTES, 'UTF-8'));
                                        }
                                    }
                                    $lineIdVal = trim((string) ($row['line_id'] ?? ''));
                                    if ($lineIdVal !== '') {
                                        $lhId = $fateLineHref($lineIdVal);
                                        $lineDisp = htmlspecialchars($lineIdVal, ENT_QUOTES, 'UTF-8');
                                        if ($lhId !== null) {
                                            $fateInfoRow('ID', '<a href="' . htmlspecialchars($lhId, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">' . $lineDisp . '</a>');
                                        } elseif (filter_var($lineIdVal, FILTER_VALIDATE_URL) && stripos($lineIdVal, 'line.me') !== false) {
                                            $fateInfoRow('ID', '<a href="' . htmlspecialchars($lineIdVal, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">點此加入 LINE</a>');
                                        } else {
                                            $fateInfoRow('ID', $lineDisp);
                                        }
                                    }
                                    $wechatVal = trim((string) ($row['wechat'] ?? ''));
                                    if ($wechatVal !== '') {
                                        $fateInfoRow('微', htmlspecialchars($wechatVal, ENT_QUOTES, 'UTF-8'));
                                    }
                                    $wechatIdVal = trim((string) ($row['wechat_id'] ?? ''));
                                    if ($wechatIdVal !== '') {
                                        $fateInfoRow('信', htmlspecialchars($wechatIdVal, ENT_QUOTES, 'UTF-8'));
                                    }
                                    $tgVal = trim((string) ($row['telegram_contact'] ?? ''));
                                    if ($tgVal !== '') {
                                        $tgH = $fateTgHref($tgVal);
                                        if ($tgH !== null) {
                                            $fateInfoRow('飛', '<a href="' . htmlspecialchars($tgH, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($tgVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                        } else {
                                            $fateInfoRow('飛', htmlspecialchars($tgVal, ENT_QUOTES, 'UTF-8'));
                                        }
                                    }
                                    $ttVal = trim((string) ($row['tiktok_contact'] ?? ''));
                                    if ($ttVal !== '') {
                                        $ttH = stripos($ttVal, 'tiktok.com/') !== false ? $ttVal : null;
                                        if ($ttH !== null) {
                                            $fateInfoRow('抖', '<a href="' . htmlspecialchars($ttH, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">' . htmlspecialchars($ttVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                        } else {
                                            $fateInfoRow('抖', htmlspecialchars($ttVal, ENT_QUOTES, 'UTF-8'));
                                        }
                                    }
                                    $emailVal = trim((string) ($row['email'] ?? ''));
                                    if ($emailVal !== '') {
                                        $fateInfoRow('@', '<a href="mailto:' . htmlspecialchars($emailVal, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($emailVal, ENT_QUOTES, 'UTF-8') . '</a>');
                                    }
                                    $webVal = trim((string) ($row['website'] ?? ''));
                                    if ($webVal !== '') {
                                        $wu = $webVal;
                                        if (!preg_match('~^(?:f|ht)tps?://~i', $wu)) {
                                            $wu = 'http://' . $wu;
                                        }
                                        $host = parse_url($wu, PHP_URL_HOST) ?: $webVal;
                                        $fateInfoRow('網', '<a href="' . htmlspecialchars($wu, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer" title="' . htmlspecialchars($webVal, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars((string) $host, ENT_QUOTES, 'UTF-8') . '</a>');
                                    }
                                    $fbVal = trim((string) ($row['facebook'] ?? ''));
                                    if ($fbVal !== '') {
                                        $fbUrl = $fbVal;
                                        if (!filter_var($fbUrl, FILTER_VALIDATE_URL)) {
                                            $fbUrl = 'https://www.facebook.com/' . rawurlencode(trim(str_replace('@', '', $fbVal)));
                                        }
                                        $fateInfoRow('f', '<a href="' . htmlspecialchars($fbUrl, ENT_QUOTES, 'UTF-8') . '" target="_blank" rel="noopener noreferrer">Facebook 專頁</a>');
                                    }

                                    if (fate_store_hours_has_content($hoursBlocks)) {
                                        $hoursHasDetails = $hoursBlocks['rows'] !== []
                                            || ($hoursBlocks['legacy'] !== null && $hoursBlocks['legacy'] !== '')
                                            || $hoursBlocks['raw_lines'] !== [];
                                        ob_start();
                                        echo '<div class="store-hours-card">';
                                        if ($hoursBlocks['today'] !== null && $hoursBlocks['today'] !== '') {
                                            echo '<p class="store-hours-card__today"><span class="store-hours-card__tag">今日</span> '
                                                . htmlspecialchars($hoursBlocks['today'], ENT_QUOTES, 'UTF-8') . '</p>';
                                        }
                                        if ($hoursHasDetails) {
                                            echo '<button type="button" class="store-hours-card__toggle" id="storeHoursToggleFate" aria-expanded="false" aria-controls="storeHoursDetailsFate">顯示完整營業時間</button>';
                                            echo '<div class="store-hours-card__details" id="storeHoursDetailsFate" hidden>';
                                            if ($hoursBlocks['rows'] !== []) {
                                                echo '<div class="store-hours-card__table-wrap"><table class="store-hours-card__table"><tbody>';
                                                foreach ($hoursBlocks['rows'] as $hr) {
                                                    echo '<tr>';
                                                    if ($hr['label'] !== '') {
                                                        echo '<th scope="row">' . htmlspecialchars($hr['label'], ENT_QUOTES, 'UTF-8') . '</th>';
                                                        echo '<td>' . htmlspecialchars($hr['value'], ENT_QUOTES, 'UTF-8') . '</td>';
                                                    } else {
                                                        echo '<td colspan="2">' . htmlspecialchars($hr['value'], ENT_QUOTES, 'UTF-8') . '</td>';
                                                    }
                                                    echo '</tr>';
                                                }
                                                echo '</tbody></table></div>';
                                            } elseif ($hoursBlocks['legacy'] !== null && $hoursBlocks['legacy'] !== '') {
                                                echo '<p class="store-hours-card__legacy">' . htmlspecialchars($hoursBlocks['legacy'], ENT_QUOTES, 'UTF-8') . '</p>';
                                            } elseif ($hoursBlocks['raw_lines'] !== []) {
                                                echo '<ul class="store-hours-card__list">';
                                                foreach ($hoursBlocks['raw_lines'] as $ln) {
                                                    echo '<li>' . htmlspecialchars($ln, ENT_QUOTES, 'UTF-8') . '</li>';
                                                }
                                                echo '</ul>';
                                            }
                                            echo '</div>';
                                        }
                                        echo '</div>';
                                        $fateInfoRow('時', (string) ob_get_clean());
                                    }

                                    if (!$fateIncludeStoreMap && isset($row['latitude']) && isset($row['longitude'])) {
                                        $la = trim((string) $row['latitude']);
                                        $ln = trim((string) $row['longitude']);
                                        if ($la !== '' && $ln !== '' && is_numeric($la) && is_numeric($ln)) {
                                            $coordLabel = htmlspecialchars($la . ', ' . $ln, ENT_QUOTES, 'UTF-8');
                                            $fateInfoRow('標', $coordLabel);
                                        }
                                    }
                                    ?>
                                </div>

                                <div class="store-features-fate">
                                    <?php
                                    $biz = trim((string) ($row['business_type'] ?? ''));
                                    if ($biz !== '') {
                                        echo '<span class="store-badge-fate store-badge-fate--muted">' . htmlspecialchars($biz, ENT_QUOTES, 'UTF-8') . '</span>';
                                    }
                                    $appt = trim((string) ($row['appointment_required'] ?? ''));
                                    if ($appt !== '') {
                                        $apptText = ($appt === '預約') ? '需預約' : $appt;
                                        echo '<span class="store-badge-fate store-badge-fate--muted">' . htmlspecialchars($apptText, ENT_QUOTES, 'UTF-8') . '</span>';
                                    }
                                    $park = trim((string) ($row['parking'] ?? ''));
                                    if ($park !== '' && $park !== '未設定') {
                                        echo '<span class="store-badge-fate store-badge-fate--muted">' . htmlspecialchars($park, ENT_QUOTES, 'UTF-8') . '</span>';
                                    }
                                    $pay = trim((string) ($row['payment_method'] ?? ''));
                                    if ($pay !== '' && $pay !== '未設定') {
                                        echo '<span class="store-badge-fate store-badge-fate--muted">' . htmlspecialchars($pay, ENT_QUOTES, 'UTF-8') . '</span>';
                                    }
                                    $spaTypes = trim((string) ($row['spa_type'] ?? ''));
                                    if ($spaTypes !== '') {
                                        foreach (array_filter(array_map('trim', explode(',', $spaTypes))) as $stOne) {
                                            echo '<span class="store-badge-fate store-badge-fate--accent">' . htmlspecialchars($stOne, ENT_QUOTES, 'UTF-8') . '</span>';
                                        }
                                    }
                                    if (isset($row['basic_charge']) && $row['basic_charge'] !== '' && $row['basic_charge'] !== null && is_numeric($row['basic_charge']) && (float) $row['basic_charge'] > 0) {
                                        echo '<span class="store-badge-fate store-badge-fate--ok">$' . htmlspecialchars(number_format((float) $row['basic_charge'], 0, '.', ','), ENT_QUOTES, 'UTF-8') . ' 起</span>';
                                    }
                                    ?>
                                </div>

                                <div class="store-disclaimer-fate">
                                    <strong>提醒：</strong>店家資訊由網路收集，訊息可能有誤差，請以店家實際情況為主；本站無法過濾各項合規性，請自行判斷消費。
                                </div>
                            </div>
                        </div>

                        <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'store_reviews.php'; ?>

                        <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'store_tabs_extra.php'; ?>

                        <?php
                        // 論壇插件（守衛式注入）：移除 /forum 後自動停用，不影響店家頁。
                        $forumHookFile = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'forum' . DIRECTORY_SEPARATOR . 'hook.php';
                        if (is_file($forumHookFile)) {
                            $forumHookStoreId = $sid;
                            require $forumHookFile;
                        }
                        ?>

                        <footer class="store-meta-foot store-meta-foot--detail">
                            <span class="store-meta-foot__id">#<?= $sid ?></span>
                            <?php if ($syncedAt !== ''): ?>
                                <span class="store-meta-foot__sync">資料同步 <?= htmlspecialchars($syncedAt, ENT_QUOTES, 'UTF-8') ?></span>
                            <?php endif; ?>
                        </footer>
                    </article>
                <?php endif; ?>
            </div>

            <?php require __DIR__ . DIRECTORY_SEPARATOR . 'partials' . DIRECTORY_SEPARATOR . 'sidebar.php'; ?>
        </div>
    </div>
<?php if ($fateSkipLayoutTopbar): ?>
</div>
<?php endif; ?>

<script>
(function () {
    document.querySelector('[data-fate-share="copy"]')?.addEventListener('click', function () {
        var url = window.location.href;
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(url).then(function () {
                alert('已複製連結');
            }).catch(function () {
                window.prompt('複製連結', url);
            });
        } else {
            window.prompt('複製連結', url);
        }
    });
    var hoursBtn = document.getElementById('storeHoursToggleFate');
    var hoursPanel = document.getElementById('storeHoursDetailsFate');
    if (hoursBtn && hoursPanel) {
        hoursBtn.addEventListener('click', function () {
            var open = hoursBtn.getAttribute('aria-expanded') === 'true';
            open = !open;
            hoursBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
            hoursBtn.textContent = open ? '收合營業時間' : '顯示完整營業時間';
            if (open) {
                hoursPanel.removeAttribute('hidden');
            } else {
                hoursPanel.setAttribute('hidden', '');
            }
        });
    }
})();
</script>
