<?php
/**
 * sitemap.php — dynamic sitemap generator
 *
 * Replaces the old hand-written sitemap.xml. Static marketing pages are
 * listed below; products and blog posts are pulled live from the database
 * so every new product / post is automatically included with no manual
 * editing required.
 *
 * /sitemap.xml is rewritten to this file via .htaccess (see notes), so the
 * URL already submitted in Google Search Console keeps working.
 */

require_once __DIR__ . '/includes/db.php';

header('Content-Type: application/xml; charset=UTF-8');
header('X-Robots-Tag: noindex'); // the sitemap file itself shouldn't be indexed as a page

$base = 'https://mobile-team.co.za';

function sm_esc(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_XML1, 'UTF-8');
}

function sm_url(string $loc, ?string $lastmod, string $changefreq, string $priority): string {
    $xml  = "  <url>\n";
    $xml .= "    <loc>" . sm_esc($loc) . "</loc>\n";
    if ($lastmod) {
        $xml .= "    <lastmod>" . sm_esc($lastmod) . "</lastmod>\n";
    }
    $xml .= "    <changefreq>{$changefreq}</changefreq>\n";
    $xml .= "    <priority>{$priority}</priority>\n";
    $xml .= "  </url>\n";
    return $xml;
}

$today = date('Y-m-d');

// ── Static marketing / info pages ─────────────────────────────────────────
// (Private/account/auth/transactional/admin/utility pages are intentionally
//  excluded — they are noindex and have no SEO value.)
$static_pages = [
    ['/',                                          $today, 'weekly',  '1.0'],
    ['/services.php',                              $today, 'weekly',  '0.9'],
    ['/products.php',                              $today, 'weekly',  '0.9'],
    ['/unlocknow.php',                             $today, 'daily',   '0.9'],
    ['/unlock-prices.php',                         $today, 'weekly',  '0.9'],
    ['/blog.php',                                  $today, 'daily',   '0.8'],
    ['/reviews.php',                               $today, 'weekly',  '0.7'],
    ['/iphone-unlock-cost-south-africa.php',       $today, 'monthly', '0.8'],
    ['/icloud-unlock-service-near-me.php',         $today, 'monthly', '0.8'],
    ['/unlock-vodacom.php',                        $today, 'monthly', '0.8'],
    ['/unlock-mtn.php',                            $today, 'monthly', '0.8'],
    ['/icloud-removal.php',                        $today, 'monthly', '0.8'],
    ['/iphone-passcode-unlock.php',                $today, 'monthly', '0.8'],
    ['/unlock-activation-lock.php',                $today, 'monthly', '0.8'],
    ['/unlock-disabled.php',                       $today, 'monthly', '0.8'],
    ['/macbook-unlock.php',                        $today, 'monthly', '0.8'],
    ['/blacklist-removal.php',                     $today, 'monthly', '0.8'],
    ['/frp-unlock.php',                            $today, 'monthly', '0.8'],
    ['/johannesburg.php',                          $today, 'monthly', '0.7'],
    ['/about.php',                                 $today, 'yearly',  '0.6'],
    ['/support.php',                               $today, 'monthly', '0.6'],
    ['/terms.php',                                 $today, 'yearly',  '0.5'],
    ['/privacy.php',                               $today, 'yearly',  '0.5'],
];

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

foreach ($static_pages as [$path, $lastmod, $freq, $priority]) {
    echo sm_url($base . $path, $lastmod, $freq, $priority);
}

// ── Services (one URL per active service) ─────────────────────────────────
try {
    $stmt = $pdo->query("SELECT id, updated_at, created_at FROM services WHERE status = 'active'");
    while ($row = $stmt->fetch()) {
        $lastmod = $row['updated_at'] ?? $row['created_at'] ?? null;
        $lastmod = $lastmod ? date('Y-m-d', strtotime($lastmod)) : null;
        echo sm_url(
            $base . '/service_detail.php?id=' . (int)$row['id'],
            $lastmod,
            'weekly',
            '0.7'
        );
    }
} catch (Throwable $e) {
    error_log('[sitemap.php] services query failed: ' . $e->getMessage());
}

// ── Products (one URL per active product) ────────────────────────────────
try {
    $stmt = $pdo->query("SELECT id, updated_at, created_at FROM products WHERE status = 'active'");
    while ($row = $stmt->fetch()) {
        $lastmod = $row['updated_at'] ?? $row['created_at'] ?? null;
        $lastmod = $lastmod ? date('Y-m-d', strtotime($lastmod)) : null;
        echo sm_url(
            $base . '/product_detail.php?id=' . (int)$row['id'],
            $lastmod,
            'weekly',
            '0.7'
        );
    }
} catch (Throwable $e) {
    error_log('[sitemap.php] products query failed: ' . $e->getMessage());
}

// ── Blog posts (one URL per published post) ──────────────────────────────
try {
    $stmt = $pdo->query("SELECT slug, updated_at, created_at FROM blog_posts WHERE status = 'published'");
    while ($row = $stmt->fetch()) {
        $lastmod = $row['updated_at'] ?? $row['created_at'] ?? null;
        $lastmod = $lastmod ? date('Y-m-d', strtotime($lastmod)) : null;
        echo sm_url(
            $base . '/blog_post.php?slug=' . rawurlencode($row['slug']),
            $lastmod,
            'monthly',
            '0.6'
        );
    }
} catch (Throwable $e) {
    error_log('[sitemap.php] blog_posts query failed: ' . $e->getMessage());
}

echo '</urlset>';
