<?php

declare(strict_types=1);

/**
 * 店家詳細頁（預設模版 templates/default/store.php）。
 */
header('Content-Type: text/html; charset=UTF-8');

require_once __DIR__ . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'app.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_session.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_urls.php';

fate_public_session_start();
$fatePublicMember = fate_public_member_current();

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_hours.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_page_counter.php';

$httpHost = $_SERVER['HTTP_HOST'] ?? '';

$storeId = isset($_GET['id']) ? (int) $_GET['id'] : 0;

$frontendDb = fate_frontend_db_bootstrap();
$pdo = $frontendDb['pdo'];
$dbError = $frontendDb['dbError'];

if ($fatePublicMember !== null && $pdo instanceof PDO) {
    require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_member_profile.php';
    fate_public_member_ensure_admin_flag($pdo);
    fate_member_profile_hydrate_session($pdo, (int) $fatePublicMember['id']);
    $fatePublicMember = fate_public_member_current();
}

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_nav_visibility.php';
$fateAdminNavVisible = fate_admin_nav_visible_for_frontend();
if (session_status() === PHP_SESSION_NONE) {
    fate_public_session_start();
}

/** @var array<string,mixed>|null */
$storeRow = null;
$storeFetchError = null;

if ($pdo instanceof PDO && $storeId > 0) {
    try {
        $st = $pdo->prepare('SELECT * FROM spa_store_snapshots WHERE spa_store_id = ? LIMIT 1');
        $st->execute([$storeId]);
        $fetched = $st->fetch(PDO::FETCH_ASSOC);
        $storeRow = is_array($fetched) ? $fetched : null;

        if ($storeRow !== null) {
            $isApproved = isset($storeRow['is_approved']) ? (int)$storeRow['is_approved'] : 1;
            $creatorId = isset($storeRow['created_member_id']) && $storeRow['created_member_id'] !== null ? (int)$storeRow['created_member_id'] : 0;
            $isAdmin = !empty($fateAdminNavVisible);
            $isCreator = $fatePublicMember !== null && (int)$fatePublicMember['id'] === $creatorId;
            if ($isApproved !== 1 && !$isAdmin && !$isCreator) {
                $storeRow = null;
            }
        }
    } catch (Throwable $e) {
        $storeFetchError = $e->getMessage();
        $storeRow = null;
    }
}

$cityFilter = isset($_GET['city']) ? trim((string) $_GET['city']) : '';
if (strlen($cityFilter) > 120) {
    $cityFilter = substr($cityFilter, 0, 120);
}

$sort = isset($_GET['sort']) ? strtolower(trim((string) $_GET['sort'])) : 'rating';
if (!in_array($sort, ['rating', 'name', 'recent'], true)) {
    $sort = 'rating';
}

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_search_probe.php';

$storeSearchQ = fate_search_normalize_public_query(isset($_GET['q']) ? (string) $_GET['q'] : '');

require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_list_query.php';
$buildHomeQuery = static function (array $overrides): string {
    return fate_build_home_list_query($_GET, $overrides);
};
/** 店家頁分頁用；側欄搜尋請用 $buildHomeQuery → index.php */
$buildQuery = static function (array $overrides): string {
    $q = array_merge($_GET, $overrides);
    $pairs = [];
    foreach ($q as $k => $v) {
        if ($v === null || $v === '') {
            continue;
        }
        $pairs[] = rawurlencode((string) $k) . '=' . rawurlencode((string) $v);
    }

    return $pairs !== [] ? '?' . implode('&', $pairs) : '';
};
$storeSearchTotal = null;

$fateMemberIdForLog = fate_page_stats_member_id($fatePublicMember);

$displayName = '';
if (is_array($storeRow)) {
    $displayName = trim((string) ($storeRow['store_name'] ?? ''));
    if ($displayName === '') {
        $displayName = '店家 #' . $storeId;
    }
}
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_ui_settings.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_seo.php';
$fateBrandForTitle = fate_public_site_branding();
$siteTitleSuffix = $fateBrandForTitle['title_main'];

$fateSeoContext = fate_seo_store_context($storeRow, $storeId);
$fatePageTitle = (string) ($fateSeoContext['title'] ?? ('店家詳情 — ' . $siteTitleSuffix));

$pageKey = $storeId > 0 ? ('store.' . $storeId) : '';
$fatePageStatsFooter = fate_page_stats_for_footer($pdo, $pageKey, $fateMemberIdForLog, $fatePageTitle);
$fatePageHitCount = $fatePageStatsFooter['fatePageHitCount'];
$fatePageStatsDbOk = $fatePageStatsFooter['fatePageStatsDbOk'];

fate_render_store(compact(
    'httpHost',
    'dbError',
    'pdo',
    'storeId',
    'storeRow',
    'storeFetchError',
    'fatePublicMember',
    'cityFilter',
    'sort',
    'storeSearchQ',
    'buildQuery',
    'buildHomeQuery',
    'storeSearchTotal',
    'fatePageHitCount',
    'fatePageStatsDbOk',
    'fatePageTitle',
    'fateSeoContext',
    'fateAdminNavVisible'
));
