<?php
header("Content-Type: application/xml; charset=utf-8");

// DB CONNECTION
$conn = new mysqli("localhost", "fsrqglou_db_packfora", "KEGN!Qi_C!yT", "fsrqglou_db_packfora");

if ($conn->connect_error) {
    die("Database connection failed");
}

// XML START
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

<?php
// ======================================================
// 1. STATIC PAGES
// ======================================================
$staticPages = [
    "" => "1.00",
    "about" => "0.80",
    "our-capabilities" => "0.80",
    "leadership" => "0.80",
    "our-clients" => "0.80",
    "design-to-value" => "0.80",
    "packaging-innovation-and-engineering" => "0.80",
    "sustainability" => "0.80",
    "supply-chain-automation" => "0.80",
    "talent-flex" => "0.80",
    "packaging-procurement" => "0.80",
    "specification-management" => "0.80",
    "our-approach" => "0.80",
    "case-studies" => "0.80",
    "knowledge-centre" => "0.80",
    "packforum-2024" => "0.80",
    "explore-opportunities" => "0.80",
    "life-at-packfora" => "0.80",
    "contact-us" => "0.80",
    "maxmold" => "0.80"
];

foreach ($staticPages as $page => $priority) {
    ?>
    <url>
        <loc>https://packfora.com/<?php echo $page; ?></loc>
        <lastmod><?php echo date("c"); ?></lastmod>
        <changefreq>monthly</changefreq>
        <priority><?php echo $priority; ?></priority>
    </url>
    <?php
}

// ======================================================
// 2. BLOGS (DYNAMIC)
// ======================================================
$sql = "
    SELECT 
        slug,
        COALESCE(article_modified_time, publish_date, created_at) AS lastmod
    FROM tbl_blogs
    WHERE is_active = 1
    AND is_delete = '0'
    AND slug IS NOT NULL
    AND slug != ''
    AND slug NOT LIKE '%?%'
";

$result = $conn->query($sql);

if ($result && $result->num_rows > 0) {

    while ($row = $result->fetch_assoc()) {

        $slug = trim($row['slug']);

        // Extra safety: remove query params if any slipped
        $slug = strtok($slug, '?');

        // Last modified
        $lastmod = date("c", strtotime($row['lastmod']));

        // Dynamic priority (recent blogs get higher priority)
        $priority = "0.64";
        if (strtotime($row['lastmod']) > strtotime("-30 days")) {
            $priority = "0.80";
        }

        ?>
        <url>
            <loc>https://packfora.com/<?php echo htmlspecialchars($slug); ?></loc>
            <lastmod><?php echo $lastmod; ?></lastmod>
            <changefreq>weekly</changefreq>
            <priority><?php echo $priority; ?></priority>
        </url>
        <?php
    }
}
?>

</urlset>