<?php
/**
 * Cron Job - Generate Sitemap
 * Run daily: 0 0 * * * php /path/to/cron/generate-sitemap.php
 */

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

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

// Get all SEO pages
$pages = dbFetchAll("SELECT * FROM seo_pages WHERE status = 'active'");

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

// Add homepage
$xml .= "  <url>\n";
$xml .= "    <loc>{$baseUrl}/</loc>\n";
$xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
$xml .= "    <changefreq>daily</changefreq>\n";
$xml .= "    <priority>1.0</priority>\n";
$xml .= "  </url>\n";

// Add SEO managed pages
foreach ($pages as $page) {
    $url = $baseUrl . '/' . ltrim($page['page_url'], '/');
    $lastmod = date('Y-m-d', strtotime($page['updated_at']));
    
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$url}</loc>\n";
    $xml .= "    <lastmod>{$lastmod}</lastmod>\n";
    $xml .= "    <changefreq>weekly</changefreq>\n";
    $xml .= "    <priority>0.8</priority>\n";
    $xml .= "  </url>\n";
}

// Add static pages
$staticPages = [
    ['url' => 'user/login.php', 'priority' => '0.7', 'changefreq' => 'monthly'],
    ['url' => 'user/register.php', 'priority' => '0.8', 'changefreq' => 'monthly'],
    ['url' => 'user/trade.php', 'priority' => '0.9', 'changefreq' => 'daily'],
    ['url' => 'user/deposit.php', 'priority' => '0.7', 'changefreq' => 'weekly'],
];

foreach ($staticPages as $sp) {
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$baseUrl}/{$sp['url']}</loc>\n";
    $xml .= "    <changefreq>{$sp['changefreq']}</changefreq>\n";
    $xml .= "    <priority>{$sp['priority']}</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= '</urlset>';

// Save sitemap
$sitemapPath = ROOT_PATH . '/sitemap.xml';
file_put_contents($sitemapPath, $xml);

echo "Sitemap generated successfully at " . date('Y-m-d H:i:s') . "\n";
echo "Total URLs: " . (count($pages) + count($staticPages) + 1) . "\n";
