<?php
// sitemap.php — havadurumu.website (şehir/ilçe sayfaları için dinamik sitemap)
// index.php ile aynı JSON veri modelini kullanır, TR-uyumlu slug üretir.

// -------------------- Ayarlar --------------------
const MAX_URLS_PER_SITEMAP = 45000;   // Google limitine (50k) tampon
const CHANGEFREQ_CITY      = 'daily';
const CHANGEFREQ_DISTRICT  = 'daily';
const PRIORITY_HOME        = '1.0';
const PRIORITY_CITY        = '0.8';
const PRIORITY_DISTRICT    = '0.7';

// İstersen sabitleyebilirsin:
// $BASE = 'https://havadurumu.website';
$BASE = null; // otomatik tespit (https tercihli)

// -------------------- Yardımcılar --------------------
ini_set('display_errors','0');
if(function_exists('mb_internal_encoding')){ mb_internal_encoding('UTF-8'); }

function toSlug($s){
  $map=['ç'=>'c','ğ'=>'g','ı'=>'i','ö'=>'o','ş'=>'s','ü'=>'u','Ç'=>'c','Ğ'=>'g','İ'=>'i','Ö'=>'o','Ş'=>'s','Ü'=>'u','Â'=>'a','Î'=>'i','Û'=>'u','â'=>'a','î'=>'i','û'=>'u'];
  $t=strtr($s,$map);
  $t=mb_strtolower($t,'UTF-8');
  $t=preg_replace('~[^a-z0-9]+~','-',$t);
  return trim($t,'-');
}
function xml($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function url_join($base,$path){
  return rtrim($base,'/').'/'.ltrim($path,'/');
}
function is_valid_slug($s){
  return (bool)preg_match('~^[a-z0-9-]+$~',$s);
}
function detect_base_url(){
  // https tercihli
  $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || 
           (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
  $scheme = $https ? 'https' : 'http';
  $host   = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'havadurumu.website';
  return $scheme.'://'.$host;
}
function today_iso(){ return gmdate('Y-m-d'); } // YYYY-MM-DD (Google için yeterli)

// -------------------- JSON yükle --------------------
$jsonPath = __DIR__ . '/data/cities.tr.json';
$citiesRaw = [];
if (is_file($jsonPath)) {
  $json = file_get_contents($jsonPath);
  $citiesRaw = json_decode($json, true, 512, JSON_INVALID_UTF8_SUBSTITUTE);
}

if (!is_array($citiesRaw) || !$citiesRaw) {
  // Fallback — index.php ile uyumlu minimum set
  $citiesRaw = [
    ['name'=>'İstanbul','slug'=>'istanbul','districts'=>[
      ['name'=>'Kadıköy','slug'=>'kadikoy'],
      ['name'=>'Beşiktaş','slug'=>'besiktas'],
    ]],
    ['name'=>'Ankara','slug'=>'ankara','districts'=>[
      ['name'=>'Çankaya','slug'=>'cankaya'],
      ['name'=>'Keçiören','slug'=>'kecioren'],
    ]],
    ['name'=>'İzmir','slug'=>'izmir','districts'=>[
      ['name'=>'Konak','slug'=>'konak'],
      ['name'=>'Karşıyaka','slug'=>'karsiyaka'],
    ]],
  ];
}

// -------------------- URL listesi üret --------------------
$BASE = $BASE ?: detect_base_url();
$urls = [];

// Ana sayfa
$urls[] = [
  'loc'        => url_join($BASE, '/'),
  'lastmod'    => today_iso(),
  'changefreq' => 'hourly',
  'priority'   => PRIORITY_HOME,
];

// Şehir + ilçe URL'leri
foreach ($citiesRaw as $c) {
  $cName = $c['name'] ?? '';
  if ($cName==='') continue;

  // Şehir slug (JSON'da varsa al, yoksa üret; bozuksa düzelt)
  $cSlug = $c['slug'] ?? '';
  if ($cSlug==='' || !is_valid_slug($cSlug)) {
    $cSlug = toSlug($cName);
  }

  // Şehir sayfası
  $urls[] = [
    'loc'        => url_join($BASE, "/{$cSlug}-hava-durumu/"),
    'lastmod'    => today_iso(),
    'changefreq' => CHANGEFREQ_CITY,
    'priority'   => PRIORITY_CITY,
  ];

  // İlçeler
  $districts = is_array($c['districts'] ?? null) ? $c['districts'] : [];
  foreach ($districts as $d) {
    $dName = $d['name'] ?? '';
    if ($dName==='') continue;

    $dSlug = $d['slug'] ?? '';
    $auto  = toSlug($dName);
    if ($dSlug==='' || !is_valid_slug($dSlug)) {
      $dSlug = $auto;
    }

    $urls[] = [
      'loc'        => url_join($BASE, "/{$cSlug}-{$dSlug}-hava-durumu/"),
      'lastmod'    => today_iso(),
      'changefreq' => CHANGEFREQ_DISTRICT,
      'priority'   => PRIORITY_DISTRICT,
    ];
  }
}

// -------------------- Çıktı modu: index mi parça mı? --------------------
$total = count($urls);
$needIndex = ($total > MAX_URLS_PER_SITEMAP);

// Cache-friendly headerlar
header('Content-Type: application/xml; charset=utf-8');
header('X-Robots-Tag: noarchive'); // tercih
header('Cache-Control: public, max-age=3600');

// İsteğe göre parça döndür
$part = isset($_GET['part']) ? max(1, (int)$_GET['part']) : null;

// -------------------- Sitemap-Index --------------------
if ($needIndex && !$part) {
  // Parça sayısı
  $parts = (int)ceil($total / MAX_URLS_PER_SITEMAP);
  echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
  echo '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";

  for ($i=1; $i<=$parts; $i++){
    $loc = url_join($BASE, '/sitemap.php?part='.$i);
    // Eğer .htaccess ile /sitemap.xml rewritelıyorsan, şunu kullanabilirsin:
    // $loc = url_join($BASE, '/sitemap.xml?part='.$i);
    echo "  <sitemap>\n";
    echo '    <loc>'.xml($loc)."</loc>\n";
    echo '    <lastmod>'.today_iso()."</lastmod>\n";
    echo "  </sitemap>\n";
  }

  echo "</sitemapindex>";
  exit;
}

// -------------------- Tek parça ya da istenen parça URLSET --------------------
$start = 0;
$len   = $total;

if ($needIndex) {
  $start = ($part-1) * MAX_URLS_PER_SITEMAP;
  if ($start >= $total) { http_response_code(404); exit; }
  $len   = min(MAX_URLS_PER_SITEMAP, $total - $start);
}

echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";

$end = $start + $len;
for ($i=$start; $i<$end; $i++){
  $u = $urls[$i];
  echo "  <url>\n";
  echo '    <loc>'.xml($u['loc'])."</loc>\n";
  if (!empty($u['lastmod']))    echo '    <lastmod>'.xml($u['lastmod'])."</lastmod>\n";
  if (!empty($u['changefreq'])) echo '    <changefreq>'.xml($u['changefreq'])."</changefreq>\n";
  if (!empty($u['priority']))   echo '    <priority>'.xml($u['priority'])."</priority>\n";
  echo "  </url>\n";
}

echo "</urlset>";
