<?php
declare(strict_types=1);
require __DIR__ . '/app/bootstrap.php';

if (!file_exists(__DIR__ . '/installed.lock')) {
    header('Location: /install/');
    exit;
}

ensure_fishing_spots_table();
$db = db();

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    header('HTTP/1.1 404 Not Found');
    echo 'Not Found';
    exit;
}

$stmt = $db->prepare("SELECT * FROM fishing_spots WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$spot = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$spot) {
    header('HTTP/1.1 404 Not Found');
    echo 'Not Found';
    exit;
}

$title = trim((string)$spot['title']);
if ($title === '') $title = '钓点 #' . $id;

$province = trim((string)$spot['province']);
$city = trim((string)$spot['city']);
$region = trim($province . ($city ? (' ' . $city) : ''));

$lat = (string)$spot['lat'];
$lon = (string)$spot['lon'];

$up = (int)($spot['up_count'] ?? 0);
$down = (int)($spot['down_count'] ?? 0);

$updated = (string)($spot['updated_at'] ?? '');

// base url
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = (string)($_SERVER['HTTP_HOST'] ?? '');
$base = $scheme . '://' . $host;

$canonical = $base . '/spot.php?id=' . $id;

$desc = $region ? ($region . '钓点分享，') : '';
$desc .= '坐标：' . $lat . ',' . $lon . '。查看附近钓点、狂口龟点、地图导航与参考信息。';

// nearby (10km) - fast rough filter first by bounding box then Haversine
function haversine_km(float $lat1, float $lon1, float $lat2, float $lon2): float {
    $R = 6371.0;
    $dLat = deg2rad($lat2-$lat1);
    $dLon = deg2rad($lon2-$lon1);
    $a = sin($dLat/2)*sin($dLat/2) + cos(deg2rad($lat1))*cos(deg2rad($lat2))*sin($dLon/2)*sin($dLon/2);
    $c = 2*atan2(sqrt($a), sqrt(1-$a));
    return $R*$c;
}
$near = [];
try {
    $latf = (float)$spot['lat'];
    $lonf = (float)$spot['lon'];
    $radius = 10.0;
    $latDelta = $radius / 111.0;
    $lonDelta = $radius / (111.0 * max(0.2, cos(deg2rad($latf))));
    $minLat = $latf - $latDelta;
    $maxLat = $latf + $latDelta;
    $minLon = $lonf - $lonDelta;
    $maxLon = $lonf + $lonDelta;

    $stmt = $db->prepare("SELECT id,title,lat,lon,up_count,down_count,updated_at FROM fishing_spots
                          WHERE id<>?
                            AND lat BETWEEN ? AND ?
                            AND lon BETWEEN ? AND ?
                          ORDER BY updated_at DESC
                          LIMIT 50");
    $stmt->execute([$id, $minLat, $maxLat, $minLon, $maxLon]);
    while ($r = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $d = haversine_km($latf, $lonf, (float)$r['lat'], (float)$r['lon']);
        if ($d <= $radius) {
            $r['dist_km'] = $d;
            $near[] = $r;
        }
    }
    usort($near, fn($a,$b)=>($a['dist_km'] <=> $b['dist_km']));
    $near = array_slice($near, 0, 15);
} catch (Throwable $e) {
    // ignore
}

$frontHeaderTitle = setting_get('front_header_title', '钓鱼天气/潮汐');
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= e($title) ?> - <?= e($frontHeaderTitle) ?></title>
  <meta name="description" content="<?= e($desc) ?>">
  <link rel="canonical" href="<?= e($canonical) ?>">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{background:#f6f7fb;}
    .mono{font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;}
    .card{border-radius:16px;}
  </style>

  <script type="application/ld+json">
  <?= json_encode([
      "@context"=>"https://schema.org",
      "@type"=>"Place",
      "name"=>$title,
      "address"=>$region ?: null,
      "geo"=>[
        "@type"=>"GeoCoordinates",
        "latitude"=>(float)$spot['lat'],
        "longitude"=>(float)$spot['lon'],
      ],
      "url"=>$canonical,
      "dateModified"=>$updated ?: null,
  ], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT) ?>
  </script>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-white border-bottom">
  <div class="container">
    <a class="navbar-brand fw-semibold" href="/"><?= e($frontHeaderTitle) ?></a>
    <div class="ms-auto">
      <a class="btn btn-outline-primary btn-sm" href="/">返回地图工具</a>
    </div>
  </div>
</nav>

<main class="container py-3">
  <div class="row g-3">
    <div class="col-12 col-lg-7">
      <div class="card shadow-sm">
        <div class="card-body">
          <h1 class="h4 mb-2"><?= e($title) ?></h1>
          <div class="text-muted small mb-3">
            <?php if ($region): ?><?= e($region) ?> · <?php endif; ?>
            坐标：<span class="mono"><?= e($lat) ?>, <?= e($lon) ?></span>
            <?php if ($updated): ?> · 更新：<?= e($updated) ?><?php endif; ?>
          </div>

          <?php if (!empty($spot['note'])): ?>
            <div class="mb-3">
              <div class="fw-semibold mb-1">备注</div>
              <div class="small" style="white-space:pre-wrap;"><?= e((string)$spot['note']) ?></div>
            </div>
          <?php endif; ?>

          <div class="d-flex flex-wrap gap-2">
            <span class="badge text-bg-success">👍 <?= (int)$up ?></span>
            <span class="badge text-bg-danger">👎 <?= (int)$down ?></span>
            <a class="btn btn-outline-secondary btn-sm" target="_blank"
               href="https://api.map.baidu.com/marker?location=<?= e($lat) ?>,<?= e($lon) ?>&title=<?= rawurlencode($title) ?>&content=<?= rawurlencode($region) ?>&output=html&src=diaoyu.0unit.com">
              打开百度地图
            </a>
          </div>

          <hr class="my-3">

          <div class="text-muted small">
            提示：本页是搜索引擎可收录的钓点详情页；实时天气/潮汐请回到首页地图工具查看。
          </div>
        </div>
      </div>
    </div>

    <div class="col-12 col-lg-5">
      <div class="card shadow-sm">
        <div class="card-body">
          <div class="fw-semibold mb-2">附近 10 公里内钓点（最多 15 条）</div>
          <?php if (!$near): ?>
            <div class="text-muted small">暂无更多附近钓点。</div>
          <?php else: ?>
            <div class="list-group list-group-flush">
              <?php foreach ($near as $n): ?>
                <?php
                  $nt = trim((string)$n['title']); if ($nt==='') $nt='钓点 #'.(int)$n['id'];
                  $dist = number_format((float)$n['dist_km'], 2);
                ?>
                <a class="list-group-item list-group-item-action d-flex justify-content-between align-items-center"
                   href="/spot.php?id=<?= (int)$n['id'] ?>">
                  <div>
                    <div class="fw-semibold small"><?= e($nt) ?></div>
                    <div class="text-muted small">距离约 <?= e($dist) ?> km · 👍 <?= (int)$n['up_count'] ?> / 👎 <?= (int)$n['down_count'] ?></div>
                  </div>
                  <span class="text-muted small">#<?= (int)$n['id'] ?></span>
                </a>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <?php if ($province || $city): ?>
      <div class="mt-3">
        <a class="btn btn-outline-dark w-100"
           href="/city.php?province=<?= rawurlencode($province) ?><?= $city ? ('&city='.rawurlencode($city)) : '' ?>">
          查看 <?= e($province ?: '该地区') ?><?= $city ? (' · '.$city) : '' ?> 钓点列表
        </a>
      </div>
      <?php endif; ?>
    </div>
  </div>
</main>

<footer class="container pb-4 pt-2 text-center text-muted small">
  © <?= date('Y') ?> <?= e($host) ?>
</footer>

</body>
</html>
