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

// Allow CLI only
if (php_sapi_name() !== 'cli') {
    die('This script can only be run from command line');
}

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

echo "Starting sitemap generation...\n";

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

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

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

// 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";

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

// Static pages
$staticPages = ['user/login.php', 'user/register.php', 'user/trade.php'];
foreach ($staticPages as $sp) {
    $xml .= "  <url>\n";
    $xml .= "    <loc>{$baseUrl}/{$sp}</loc>\n";
    $xml .= "    <changefreq>monthly</changefreq>\n";
    $xml .= "    <priority>0.7</priority>\n";
    $xml .= "  </url>\n";
}

$xml .= '</urlset>';

// Save
$filepath = ROOT_PATH . '/sitemap.xml';
if (file_put_contents($filepath, $xml)) {
    echo "Sitemap generated successfully!\n";
    echo "Path: {$filepath}\n";
    echo "Pages: " . (count($pages) + count($staticPages) + 1) . "\n";
} else {
    echo "ERROR: Failed to write sitemap\n";
    exit(1);
}

// Optionally ping search engines
$sitemapUrl = urlencode(SITE_URL . '/sitemap.xml');

// Ping Google
$ch = curl_init("https://www.google.com/ping?sitemap={$sitemapUrl}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Google ping: " . ($code == 200 ? "OK" : "Failed ({$code})") . "\n";

// Ping Bing
$ch = curl_init("https://www.bing.com/ping?sitemap={$sitemapUrl}");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Bing ping: " . ($code == 200 ? "OK" : "Failed ({$code})") . "\n";

echo "Done!\n";
