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

$json_file = 'movies.json';
$movies = file_exists($json_file) ? json_decode(file_get_contents($json_file), true) : [];

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$base_url = $protocol . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

// Fungsi slug (harus sama dengan halaman utama)
function generateSlug($title) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $title)));
}

echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- Halaman Utama -->
    <url>
        <loc><?php echo htmlspecialchars($base_url . '/index.php'); ?></loc>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>
    <url>
        <loc><?php echo htmlspecialchars($base_url . '/index.php?type=movie'); ?></loc>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>
    <url>
        <loc><?php echo htmlspecialchars($base_url . '/index.php?type=series'); ?></loc>
        <changefreq>daily</changefreq>
        <priority>0.8</priority>
    </url>

    <?php if (is_array($movies)): ?>
        <?php foreach ($movies as $m): ?>
            <?php 
                $slug = generateSlug($m['title'] ?? 'movie');
                $type = $m['type'] ?? 'movie';
                
                if ($type === 'series' && isset($m['seasons'][0])) {
                    $first_s = $m['seasons'][0]['season'] ?? '1';
                    $first_e = $m['seasons'][0]['episodes'][0] ?? '1';
                    $movie_url = $base_url . '/index.php?slug=' . $slug . '&s=' . $first_s . '&e=' . $first_e;
                } else {
                    $movie_url = $base_url . '/index.php?slug=' . $slug;
                }
            ?>
            <url>
                <loc><?php echo htmlspecialchars($movie_url); ?></loc>
                <changefreq>weekly</changefreq>
                <priority>0.7</priority>
            </url>
        <?php endforeach; ?>
    <?php endif; ?>
</urlset>