<?php
header("Content-Type: application/xml; charset=utf-8");

// 数据库连接配置
$host = "localhost";
$user = "db_user";
$pass = "db_password";
$dbname = "movies_db";

$conn = new mysqli($host, $user, $pass, $dbname);
if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}

// 网站域名（根据你的实际域名改）
$siteUrl = "https://www.movies-popular.com";

// 获取当前日期
$today = date("Y-m-d");

// XML 开头
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">

<!-- 首页 -->
<url>
    <loc><?php echo $siteUrl; ?>/</loc>
    <lastmod><?php echo $today; ?></lastmod>
    <changefreq>daily</changefreq>
    <priority>1.0</priority>
</url>

<?php
// 分类页
$result = $conn->query("SELECT slug, updated_at FROM categories");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $url = $siteUrl . "/" . htmlspecialchars($row['slug']);
        $lastmod = date("Y-m-d", strtotime($row['updated_at']));
        ?>
<url>
    <loc><?php echo $url; ?></loc>
    <lastmod><?php echo $lastmod; ?></lastmod>
    <changefreq>weekly</changefreq>
    <priority>0.9</priority>
</url>
<?php
    }
}

// 电影详情页
$result = $conn->query("SELECT slug, updated_at FROM movies ORDER BY updated_at DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $url = $siteUrl . "/movie/" . htmlspecialchars($row['slug']);
        $lastmod = date("Y-m-d", strtotime($row['updated_at']));
        ?>
<url>
    <loc><?php echo $url; ?></loc>
    <lastmod><?php echo $lastmod; ?></lastmod>
    <changefreq>monthly</changefreq>
    <priority>0.7</priority>
</url>
<?php
    }
}

$conn->close();
?>
</urlset>
