<?php
include('pages.php'); // 引入包含 $pagesArray 的檔案

// Pages Array 的 限制數量
$limit = 20;
$count = 0;

// 設定今天零時零分的時間
$today = date('Y-m-d') . 'T00:00:00+00:00';

// 獲取語言參數
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';

// 根據語言參數決定要使用哪個 API URL 和網址前綴
$base_url = '';
$api_data = null;
if ($lang === 'en') {
    $base_url = 'https://ir.swireproperties.com/en/';
    $api_url = 'https://sync.irasia.com/api/adaptation/swireproperties/en/byType/acr/latestYear';
    $json_data = file_get_contents($api_url);
    $api_data = json_decode($json_data, true);
} elseif ($lang === 'zh-hk') {
    $base_url = 'https://ir.swireproperties.com/zh-hk/';
    $api_url = 'https://sync.irasia.com/api/adaptation/swireproperties/tc/byType/acr/latestYear';
    $json_data = file_get_contents($api_url);
    $api_data = json_decode($json_data, true);
} elseif ($lang === 'zh-cn') {
    $base_url = 'https://ir.swireproperties.com/zh-cn/';
    $api_url = 'https://sync.irasia.com/api/adaptation/swireproperties/tc/byType/acr/latestYear';
    $json_data = file_get_contents($api_url);
    $api_data = json_decode($json_data, true);
}

// 輸出 XML 頭部
header('Content-Type: application/xml; charset=utf-8');
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9             http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . "\n";

// 修改 $pagesArray 的遍歷部分
foreach ($pagesArray as $page) {
    // 檢查 URL 是否符合所選語言版本
    if ($base_url && strpos($page['url'], $base_url) !== 0) {
        continue;
    }
    
    echo "<url>\n";
    echo "  <loc>" . htmlspecialchars($page['url']) . "</loc>\n";
    $urlPath = parse_url($page['url'], PHP_URL_PATH);
    $extension = strtolower(pathinfo($urlPath, PATHINFO_EXTENSION));
    
    if ($extension === 'php') {
        echo "  <lastmod>" . $today . "</lastmod>\n";
    } else {
        echo "  <lastmod>" . $page['lastmod'] . "</lastmod>\n";
    }
    
    echo "  <priority>" . $page['priority'] . "</priority>\n";
    echo "</url>\n";

    if($count >= $limit) {
        break;
    }
    $count++;
}

// 修改 API 結果的遍歷部分
if ($api_data) {
    foreach ($api_data['data']['results'] as $result) {
        $url = str_replace('\\/', '/', $result['url']);
        $lastmod = date('c', strtotime($result['updatetime']));
        
        echo "\n<url>";
        echo "\n\t<loc>" . htmlspecialchars($url) . "</loc>";
        //echo "\n\t<lastmod>" . $lastmod . "</lastmod>";
        echo "  <lastmod>" . $today . "</lastmod>\n";
        echo "\n\t<priority>0.80</priority>";
        echo "\n</url>";
    }
}

// 輸出 XML 尾部
echo "\n</urlset>";
