<?php
declare(strict_types=1);

require_once __DIR__ . '/../app/macro.php';

$category = preg_replace('~[^A-Za-z0-9_\-]+~', '', (string)($_GET['category'] ?? ''));
$id       = max(0, (int)($_GET['id'] ?? 0));

$ctx = [
    'category' => $category,
    'id'       => $id,
    'query'    => $_GET,
];

// ユーザーが編集するテンプレHTMLの場所（任意）
$tplPath = tpcms_templates_dir() . '/detail.html';

// 読み込み（無ければフォールバック）
if (is_file($tplPath)) {
    $html = (string)file_get_contents($tplPath);
} else {
    $css     = h(asset_url('/admin/assets/admin.css', true));
    $backUrl = h(url_for('/list', ['category' => $category]));
    $html = <<<HTML
<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>詳細｜tpcms</title>
  <link rel="stylesheet" href="{$css}">
  <style>
    .tpcms-detail{max-width:980px;margin:0 auto}
    .detail-media img,.detail-media video{width:100%;height:auto;display:block;margin-bottom:1rem}
    .tpcms-detail table{width:100%;border-collapse:collapse;margin-top:1rem}
    .tpcms-detail th,.tpcms-detail td{border:1px solid #ddd;padding:.5rem;text-align:left;vertical-align:top}
    .map-area{margin-top:1.5rem}
  </style>
</head>
<body>
  <main class="container">
    <p><a href="{$backUrl}">&laquo; 一覧に戻る</a></p>
    {{DETAIL}}
    <div class="map-area">
      {{MAP}}
    </div>
  </main>
</body>
</html>
HTML;
}

// プレースホルダー置換して出力
echo macro_render($html, $ctx);
