<?php
// sitemap.php
require 'db.php';

// --- ป้องกัน Error แสดงผลแทรกใน XML ---
ini_set('display_errors', 0);
error_reporting(E_ALL);

header("Content-Type: application/xml; charset=utf-8");

$base_url = "https://" . $_SERVER['HTTP_HOST'] . "/";

// ฟังก์ชันสร้าง Slug
if (!function_exists('createSlug')) {
    function createSlug($str) {
        $str = trim($str);
        $str = mb_strtolower($str, 'UTF-8');
        $str = preg_replace('/[^A-Za-z0-9\-\p{Thai}]/u', '-', $str);
        $str = preg_replace('/-+/', '-', $str);
        $str = trim($str, '-');
        return $str;
    }
}

// ฟังก์ชันแปลงตัวอักษรพิเศษให้เป็น XML Safe (เช่น & -> &amp;)
function xmlEscape($str) {
    return htmlspecialchars($str, ENT_XML1, 'UTF-8');
}

echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

    <?php 
    $langs = ['th', 'en'];
    $static_pages = [
        '' => ['priority' => '1.0', 'freq' => 'daily'],
        'catalog' => ['priority' => '0.8', 'freq' => 'daily'],
        'articles' => ['priority' => '0.8', 'freq' => 'daily']
    ];

    foreach ($static_pages as $page => $meta) {
        foreach ($langs as $lang) {
            $url = $base_url . $lang . '/' . $page;
            ?>
    <url>
        <loc><?php echo xmlEscape($url); ?></loc>
        <priority><?php echo $meta['priority']; ?></priority>
        <changefreq><?php echo $meta['freq']; ?></changefreq>
    </url>
            <?php
        }
    }
    ?>

    <?php
    $sql_prod = "SELECT id, name_th, name_en FROM products ORDER BY id DESC";
    $result_prod = @$conn->query($sql_prod);

    if ($result_prod) {
        $today = date('Y-m-d'); // ใช้วันปัจจุบันไปเลย
        while ($row = $result_prod->fetch_assoc()) {
            foreach ($langs as $lang) {
                $name = ($lang === 'en' && !empty($row['name_en'])) ? $row['name_en'] : $row['name_th'];
                $slug = createSlug($name);
                $url = $base_url . $lang . "/product/" . $row['id'] . "/" . $slug; // $slug may need urlencode, handled by browser usually, but better to keep safe
                // Let's use urlencode on slug
                $url = $base_url . $lang . "/product/" . $row['id'] . "/" . urlencode($slug);
    ?>
    <url>
        <loc><?php echo xmlEscape($url); ?></loc>
        <lastmod><?php echo $today; ?></lastmod>
        <priority>0.9</priority>
        <changefreq>weekly</changefreq>
    </url>
    <?php 
            }
        }
    } 
    ?>

    <?php
    $sql_art = "SELECT id, title, title_en, created_at FROM articles WHERE status = 'published' ORDER BY id DESC";
    $result_art = @$conn->query($sql_art); // ใส่ @ ดัก Error ไว้ก่อน

    if ($result_art) {
        while ($row = $result_art->fetch_assoc()) {
            foreach ($langs as $lang) {
                $title = ($lang === 'en' && !empty($row['title_en'])) ? $row['title_en'] : $row['title'];
                $slug = createSlug($title);
                $url = $base_url . $lang . "/article/" . $row['id'] . "/" . urlencode($slug);
                $date = date('Y-m-d', strtotime($row['created_at']));
    ?>
    <url>
        <loc><?php echo xmlEscape($url); ?></loc>
        <lastmod><?php echo $date; ?></lastmod>
        <priority>0.7</priority>
        <changefreq>monthly</changefreq>
    </url>
    <?php 
            }
        }
    }
    ?>

</urlset>