<?php
// 1. Include your existing database configuration
// This assumes includes/db-config.php defines $host, $db, $user, and $pass
require_once 'includes/db-config.php';

// If your config file uses a different variable naming convention (e.g., $db_host), 
// make sure the variables below match your file.
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
     $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
     // In production, log errors instead of echoing them for security
     error_log($e->getMessage());
     exit("Database connection failed.");
}

// 2. Set headers to output XML
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">';

// --- HELPER FUNCTION TO PRINT URLS ---
function print_url($loc, $lastmod, $priority) {
    echo '<url>';
    echo '<loc>' . htmlspecialchars($loc) . '</loc>';
    echo '<lastmod>' . date('Y-m-d', strtotime($lastmod)) . '</lastmod>';
    echo '<priority>' . $priority . '</priority>';
    echo '</url>';
}

// 3. Static Home Page
print_url("https://toyvista.com/", 'now', '1.0');
print_url("https://toyvista.com/blogs", 'now', '0.8');

// 4. Categories (toyvista.com/category-slug)
$stmt = $pdo->query("SELECT slug, created_at FROM Categories");
while ($row = $stmt->fetch()) {
    print_url("https://toyvista.com/{$row['slug']}", $row['created_at'], '0.9');
}

// 5. Subcategories (toyvista.com/products/subcategory-slug)
$stmt = $pdo->query("SELECT slug, created_at FROM Subcategories");
while ($row = $stmt->fetch()) {
    print_url("https://toyvista.com/products/{$row['slug']}", $row['created_at'], '0.8');
}

// 6. Products (toyvista.com/product/product-slug)
$stmt = $pdo->query("SELECT slug, created_at FROM Products WHERE slug IS NOT NULL");
while ($row = $stmt->fetch()) {
    print_url("https://toyvista.com/product/{$row['slug']}", $row['created_at'], '0.6');
}

// 7. Blogs (toyvista.com/blog/blog-slug)
$stmt = $pdo->query("SELECT slug, created_at FROM blogs WHERE slug IS NOT NULL");
while ($row = $stmt->fetch()) {
    print_url("https://toyvista.com/blog/{$row['slug']}", $row['created_at'], '0.7');
}

echo '</urlset>';