<?php
header('Content-Type: application/xml; charset=UTF-8');

function wu_wpconfig_const($name, $configText) {
    if (preg_match("/define\\(\\s*'" . preg_quote($name, '/') . "'\\s*,\\s*'([^']*)'/", $configText, $m)) {
        return $m[1];
    }
    return null;
}

$configText   = file_get_contents(__DIR__ . '/wp-config.php');
$dbName       = wu_wpconfig_const('DB_NAME', $configText);
$dbUser       = wu_wpconfig_const('DB_USER', $configText);
$dbPass       = wu_wpconfig_const('DB_PASSWORD', $configText);
$dbHost       = wu_wpconfig_const('DB_HOST', $configText);
$tablePrefix  = 'wp_';
if (preg_match('/\$table_prefix\s*=\s*\'([^\']*)\'/', $configText, $m)) {
    $tablePrefix = $m[1];
}

$base = 'https://wakingup.com.ar';

$pages = [
    '/',
    '/quienes-somos/',
    '/pilares-fundamentales/',
    '/oferta-educativa/',
    '/oferta-educativa-kids/',
    '/oferta-educativa-juniors/',
    '/oferta-educativa-teens/',
    '/oferta-educativa-adults/',
    '/oferta-educativa-summer-camp-live-usa/',
    '/oferta-educativa-summer-workshop/',
    '/oferta-educativa-christmas-workshop/',
    '/oferta-educativa-capacitaciones-docentes/',
    '/franquicias/',
    '/servicios/',
    '/contacto/',
    '/novedades/',
];

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

foreach ($pages as $path) {
    echo '  <url><loc>' . htmlspecialchars($base . $path) . "</loc><changefreq>monthly</changefreq></url>\n";
}

try {
    $posts_t = $tablePrefix . 'posts';
    $tr_t    = $tablePrefix . 'term_relationships';
    $tt_t    = $tablePrefix . 'term_taxonomy';
    $terms_t = $tablePrefix . 'terms';

    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
    $stmt = $pdo->query("
        SELECT p.post_name, p.post_date, p.post_modified_gmt
        FROM {$posts_t} p
        INNER JOIN {$tr_t} tr ON tr.object_id = p.ID
        INNER JOIN {$tt_t} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
        INNER JOIN {$terms_t} t ON t.term_id = tt.term_id
        WHERE p.post_type = 'post' AND p.post_status = 'publish'
          AND tt.taxonomy = 'category' AND t.slug = 'novedades'
        ORDER BY p.post_date DESC
    ");
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
        $d = new DateTime($row['post_date']);
        $loc = $base . '/' . $d->format('Y/m/d') . '/' . $row['post_name'] . '/';
        $lastmod = (new DateTime($row['post_modified_gmt'], new DateTimeZone('UTC')))->format('c');
        echo '  <url><loc>' . htmlspecialchars($loc) . "</loc><lastmod>{$lastmod}</lastmod><changefreq>weekly</changefreq></url>\n";
    }
} catch (Throwable $e) {
    // DB unreachable — sitemap still serves the static marketing pages above
}

echo '</urlset>' . "\n";
