<?php
/**
 * sitemap.php - DYNAMIC SEO MAP GENERATOR
 * ---------------------------------------------------------------------------
 * This file connects to your database and generates a live XML map
 * for Google. It includes every OEM code and Image.
 * ---------------------------------------------------------------------------
 */

require_once __DIR__ . '/data_helpers.php';

// 1. Set Header so Google knows this is XML, not HTML
header("Content-Type: application/xml; charset=utf-8");

// 2. Base URL (CHANGE THIS TO YOUR REAL DOMAIN)
$base_url = "https://" . $_SERVER['HTTP_HOST'];

// 3. Output XML Header
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">';

// 4. Add Static Pages
$pages = ['index.php', 'contact.php', 'about.php'];
foreach ($pages as $page) {
    echo '<url>';
    echo '<loc>' . $base_url . '/' . $page . '</loc>';
    echo '<changefreq>daily</changefreq>';
    echo '<priority>1.0</priority>';
    echo '</url>';
}

// 5. Add Dynamic Parts (The "Deep Indexing")
$parts = get_all_parts(10000); // Fetch up to 10k items

foreach ($parts as $part) {
    echo '<url>';
    // Link to the specific part
    echo '<loc>' . $base_url . '/part_detail.php?id=' . $part['id'] . '</loc>';
    echo '<lastmod>' . date('Y-m-d', strtotime($part['created'])) . '</lastmod>';
    echo '<changefreq>weekly</changefreq>';
    echo '<priority>0.8</priority>';

    // Image SEO (Crucial for Google Images)
    if (!empty($part['images'])) {
        $imgs = is_string($part['images']) ? json_decode($part['images'], true) : $part['images'];
        if (is_array($imgs) && count($imgs) > 0) {
            echo '<image:image>';
            echo '<image:loc>' . htmlspecialchars($imgs[0]) . '</image:loc>';
            echo '<image:title>' . htmlspecialchars($part['part_name'] . ' ' . $part['oem_number']) . '</image:title>';
            echo '</image:image>';
        }
    }
    echo '</url>';
}

echo '</urlset>';
?>