<?php
while(ob_get_level()){ob_end_clean();}
header('Content-Type:application/xml;charset=utf-8',true);

$config=require __DIR__.'/config/env.php';
try{
$pdo=new PDO('mysql:host='.$config['db_host'].';dbname='.$config['db_name'].';charset=utf8mb4',$config['db_user'],$config['db_pass'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
$pdo->exec('SET NAMES utf8mb4');
}catch(PDOException $e){http_response_code(500);die('DB Error');}

echo'<?xml version="1.0" encoding="UTF-8"?>'."\n";
echo'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
echo'<url><loc>https://perunews.com/</loc><lastmod>'.date('Y-m-d').'</lastmod><changefreq>hourly</changefreq><priority>1.0</priority></url>'."\n";

try{
$stmt=$pdo->query("SELECT DISTINCT t.slug FROM wp_terms t INNER JOIN wp_term_taxonomy tt ON t.term_id=tt.term_id WHERE tt.taxonomy='category' AND t.slug!='' ORDER BY t.slug");
if($stmt){while($row=$stmt->fetch(PDO::FETCH_ASSOC)){$s=trim($row['slug']);if(preg_match('/^[a-z0-9\-]+$/i',$s)){echo'<url><loc>https://perunews.com/'.$s.'/</loc><lastmod>'.date('Y-m-d').'</lastmod><changefreq>daily</changefreq><priority>0.8</priority></url>'."\n";}}}

$stmt=$pdo->query("SELECT p.ID,t.slug FROM wp_posts p INNER JOIN wp_term_relationships tr ON p.ID=tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id=tt.term_taxonomy_id INNER JOIN wp_terms t ON tt.term_id=t.term_id WHERE p.post_status='publish' AND p.post_type='post' AND tt.taxonomy='category' ORDER BY p.ID DESC LIMIT 1000");
if($stmt){while($row=$stmt->fetch(PDO::FETCH_ASSOC)){$s=!empty($row['slug'])?trim($row['slug']):'noticias';$id=(int)$row['ID'];if(preg_match('/^[a-z0-9\-]+$/i',$s)&&$id>0){echo'<url><loc>https://perunews.com/'.$s.'/post/'.$id.'</loc><lastmod>'.date('Y-m-d').'</lastmod><changefreq>weekly</changefreq><priority>0.6</priority></url>'."\n";}}}
}catch(PDOException $e){error_log('sitemap:'.$e->getMessage());}

echo'</urlset>';