<?php
header("Content-Type: application/xml; charset=utf-8");
$base = "https://instanttoolspro.com";

// ── DB Connection ────────────────────────────────────────────
function getDB() {
    static $pdo = null;
    if (!$pdo) {
        try {
            $pdo = new PDO('mysql:host=localhost;dbname=instanttoolspro_cms;charset=utf8mb4', 'itp_admin', 'Danwantxbase5711');
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(Exception $e) { $pdo = null; }
    }
    return $pdo;
}

// ── Scan PHP tool pages ───────────────────────────────────────
function scanPages($dir, $ignore = []) {
    $defaultIgnore = ["header.php","footer.php","config.php","sitemap.php","download.php","index.php"];
    $ignore = array_merge($defaultIgnore, $ignore);
    $files  = glob($dir . "/*.php");
    $urls   = [];
    foreach ($files as $file) {
        $name = basename($file);
        if (in_array($name, $ignore)) continue;
        $url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
        $url = str_replace(".php", "", $url);
        $url = str_replace("//", "/", $url);
        $urls[] = $url;
    }
    $indexFile = $dir . "/index.php";
    if (file_exists($indexFile)) {
        $url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $indexFile);
        $url = dirname($url) . "/";
        $url = str_replace("//", "/", $url);
        $urls[] = $url;
    }
    return $urls;
}

// ── Priority ─────────────────────────────────────────────────
function getPriority($page) {
    if ($page === "/")                              return "1.0";
    if (strpos($page, "/pdf-tools/") !== false)    return "0.9";
    if (strpos($page, "/image-tools/") !== false)  return "0.9";
    if (strpos($page, "/ai-tools/") !== false)     return "0.9";
    if (strpos($page, "/finance-tools/") !== false) return "0.8";
    if (strpos($page, "/utility-tools/") !== false) return "0.8";
    if ($page === "/blog/")                         return "0.8";
    if (strpos($page, "/blog/") !== false)          return "0.7";
    return "0.6";
}

// ── Changefreq ────────────────────────────────────────────────
function getChangefreq($page) {
    if ($page === "/")                        return "daily";
    if (strpos($page, "/blog/") !== false)    return "monthly";
    if (strpos($page, "-tools/") !== false)   return "weekly";
    return "monthly";
}

// ── Collect all URLs ──────────────────────────────────────────
$root  = $_SERVER['DOCUMENT_ROOT'];
$urls  = [];

// 1. Homepage
$urls[] = ["loc" => "/", "lastmod" => date("Y-m-d"), "priority" => "1.0", "changefreq" => "daily"];

// 2. Tool category pages + individual tools
$toolDirs = ["pdf-tools", "image-tools", "finance-tools", "utility-tools", "ai-tools"];
foreach ($toolDirs as $dir) {
    if (is_dir("$root/$dir")) {
        foreach (scanPages("$root/$dir") as $page) {
            $urls[] = ["loc" => $page, "lastmod" => date("Y-m-d"), "priority" => getPriority($page), "changefreq" => getChangefreq($page)];
        }
    }
}

// 3. Main static pages
foreach (scanPages($root) as $page) {
    $urls[] = ["loc" => $page, "lastmod" => date("Y-m-d"), "priority" => getPriority($page), "changefreq" => getChangefreq($page)];
}

// 4. Blog index
$urls[] = ["loc" => "/blog/", "lastmod" => date("Y-m-d"), "priority" => "0.8", "changefreq" => "daily"];

// 5. CMS Blog posts from DATABASE ← MAIN FIX
$db = getDB();
if ($db) {
    $posts = $db->query("SELECT slug, updated_at, published_at FROM blog_posts WHERE status='published' ORDER BY published_at DESC")->fetchAll(PDO::FETCH_ASSOC);
    foreach ($posts as $post) {
        $lastmod = date("Y-m-d", strtotime($post['updated_at'] ?: $post['published_at'] ?: date('Y-m-d')));
        $urls[] = [
            "loc"        => "/blog/" . $post['slug'],
            "lastmod"    => $lastmod,
            "priority"   => "0.7",
            "changefreq" => "monthly"
        ];
    }
}

// 6. Remove duplicates by loc
$seen = [];
$unique = [];
foreach ($urls as $url) {
    if (!isset($seen[$url['loc']])) {
        $seen[$url['loc']] = true;
        $unique[] = $url;
    }
}

// Output XML
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9
        http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">
<?php foreach ($unique as $url): ?>
  <url>
    <loc><?= htmlspecialchars($base . $url['loc']) ?></loc>
    <lastmod><?= $url['lastmod'] ?></lastmod>
    <changefreq><?= $url['changefreq'] ?></changefreq>
    <priority><?= $url['priority'] ?></priority>
  </url>
<?php endforeach; ?>
</urlset>
