<?php
declare(strict_types=1);

/**
 * /sitemap.php
 * Dynamiczny sitemap: strona główna, ogłoszenia + oferty z bazy (lokale.status='aktywny').
 * Bez logowań, bez kotwic (#), tylko kanoniczne URL-e.
 */

require_once __DIR__ . '/includes/db.php'; // powinien zdefiniować $pdo (PDO)

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

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

function iso8601(?string $ts = null): string {
  try {
    return ($ts ? (new DateTime($ts)) : new DateTime())->format('c');
  } catch (Throwable $e) {
    return (new DateTime())->format('c');
  }
}

// Stałe wpisy (możesz dorzucić kolejne stałe podstrony, gdy się pojawią)
$static = [
  [ 'loc' => $base . '/',                'changefreq' => 'daily',   'priority' => '0.9', 'lastmod' => iso8601() ],
  [ 'loc' => $base . '/ogloszenia.php',  'changefreq' => 'hourly',  'priority' => '0.8', 'lastmod' => iso8601() ],
  [ 'loc' => $base . '/serwisanci.php', 'changefreq' => 'daily',   'priority' => '0.7', 'lastmod' => iso8601() ],
  // przykład gdy dodasz politykę/regulamin:
  // [ 'loc' => $base . '/polityka-prywatnosci', 'changefreq' => 'yearly', 'priority' => '0.4', 'lastmod' => iso8601() ],
];

// Oferty z bazy
$listings = [];
if (isset($pdo) && $pdo instanceof PDO) {
  try {
    // próbujemy uprzejmie wykryć kolumny daty; jeśli ich nie ma – fallback to NOW()
    $cols = $pdo->query("SHOW COLUMNS FROM lokale")->fetchAll(PDO::FETCH_COLUMN, 0);
    $hasUpdated = in_array('updated_at', $cols ?? [], true);
    $hasCreated = in_array('created_at', $cols ?? [], true);

    $dateExpr = 'NOW()';
    if ($hasUpdated && $hasCreated) {       $dateExpr = 'GREATEST(updated_at, created_at)';
    } elseif ($hasUpdated) {                $dateExpr = 'updated_at';
    } elseif ($hasCreated) {                $dateExpr = 'created_at'; }

    $sql = "
      SELECT slug, $dateExpr AS lastmod
        FROM lokale
       WHERE status='aktywny' AND slug<>'' 
       ORDER BY COALESCE($dateExpr, NOW()) DESC
       LIMIT 5000
    ";
    $stmt = $pdo->query($sql);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $url = $base . '/oferta/' . rawurlencode((string)$row['slug']);
      $listings[] = [
        'loc'        => $url,
        'changefreq' => 'daily',
        'priority'   => '0.7',
        'lastmod'    => iso8601($row['lastmod'] ?? null),
      ];
    }
  } catch (Throwable $e) {
    // cicho pomijamy błędy – sitemap i tak się wygeneruje ze statycznych
  }
}

// Render XML
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach (array_merge($static, $listings) as $u): ?>
  <url>
    <loc><?= htmlspecialchars($u['loc'], ENT_QUOTES, 'UTF-8') ?></loc>
    <lastmod><?= htmlspecialchars($u['lastmod'], ENT_QUOTES, 'UTF-8') ?></lastmod>
    <changefreq><?= $u['changefreq'] ?></changefreq>
    <priority><?= $u['priority'] ?></priority>
  </url>
<?php endforeach; ?>
</urlset>
