<?php
// GPS Finance Group — Dynamic Sitemap
// DEPLOY TO: https://gpsfinance.com.au/sitemap.php
// Submit this URL directly to Google Search Console.
// No .htaccess rewrite needed.

// Output buffering prevents ANY whitespace leaking before <?xml
ob_start();

header('Content-Type: application/xml; charset=UTF-8');
header('Cache-Control: public, max-age=43200'); // cache 12 hours

define('BASE', 'https://gpsfinance.com.au');
define('TODAY', date('Y-m-d'));

// ── MAIN SITE PAGES ───────────────────────────────────────────────────────────
// priority: 1.0 = most important, 0.1 = least
// changefreq: always/hourly/daily/weekly/monthly/yearly/never
$pages = [

    // Core pages
    ['url' => '/',                          'priority' => '1.0', 'freq' => 'weekly'],
    ['url' => '/?page=solutions',           'priority' => '0.9', 'freq' => 'weekly'],
    ['url' => '/?page=about',               'priority' => '0.7', 'freq' => 'monthly'],
    ['url' => '/?page=contact',             'priority' => '0.8', 'freq' => 'monthly'],
    ['url' => '/?page=quote',               'priority' => '0.9', 'freq' => 'monthly'],
    ['url' => '/?page=partners',            'priority' => '0.7', 'freq' => 'monthly'],
    ['url' => '/?page=resources',           'priority' => '0.6', 'freq' => 'weekly'],

    // Product pages
    ['url' => '/?page=car-loans',           'priority' => '0.7', 'freq' => 'monthly'],
    ['url' => '/?page=personal-loans',      'priority' => '0.7', 'freq' => 'monthly'],

    // Industry pages
    ['url' => '/?page=trades',              'priority' => '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=transport',           'priority' => '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=hospitality',         'priority' => '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=professional-services','priority'=> '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=health',              'priority' => '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=education',           'priority' => '0.6', 'freq' => 'monthly'],
    ['url' => '/?page=b2b',                 'priority' => '0.6', 'freq' => 'monthly'],

    // Resource / guide pages
    ['url' => '/?page=guide-serviceability',   'priority' => '0.5', 'freq' => 'monthly'],
    ['url' => '/?page=guide-conduct-history',  'priority' => '0.5', 'freq' => 'monthly'],
    ['url' => '/?page=guide-application-delays','priority'=> '0.5', 'freq' => 'monthly'],
    ['url' => '/?page=guide-security-collateral','priority'=>'0.5', 'freq' => 'monthly'],
    ['url' => '/?page=guide-reading-financials','priority'=> '0.5', 'freq' => 'monthly'],
    ['url' => '/?page=guide-document-pack',    'priority' => '0.5', 'freq' => 'monthly'],

    // Tools
    ['url' => '/payday-super-calculator',   'priority' => '0.8', 'freq' => 'monthly'],

    // Legal (low priority but indexable)
    ['url' => '/?page=privacy',             'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/?page=terms',               'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/?page=credit-guide',        'priority' => '0.3', 'freq' => 'yearly'],
    ['url' => '/?page=complaints',          'priority' => '0.3', 'freq' => 'yearly'],

];

// ── GOOGLE ADS LANDING PAGES ──────────────────────────────────────────────────
$lp_slugs = [
    'fast-business-loans',
    'cash-flow-loans',
    'working-capital',
    'no-credit-check',
    'ato-debt',
    'payroll-finance',
    'unsecured-loans',
    'line-of-credit',
    'no-doc-loans',
    'bank-rejected',
];

foreach ($lp_slugs as $slug) {
    $pages[] = [
        'url'      => '/lp/' . $slug . '.html',
        'priority' => '0.8',
        'freq'     => 'monthly',
    ];
}

// ── BLOG POSTS ────────────────────────────────────────────────────────────────
// Auto-discovers posts from your blog cache file if it exists
// Falls back to known posts if not
$blog_posts = [];
$blog_cache = __DIR__ . '/assets/data/blog_cache.json';

if (file_exists($blog_cache)) {
    $cache = json_decode(file_get_contents($blog_cache), true);
    if (is_array($cache)) {
        foreach ($cache as $post) {
            $slug = $post['slug'] ?? ($post['url'] ?? '');
            if ($slug) {
                // Handle both full URLs and slugs
                $url = (strpos($slug, 'http') === 0)
                    ? $slug
                    : BASE . '/blog/' . ltrim($slug, '/');
                $blog_posts[] = [
                    'url'      => str_replace(BASE, '', $url),
                    'priority' => '0.6',
                    'freq'     => 'monthly',
                    'lastmod'  => $post['date'] ?? TODAY,
                    'absolute' => strpos($slug, 'http') === 0 ? $slug : null,
                ];
            }
        }
    }
}

// Known blog posts as fallback
if (empty($blog_posts)) {
    $known_posts = [
        'how-lenders-actually-assess-sme-risk',
        'best-non-bank-business-lenders-in-australia-comparison-framework',
        'why-banks-are-tightening-sme-lending-in-2026',
        'what-lenders-actually-look-at',
        '7-things-that-kill-business-loan-approvals',
        'why-profit-doesnt-matter-as-much-as-cashflow',
    ];
    foreach ($known_posts as $slug) {
        $blog_posts[] = [
            'url'      => '/blog/' . $slug . '/',
            'priority' => '0.6',
            'freq'     => 'monthly',
        ];
    }
}

// ── OUTPUT XML ────────────────────────────────────────────────────────────────
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";

// Main pages
foreach ($pages as $p) {
    $loc = BASE . $p['url'];
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
    echo "    <lastmod>" . TODAY . "</lastmod>\n";
    echo "    <changefreq>" . $p['freq'] . "</changefreq>\n";
    echo "    <priority>" . $p['priority'] . "</priority>\n";
    echo "  </url>\n";
}

// Blog posts
foreach ($blog_posts as $p) {
    $loc = isset($p['absolute']) && $p['absolute']
        ? $p['absolute']
        : BASE . $p['url'];
    echo "  <url>\n";
    echo "    <loc>" . htmlspecialchars($loc, ENT_XML1) . "</loc>\n";
    echo "    <lastmod>" . ($p['lastmod'] ?? TODAY) . "</lastmod>\n";
    echo "    <changefreq>" . $p['freq'] . "</changefreq>\n";
    echo "    <priority>" . $p['priority'] . "</priority>\n";
    echo "  </url>\n";
}

echo '</urlset>';

// Flush clean output — nothing before <?xml, nothing after </urlset>
ob_end_flush();