<?php
/**
 * Dynamic XML sitemap for ABL Business Ltd.
 *
 * Served at /sitemap.xml via the rewrite rule in .htaccess.
 * Regenerates on every request, so newly published blog posts, case
 * studies, guides and legal pages appear automatically with no manual step.
 */

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/includes/functions.php';

header('Content-Type: application/xml; charset=utf-8');

$base = rtrim(SITE_URL, '/');

/** Collected URL entries. */
$urls = [];

/**
 * Add a single URL to the sitemap.
 */
function sm_add(array &$urls, string $base, string $path, string $changefreq, string $priority, ?string $lastmod = null): void {
    $loc = $base . $path;
    $urls[] = [
        'loc'        => $loc,
        'lastmod'    => $lastmod ?: date('Y-m-d'),
        'changefreq' => $changefreq,
        'priority'   => $priority,
    ];
}

// ── Static pages ────────────────────────────────────────────────────────
// Paths match the live navigation. Broken root-level duplicates of the
// service pages are deliberately excluded.
$static = [
    ['/',                              'weekly',  '1.0'],
    ['/about',                         'monthly', '0.8'],
    ['/contact',                       'monthly', '0.8'],
    ['/finance-discovery-call',        'monthly', '0.8'],
    ['/insights',                      'weekly',  '0.9'],
    ['/abl-fx',                        'monthly', '0.7'],
    ['/services/business-finance',     'monthly', '0.9'],
    ['/services/property-finance',     'monthly', '0.9'],
    ['/services/acquisition-finance',  'monthly', '0.9'],
    ['/services/vat-funding',          'monthly', '0.8'],
];
foreach ($static as $s) {
    sm_add($urls, $base, $s[0], $s[1], $s[2]);
}

// ── Blog posts, case studies and guides ─────────────────────────────────
try {
    $st = db()->query(
        "SELECT slug, published_date, updated_at, category
           FROM blog_posts
          WHERE status = 'published' AND slug <> ''
       ORDER BY published_date DESC"
    );
    foreach ($st->fetchAll() as $post) {
        $lastmod = $post['updated_at'] ?: $post['published_date'];
        $lastmod = $lastmod ? date('Y-m-d', strtotime($lastmod)) : date('Y-m-d');

        // Guides and case studies are cornerstone content, so rank them higher.
        $priority = ($post['category'] === 'guide' || $post['category'] === 'case_study')
            ? '0.8'
            : '0.6';

        sm_add($urls, $base, '/insights/' . rawurlencode($post['slug']), 'monthly', $priority, $lastmod);
    }
} catch (Throwable $e) {
    // A database problem must not produce a broken sitemap - skip these entries.
}

// ── Legal pages ─────────────────────────────────────────────────────────
try {
    $st = db()->query("SELECT slug, updated_at FROM legal_pages WHERE slug <> '' ORDER BY slug ASC");
    foreach ($st->fetchAll() as $page) {
        $lastmod = !empty($page['updated_at']) ? date('Y-m-d', strtotime($page['updated_at'])) : date('Y-m-d');
        sm_add($urls, $base, '/legal/' . rawurlencode($page['slug']), 'yearly', '0.3', $lastmod);
    }
} catch (Throwable $e) {
    // Legal pages are optional - carry on without them.
}

// ── Output ──────────────────────────────────────────────────────────────
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<?php foreach ($urls as $u): ?>
  <url>
    <loc><?= htmlspecialchars($u['loc'], ENT_XML1, 'UTF-8') ?></loc>
    <lastmod><?= $u['lastmod'] ?></lastmod>
    <changefreq><?= $u['changefreq'] ?></changefreq>
    <priority><?= $u['priority'] ?></priority>
  </url>
<?php endforeach; ?>
</urlset>
