<?php

declare(strict_types=1);

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_install.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_public_member_auth.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_template.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_page_counter.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_listing.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_masseur_weekly_recommend.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_seo.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_admin_nav_visibility.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_plugins.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_blog.php';

fate_public_session_start();
fate_install_maybe_redirect();

if (!fate_masseur_weekly_recommend_enabled()) {
    http_response_code(404);
    $weeklyDisabledMsg = !fate_masseur_feature_enabled()
        ? '推薦技師功能尚未啟用。'
        : '本週推薦榜尚未啟用。';
    echo '<!DOCTYPE html><html lang="zh-Hant"><head><meta charset="UTF-8"><title>找不到頁面</title></head><body><p>' . htmlspecialchars($weeklyDisabledMsg, ENT_QUOTES, 'UTF-8') . '</p><p><a href="./">返回首頁</a></p></body></html>';
    exit;
}

$fatePublicMember = fate_public_member_current();
$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();
}

$fateAdminNavVisible = fate_admin_nav_visible_for_frontend();
$fateForumNavVisible = fate_store_forum_plugin_active();
$fateBlogNavVisible = fate_blog_nav_visible_for_frontend();
$fateBlogNavLabel = fate_blog_nav_label();
$fateMasseurWeeklyNavVisible = true;

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

$currentWeek = fate_masseur_weekly_recommend_week_date();
$weekParam = isset($_GET['week']) ? trim((string) $_GET['week']) : '';
if ($weekParam !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $weekParam) === 1) {
    $viewWeek = fate_masseur_weekly_normalize_view_week($weekParam, $currentWeek);
} elseif (!empty($_GET['prev'])) {
    try {
        $viewWeek = fate_masseur_weekly_normalize_view_week(
            (new DateTimeImmutable($currentWeek))->modify('-7 days')->format('Y-m-d'),
            $currentWeek
        );
    } catch (Throwable) {
        $viewWeek = $currentWeek;
    }
} else {
    $viewWeek = $currentWeek;
}

$rankLimit = fate_masseur_weekly_rank_limit();
$weeklyRankRows = [];
$weeklyRankCities = [];
$weeklyAvailableWeeks = [$currentWeek];
$memberWeeklyRecords = [];
$memberWeeklyUsage = ['used' => 0, 'max' => fate_masseur_weekly_recommend_max_per_week(), 'recommended_ids' => []];
$adminWeeklyRecords = ['items' => [], 'total' => 0];
$adminRecordsPage = isset($_GET['alog']) ? max(1, (int) $_GET['alog']) : 1;
$showAdminLog = isset($_GET['log']) && $_GET['log'] === 'all';
$viewerIsStaff = false;

$msgOk = isset($_SESSION['fate_masseur_flash_ok']) ? (string) $_SESSION['fate_masseur_flash_ok'] : '';
$msgBad = isset($_SESSION['fate_masseur_flash_bad']) ? (string) $_SESSION['fate_masseur_flash_bad'] : '';
unset($_SESSION['fate_masseur_flash_ok'], $_SESSION['fate_masseur_flash_bad']);

$csrf = fate_public_member_csrf_token();
$weeklyStatsRangeLabel = fate_masseur_weekly_stats_range_label($viewWeek);
$isCurrentWeek = $viewWeek === $currentWeek;

if ($pdo instanceof PDO) {
    fate_masseur_weekly_recommend_ensure_table($pdo);
    $weeklyAvailableWeeks = fate_masseur_weekly_available_weeks($pdo, 52);
    if (!in_array($viewWeek, $weeklyAvailableWeeks, true)) {
        $weeklyAvailableWeeks[] = $viewWeek;
        rsort($weeklyAvailableWeeks);
    }
    $weeklyRankRows = fate_masseur_weekly_rank_fetch(
        $pdo,
        $viewWeek,
        $listingFilter,
        $cityFilter !== '' ? $cityFilter : null,
        $rankLimit
    );
    $weeklyRankCities = fate_masseur_weekly_rank_cities($pdo, $viewWeek);

    $memberId = is_array($fatePublicMember) ? (int) ($fatePublicMember['id'] ?? 0) : 0;
    if ($memberId > 0) {
        $memberWeeklyUsage = fate_masseur_weekly_recommend_member_usage($pdo, $memberId, $viewWeek);
        $memberWeeklyRecords = fate_masseur_weekly_recommend_member_list($pdo, $memberId, $viewWeek);
    }

    require_once __DIR__ . DIRECTORY_SEPARATOR . 'includes' . DIRECTORY_SEPARATOR . 'fate_store_masseurs.php';
    $viewerIsStaff = $memberId > 0 && fate_masseur_member_is_site_staff($pdo);
    if ($showAdminLog && $viewerIsStaff) {
        $adminWeeklyRecords = fate_masseur_weekly_recommend_admin_list($pdo, $viewWeek, $adminRecordsPage, 50);
    } elseif ($showAdminLog && !$viewerIsStaff) {
        $showAdminLog = false;
    }
}

$buildWeeklyQuery = static function (array $overrides = []) use ($listingFilter, $cityFilter, $viewWeek, $currentWeek): string {
    $q = [];
    $listing = $listingFilter;
    if (array_key_exists('listing', $overrides)) {
        $listing = fate_store_listing_normalize_tab((string) $overrides['listing']);
    }
    if ($listing !== FATE_STORE_LISTING_FIXED) {
        $q['listing'] = $listing;
    }
    $city = $cityFilter;
    if (array_key_exists('city', $overrides)) {
        $city = trim((string) $overrides['city']);
    }
    if ($city !== '') {
        $q['city'] = $city;
    }
    $week = $viewWeek;
    if (array_key_exists('week', $overrides)) {
        $week = trim((string) $overrides['week']);
    }
    if ($week !== '' && $week !== $currentWeek) {
        $q['week'] = $week;
    }
    foreach ($overrides as $k => $v) {
        if ($k === 'listing' || $k === 'city' || $k === 'week') {
            continue;
        }
        if ($v === null || $v === '') {
            continue;
        }
        $q[$k] = $v;
    }
    $qs = http_build_query($q);

    return 'masseur_weekly.php' . ($qs !== '' ? ('?' . $qs) : '');
};

fate_page_counter_increment($pdo instanceof PDO ? $pdo : null, 'masseur_weekly', is_array($fatePublicMember) ? (int) ($fatePublicMember['id'] ?? 0) : null, '技師週推榜');

fate_render_masseur_weekly(compact(
    'fatePublicMember',
    'pdo',
    'dbError',
    'fateAdminNavVisible',
    'fateForumNavVisible',
    'fateBlogNavVisible',
    'fateBlogNavLabel',
    'fateMasseurWeeklyNavVisible',
    'listingFilter',
    'cityFilter',
    'viewWeek',
    'currentWeek',
    'weeklyRankRows',
    'weeklyRankCities',
    'weeklyAvailableWeeks',
    'memberWeeklyRecords',
    'memberWeeklyUsage',
    'adminWeeklyRecords',
    'adminRecordsPage',
    'showAdminLog',
    'viewerIsStaff',
    'msgOk',
    'msgBad',
    'csrf',
    'weeklyStatsRangeLabel',
    'isCurrentWeek',
    'rankLimit',
    'buildWeeklyQuery'
));
