#!/usr/bin/env php
<?php
/**
 * Generate Sitemap
 * Creates sitemap.xml for SEO
 */

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

$baseUrl = APP_URL;
$sitemapFile = __DIR__ . '/../sitemap.xml';
$pdo = getDB();

echo "Generating sitemap...\n";

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

// Add static pages
$staticPages = [
    '/',
    '/login.php',
    '/doctor/dashboard.php',
    '/doctor/repertory/index.php',
    '/doctor/materia-medica/index.php'
];

foreach ($staticPages as $page) {
    $url = $xml->addChild('url');
    $url->addChild('loc', $baseUrl . $page);
    $url->addChild('lastmod', date('Y-m-d'));
    $url->addChild('changefreq', 'daily');
    $url->addChild('priority', '0.8');
}

// Add remedy pages
$stmt = $pdo->query("SELECT id, name, updated_at FROM remedies");
$remedies = $stmt->fetchAll();

foreach ($remedies as $remedy) {
    $url = $xml->addChild('url');
    $url->addChild('loc', $baseUrl . '/doctor/materia-medica/view.php?id=' . $remedy['id']);
    $url->addChild('lastmod', date('Y-m-d', strtotime($remedy['updated_at'] ?? 'now')));
    $url->addChild('changefreq', 'monthly');
    $url->addChild('priority', '0.6');
}

// Add rubric pages
$stmt = $pdo->query("SELECT id, updated_at FROM rubrics WHERE level >= 4 LIMIT 1000");
$rubrics = $stmt->fetchAll();

foreach ($rubrics as $rubric) {
    $url = $xml->addChild('url');
    $url->addChild('loc', $baseUrl . '/doctor/repertory/rubric.php?id=' . $rubric['id']);
    $url->addChild('lastmod', date('Y-m-d', strtotime($rubric['updated_at'] ?? 'now')));
    $url->addChild('changefreq', 'monthly');
    $url->addChild('priority', '0.5');
}

// Save sitemap
$xml->asXML($sitemapFile);
echo "Sitemap generated: $sitemapFile\n";
echo "Total URLs: " . (count($staticPages) + count($remedies) + count($rubrics)) . "\n";