<?php
ob_start();
error_reporting(0);
header("Content-Type: application/xml; charset=utf-8");

// ข้อมูลการเชื่อมต่อฐานข้อมูล
$host = "localhost:3306";
$username = "freeseuganriian_h514133";
$password = "koker582528wdP";
$dbname = "freeseuganriian_h514133";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    ob_clean();
    die('<?xml version="1.0" encoding="UTF-8"?><error>Database connection failed</error>');
}
$conn->set_charset("tis620"); // หรือ utf8 ตามฐานข้อมูลจริง

// ล้าง Output Buffer ก่อนเริ่มพ่น XML ออกไป
ob_clean();

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

// 1. หน้าแรกของเว็บไซต์
echo '<url>' . "\n";
echo '  <loc>https://www.สยามรุ่งเรืองกิจการ.com/</loc>' . "\n";
echo '  <changefreq>daily</changefreq>' . "\n";
echo '  <priority>1.0</priority>' . "\n";
echo '</url>' . "\n";

// 2. ดึงข้อมูลข่าวสารจากตาราง web_news
$sql_news = "SELECT id, update_date FROM web_news ORDER BY id DESC";
$result_news = $conn->query($sql_news);

if ($result_news && $result_news->num_rows > 0) {
    while($row = $result_news->fetch_assoc()) {
        $id = $row['id'];
        $date = !empty($row['update_date']) ? date('Y-m-d', (int)$row['update_date']) : date('Y-m-d');
        
        echo '<url>' . "\n";
        echo '  <loc>https://www.สยามรุ่งเรืองกิจการ.com/news_detail.php?id=' . $id . '</loc>' . "\n";
        echo '  <lastmod>' . $date . '</lastmod>' . "\n";
        echo '  <changefreq>weekly</changefreq>' . "\n";
        echo '  <priority>0.8</priority>' . "\n";
        echo '</url>' . "\n";
    }
}

// 3. ดึงข้อมูลบทความ/ความรู้จากตาราง web_knowledge
$sql_knowledge = "SELECT id, update_date FROM web_knowledge ORDER BY id DESC";
$result_knowledge = $conn->query($sql_knowledge);

if ($result_knowledge && $result_knowledge->num_rows > 0) {
    while($row = $result_knowledge->fetch_assoc()) {
        $id = $row['id'];
        $date = !empty($row['update_date']) ? date('Y-m-d', (int)$row['update_date']) : date('Y-m-d');
        
        echo '<url>' . "\n";
        echo '  <loc>https://www.สยามรุ่งเรืองกิจการ.com/knowledge_detail.php?id=' . $id . '</loc>' . "\n";
        echo '  <lastmod>' . $date . '</lastmod>' . "\n";
        echo '  <changefreq>monthly</changefreq>' . "\n";
        echo '  <priority>0.7</priority>' . "\n";
        echo '</url>' . "\n";
    }
}

echo '</urlset>';
$conn->close();
ob_end_flush();
?>