<?php
declare(strict_types=1);

// Error reporting
error_reporting(E_ALL);
ini_set('display_errors', 0);

require_once __DIR__ . '/bootstrap.php';

try {
    pt_ensure_schema();
} catch (Throwable $e) {
    header('Content-Type: application/xml; charset=utf-8');
    echo '<?xml version="1.0" encoding="UTF-8"?>';
    echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
    echo '<url><loc>https://firsatmax.net.tr/</loc><lastmod>' . date('Y-m-d') . '</lastmod><changefreq>daily</changefreq><priority>1.0</priority></url>';
    echo '</urlset>';
    exit;
}

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

// Get base URL - tam domain URL'si
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$basePath = rtrim(pt_base_path(), '/') . '/';

// Admin panelde ayarlanan domain varsa onu kullan
$site_domain = pt_config_get('site_domain', '');
if ($site_domain !== '') {
    $baseUrl = 'https://' . rtrim($site_domain, '/') . $basePath;
} else {
    $baseUrl = $protocol . '://' . $host . $basePath;
}

// Get all products for sitemap
$conn = pt_db();
$products = [];
try {
    $result = $conn->query("SELECT asin, title, category, updated_at FROM pt_products ORDER BY updated_at DESC LIMIT 50000");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $products[] = $row;
        }
    }
} catch (Throwable $e) {
    $products = [];
}

// Get categories
$categories = [];
try {
    $result = $conn->query("SELECT DISTINCT TRIM(category) as category FROM pt_products WHERE category != '' AND category IS NOT NULL ORDER BY category");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row['category'];
        }
    }
} catch (Throwable $e) {
    $categories = [];
}

// Get static pages
$staticPages = [
    ['url' => 'index.html', 'lastmod' => date('Y-m-d'), 'changefreq' => 'daily', 'priority' => '1.0'],
    ['url' => 'kategori.html', 'lastmod' => date('Y-m-d'), 'changefreq' => 'weekly', 'priority' => '0.8'],
    ['url' => 'son-eklenenler.html', 'lastmod' => date('Y-m-d'), 'changefreq' => 'daily', 'priority' => '0.9'],
    ['url' => 'indirimler.html', 'lastmod' => date('Y-m-d'), 'changefreq' => 'daily', 'priority' => '0.9'],
        ['url' => 'fiyati-yukselenler.html', 'lastmod' => date('Y-m-d'), 'changefreq' => 'daily', 'priority' => '0.7'],
];

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php foreach ($staticPages as $page): ?>
    <url>
        <loc><?php echo htmlspecialchars($baseUrl . $page['url'], ENT_XML1, 'UTF-8'); ?></loc>
        <lastmod><?php echo htmlspecialchars($page['lastmod'], ENT_XML1, 'UTF-8'); ?></lastmod>
        <changefreq><?php echo htmlspecialchars($page['changefreq'], ENT_XML1, 'UTF-8'); ?></changefreq>
        <priority><?php echo htmlspecialchars($page['priority'], ENT_XML1, 'UTF-8'); ?></priority>
    </url>
    <?php endforeach; ?>

    <?php foreach ($categories as $category): ?>
    <?php 
    $categorySlug = pt_slugify($category);
    $categoryUrl = $baseUrl . 'kategori-' . urlencode($categorySlug) . '.html';
    ?>
    <url>
        <loc><?php echo htmlspecialchars($categoryUrl, ENT_XML1, 'UTF-8'); ?></loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>weekly</changefreq>
        <priority>0.7</priority>
    </url>
    <?php endforeach; ?>

    <?php foreach ($products as $product): ?>
    <?php 
    $asin = trim($product['asin'] ?? '');
    $title = trim($product['title'] ?? '');
    $category = trim($product['category'] ?? '');
    $updatedAt = $product['updated_at'] ?? date('Y-m-d');
    
    if ($asin === '' || $title === '') continue;
    
    // Create pretty URL
    $slugBase = $title !== '' ? $title : $asin;
    $slug = pt_slugify($slugBase);
    $productUrl = $baseUrl . urlencode($slug) . '-' . urlencode($asin) . '.html';
    
    // Determine change frequency based on last update
    $daysSinceUpdate = (strtotime(date('Y-m-d')) - strtotime(substr($updatedAt, 0, 10))) / (60 * 60 * 24);
    $changefreq = $daysSinceUpdate <= 7 ? 'daily' : ($daysSinceUpdate <= 30 ? 'weekly' : 'monthly');
    $priority = $daysSinceUpdate <= 7 ? '0.8' : '0.6';
    ?>
    <url>
        <loc><?php echo htmlspecialchars($productUrl, ENT_XML1, 'UTF-8'); ?></loc>
        <lastmod><?php echo htmlspecialchars(substr($updatedAt, 0, 10), ENT_XML1, 'UTF-8'); ?></lastmod>
        <changefreq><?php echo htmlspecialchars($changefreq, ENT_XML1, 'UTF-8'); ?></changefreq>
        <priority><?php echo htmlspecialchars($priority, ENT_XML1, 'UTF-8'); ?></priority>
    </url>
    <?php endforeach; ?>
</urlset>
