<?php
require_once __DIR__.'/_bootstrap.php';
use App\Core\Database;
$job='sitemap_generate';$started=date('Y-m-d H:i:s');try{$base=rtrim(APP_URL,'/');if($base==='')throw new RuntimeException('APP_URL must be configured to generate an absolute sitemap.');$urls=[['loc'=>$base.'/','lastmod'=>date('Y-m-d')],['loc'=>$base.'/public/products.php','lastmod'=>date('Y-m-d')]];$sets=[['SELECT slug,COALESCE(updated_at,created_at) changed FROM products WHERE status="published"','product/'],['SELECT slug,COALESCE(updated_at,created_at) changed FROM categories WHERE status="active"','public/products.php?category='],['SELECT slug,COALESCE(updated_at,created_at) changed FROM brands WHERE status="active"','brand/'],['SELECT slug,COALESCE(updated_at,created_at) changed FROM vendors WHERE status="approved"','shop/'],['SELECT slug,COALESCE(updated_at,created_at) changed FROM pages WHERE status="published"','page/']];foreach($sets as [$sql,$prefix])foreach(Database::safeFetchAll($sql) as $r)$urls[]=['loc'=>$base.'/'.$prefix.rawurlencode($r['slug']),'lastmod'=>substr((string)($r['changed']?:date('Y-m-d')),0,10)];$xml='<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.PHP_EOL;foreach($urls as $u)$xml.='  <url><loc>'.htmlspecialchars($u['loc'],ENT_XML1).'</loc><lastmod>'.htmlspecialchars($u['lastmod'],ENT_XML1).'</lastmod></url>'.PHP_EOL;$xml.='</urlset>'.PHP_EOL;if(file_put_contents(ROOT_PATH.'/sitemap.xml',$xml)===false)throw new RuntimeException('Could not write sitemap.xml.');cron_log($job,'success','Generated sitemap.xml with '.count($urls).' URL(s).',$started);}catch(Throwable $e){cron_log($job,'failed',$e->getMessage(),$started);exit(1);}
