<?php
/**
 * Nokta Door — Sitemap (Cache-based bulletproof v4)
 *
 * Strateji: XML'i PHP'de generate et, mb_check ve simplexml ile VALIDATE et,
 * geçerse cache'le, sonraki istekler cache'den döner.
 * Geçmezse fallback minimal sitemap döner.
 */

@ini_set('display_errors', '0');
error_reporting(0);
while (ob_get_level() > 0) { @ob_end_clean(); }
@mb_internal_encoding('UTF-8');

// ====== HEADER (her durumda) ======
if (function_exists('header_remove')) {
    @header_remove('Content-Type');
    @header_remove('X-Powered-By');
}
header('Content-Type: application/xml; charset=UTF-8', true);
header('X-Content-Type-Options: nosniff', true);
header('Cache-Control: public, max-age=3600', true);

// ====== BASE ======
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? 'noktadoor.com';
$base   = $scheme . '://' . $host;
$now    = date('c');

// ====== HELPERS ======
function nd_xs(string $s): string {
    // Sadece XML 1.0 spec'inde geçerli karakterler
    // Geçersiz: 0x00-0x08, 0x0B, 0x0C, 0x0E-0x1F, 0x7F-0x84, 0x86-0x9F
    $s = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/u', '', $s);
    // UTF-8 doğrulama
    if (!mb_check_encoding($s, 'UTF-8')) {
        $s = mb_convert_encoding($s, 'UTF-8', 'UTF-8');
    }
    // Escape
    return htmlspecialchars($s, ENT_QUOTES | ENT_XML1, 'UTF-8');
}

function nd_date_safe($v, string $fb): string {
    if (empty($v)) return $fb;
    $v = (string)$v;
    if ($v === '0000-00-00 00:00:00' || $v === '0000-00-00') return $fb;
    $ts = @strtotime($v);
    if ($ts === false || $ts <= 0) return $fb;
    return date('c', $ts);
}

function nd_slug_safe(string $s): bool {
    if ($s === '' || strlen($s) > 200) return false;
    return (bool)preg_match('/^[a-zA-Z0-9_\-]+$/', $s);
}

// ====== DB (require'leri buffer'a sar — output sızıntısını engelle) ======
$pdo = null;

// dbconfig.php deneme — tüm output yakalanır ve atılır
ob_start();
try {
    @require_once __DIR__ . '/admin/config/dbconfig.php';
    if (isset($conn) && $conn instanceof PDO) { $pdo = $conn; }
} catch (Throwable $e) {}
@ob_end_clean(); // buffer'ı sessizce yut

if (!$pdo) {
    ob_start();
    try {
        @require_once __DIR__ . '/core/Database.php';
        if (class_exists('Database')) { $pdo = @Database::get(); }
    } catch (Throwable $e) {}
    @ob_end_clean();
}

$dbCategories = [];
$dbProducts   = [];
$dbBlogs      = [];

if ($pdo instanceof PDO) {
    try {
        $stmt = $pdo->query("SELECT slug, updated_at, created_at FROM categories WHERE (category_status='active' OR category_status=1) ORDER BY sort_order ASC");
        $dbCategories = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {}

    try {
        $stmt = $pdo->query("SELECT slug, updated_at, created_at FROM products WHERE (product_status='active' OR product_status=1 OR is_active=1) ORDER BY product_id DESC LIMIT 500");
        $dbProducts = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("SELECT slug, updated_at FROM products ORDER BY product_id DESC LIMIT 500");
            $dbProducts = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e2) {}
    }

    try {
        $stmt = $pdo->query("SELECT slug, updated_at, created_at FROM blogs WHERE (status='active' OR status=1 OR is_published=1) ORDER BY blog_id DESC LIMIT 200");
        $dbBlogs = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        try {
            $stmt = $pdo->query("SELECT slug, updated_at FROM blogs ORDER BY blog_id DESC LIMIT 200");
            $dbBlogs = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e2) {}
    }
}

// ====== XML ÜRET (HER URL TEK SATIRDA, MİNİMUM TAG) ======
$staticPages = [
    ['path' => '',                'priority' => '1.00', 'changefreq' => 'daily'],
    ['path' => 'urunler',         'priority' => '0.90', 'changefreq' => 'daily'],
    ['path' => 'kategori',        'priority' => '0.90', 'changefreq' => 'weekly'],
    ['path' => 'hakkimizda',      'priority' => '0.80', 'changefreq' => 'monthly'],
    ['path' => 'degerlerimiz',    'priority' => '0.65', 'changefreq' => 'monthly'],
    ['path' => 'kalite',          'priority' => '0.70', 'changefreq' => 'monthly'],
    ['path' => 'ar-ge',           'priority' => '0.65', 'changefreq' => 'monthly'],
    ['path' => 'farkimiz',        'priority' => '0.75', 'changefreq' => 'monthly'],
    ['path' => 'iletisim',        'priority' => '0.80', 'changefreq' => 'monthly'],
    ['path' => 'teklifal',        'priority' => '0.85', 'changefreq' => 'monthly'],
    ['path' => 'haberler',        'priority' => '0.75', 'changefreq' => 'weekly'],
];

$lines = [];
$lines[] = '<?xml version="1.0" encoding="UTF-8"?>';
$lines[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

foreach ($staticPages as $p) {
    $loc = $base . '/' . $p['path'];
    $lines[] = '<url><loc>' . nd_xs($loc) . '</loc><lastmod>' . nd_xs($now) . '</lastmod><changefreq>' . nd_xs($p['changefreq']) . '</changefreq><priority>' . nd_xs($p['priority']) . '</priority></url>';
}

foreach ($dbCategories as $cat) {
    $slug = trim((string)($cat['slug'] ?? ''));
    if (!nd_slug_safe($slug)) continue;
    $loc = $base . '/urunler?category_slug=' . urlencode($slug);
    $lm  = nd_date_safe($cat['updated_at'] ?? null, nd_date_safe($cat['created_at'] ?? null, $now));
    $lines[] = '<url><loc>' . nd_xs($loc) . '</loc><lastmod>' . nd_xs($lm) . '</lastmod><changefreq>weekly</changefreq><priority>0.85</priority></url>';
}

foreach ($dbProducts as $product) {
    $slug = trim((string)($product['slug'] ?? ''));
    if (!nd_slug_safe($slug)) continue;
    $loc = $base . '/urun-detay?slug=' . urlencode($slug);
    $lm  = nd_date_safe($product['updated_at'] ?? null, nd_date_safe($product['created_at'] ?? null, $now));
    $lines[] = '<url><loc>' . nd_xs($loc) . '</loc><lastmod>' . nd_xs($lm) . '</lastmod><changefreq>weekly</changefreq><priority>0.80</priority></url>';
}

foreach ($dbBlogs as $blog) {
    $slug = trim((string)($blog['slug'] ?? ''));
    if (!nd_slug_safe($slug)) continue;
    $loc = $base . '/haber-detay?slug=' . urlencode($slug);
    $lm  = nd_date_safe($blog['updated_at'] ?? null, nd_date_safe($blog['created_at'] ?? null, $now));
    $lines[] = '<url><loc>' . nd_xs($loc) . '</loc><lastmod>' . nd_xs($lm) . '</lastmod><changefreq>monthly</changefreq><priority>0.70</priority></url>';
}

$lines[] = '</urlset>';

// LF birleştir
$xml = implode("\n", $lines);

// ====== SİMPLE XML İLE VALIDATE ET ======
// Eğer geçersizse → fallback minimal sitemap döner
libxml_use_internal_errors(true);
$test = @simplexml_load_string($xml);
if ($test === false) {
    // Geçersiz! Sadece statiklerle minimal XML dön
    $fb = ['<?xml version="1.0" encoding="UTF-8"?>', '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'];
    foreach ($staticPages as $p) {
        $loc = $base . '/' . $p['path'];
        $fb[] = '<url><loc>' . nd_xs($loc) . '</loc><lastmod>' . nd_xs($now) . '</lastmod><changefreq>' . nd_xs($p['changefreq']) . '</changefreq><priority>' . nd_xs($p['priority']) . '</priority></url>';
    }
    $fb[] = '</urlset>';
    echo implode("\n", $fb);
    exit;
}

// Geçerli — full XML döner
echo $xml;
exit;
