<?php
declare(strict_types=1);

require_once __DIR__ . '/core/app/bootstrap.php';

$pdo = db();

function setting(PDO $pdo, string $k, string $d=''): string {
  try {
    $st = $pdo->prepare("SELECT v FROM site_settings WHERE k=? LIMIT 1");
    $st->execute([$k]);
    $v = $st->fetchColumn();
    return $v !== false ? trim((string)$v) : $d;
  } catch (Throwable $e) { return $d; }
}

function esc(string $s): string {
  return htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
}

$siteUrl = rtrim(setting($pdo, 'site_url', ''), '/');
if ($siteUrl === '') {
  // fallback: host'tan türet
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $siteUrl = $scheme . '://' . $host;
}

header('Content-Type: application/xml; charset=utf-8');

$urls = [];

/* Homepage */
$urls[] = [
  'loc' => $siteUrl . '/',
  'lastmod' => date('Y-m-d'),
  'changefreq' => 'daily',
  'priority' => '1.0'
];

/* Site pages */
try {
  // is_indexable yoksa da patlamasın
  $hasIndexable = true;
  try { $pdo->query("SELECT `is_indexable` FROM `site_pages` LIMIT 0"); } catch (Throwable $e) { $hasIndexable = false; }

  $sql = "SELECT slug, updated_at, created_at FROM site_pages";
  if ($hasIndexable) $sql .= " WHERE is_indexable=1";
  $sql .= " ORDER BY id DESC LIMIT 5000";

  $st = $pdo->query($sql);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  foreach ($rows as $r) {
    $slug = trim((string)($r['slug'] ?? ''));
    if ($slug === '' || $slug === 'home' || $slug === '/') continue;

    // kurumsal sayfa url varsayımı: /site.php?slug=...
    // sende mod_rewrite varsa /{slug} de olabilir; gerekiyorsa sonra değiştiririz.
    $loc = $siteUrl . '/site.php?slug=' . rawurlencode($slug);

    $dt = (string)($r['updated_at'] ?? '');
    if ($dt === '') $dt = (string)($r['created_at'] ?? '');
    $last = $dt !== '' ? date('Y-m-d', strtotime($dt)) : date('Y-m-d');

    $urls[] = [
      'loc' => $loc,
      'lastmod' => $last,
      'changefreq' => 'weekly',
      'priority' => '0.6'
    ];
  }
} catch (Throwable $e) {}

/* Products */
try {
  $hasIndexable = true;
  try { $pdo->query("SELECT `is_indexable` FROM `shop_products` LIMIT 0"); } catch (Throwable $e) { $hasIndexable = false; }

  $sql = "SELECT slug, updated_at, created_at FROM shop_products";
  if ($hasIndexable) $sql .= " WHERE is_indexable=1";
  $sql .= " ORDER BY id DESC LIMIT 50000";

  $st = $pdo->query($sql);
  $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

  foreach ($rows as $r) {
    $slug = trim((string)($r['slug'] ?? ''));
    if ($slug === '') continue;

    // mağaza url varsayımı: /magaza/product.php?slug=...
    $loc = $siteUrl . '/magaza/product.php?slug=' . rawurlencode($slug);

    $dt = (string)($r['updated_at'] ?? '');
    if ($dt === '') $dt = (string)($r['created_at'] ?? '');
    $last = $dt !== '' ? date('Y-m-d', strtotime($dt)) : date('Y-m-d');

    $urls[] = [
      'loc' => $loc,
      'lastmod' => $last,
      'changefreq' => 'weekly',
      'priority' => '0.7'
    ];
  }
} catch (Throwable $e) {}

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
foreach ($urls as $u) {
  echo "  <url>\n";
  echo "    <loc>" . esc($u['loc']) . "</loc>\n";
  echo "    <lastmod>" . esc($u['lastmod']) . "</lastmod>\n";
  echo "    <changefreq>" . esc($u['changefreq']) . "</changefreq>\n";
  echo "    <priority>" . esc($u['priority']) . "</priority>\n";
  echo "  </url>\n";
}
echo "</urlset>\n";