<?php
// /sitemap.php — gjeneron sitemap.xml + image tags
@ini_set('display_errors', 0);
header('Content-Type: application/xml; charset=utf-8');

$BASE = 'https://euklitvangjeli.com';
$now  = date('c');
$urls = [];

// helper
$add = function(string $loc, string $lastmod=null, string $priority='0.80', string $changefreq='weekly', array $images=[] ) use (&$urls,$BASE,$now){
  $urls[] = [
    'loc' => $BASE . $loc,
    'lastmod' => $lastmod ?: $now,
    'priority' => $priority,
    'changefreq' => $changefreq,
    'images' => $images,
  ];
};

// bazat
$add('/', $now, '1.00', 'daily');
$add('/booking/', $now, '0.90', 'daily');
$add('/portfolio/', $now, '0.70', 'weekly');
$add('/giftcard/', null, '0.60', 'monthly');
$add('/privacy.php', null, '0.30', 'yearly');
$add('/terms.php',   null, '0.30', 'yearly');

// nëse ka DB, shto çdo set portofoli + imazhin kryesor
if (file_exists(__DIR__.'/core/db.php')) {
  require __DIR__.'/core/db.php';
  try {
    $rows = DB::run("
      SELECT p.slug, COALESCE(p.updated_at, p.created_at) AS m,
             (SELECT image_url FROM portfolio_images WHERE portfolio_id=p.id 
              ORDER BY is_primary DESC, sort_order ASC, id ASC LIMIT 1) AS cover,
             p.title
      FROM portfolio p
      WHERE p.is_active=1
      ORDER BY m DESC
      LIMIT 500
    ")->fetchAll();

    foreach ($rows as $r) {
      $img = [];
      if (!empty($r['cover'])) {
        $img[] = [
          'loc'   => (strpos($r['cover'], 'http')===0 ? $r['cover'] : $BASE.$r['cover']),
          'title' => $r['title'] ?: 'Portfolio',
        ];
      }
      $add('/portfolio/view.php?slug='.rawurlencode($r['slug']),
           date('c', strtotime($r['m'] ?? $now)),
           '0.70','weekly',$img);
    }
  } catch (Throwable $e) { /* ok, vazhdo pa DB */ }
}

// printo XML
echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<?php foreach ($urls as $u): ?>
  <url>
    <loc><?=htmlspecialchars($u['loc'], ENT_XML1)?></loc>
    <lastmod><?=htmlspecialchars($u['lastmod'], ENT_XML1)?></lastmod>
    <changefreq><?=$u['changefreq']?></changefreq>
    <priority><?=$u['priority']?></priority>
    <?php foreach (($u['images'] ?? []) as $im): ?>
      <image:image>
        <image:loc><?=htmlspecialchars($im['loc'], ENT_XML1)?></image:loc>
        <?php if (!empty($im['title'])): ?>
        <image:title><?=htmlspecialchars($im['title'], ENT_XML1)?></image:title>
        <?php endif; ?>
      </image:image>
    <?php endforeach; ?>
  </url>
<?php endforeach; ?>
</urlset>
