<?php
// install/index.php

$is_rss = (isset($_GET['rss']));

header('Content-Type: ' . ($is_rss ? 'application/rss+xml; charset=UTF-8' : 'text/html; charset=UTF-8'));

function safe_filename($name) {
    return preg_replace('/[\/\\\\:*?"<>|]/u', '_', $name);
}

function list_html_files($dir) {
    $files = [];

    foreach (scandir($dir) as $file) {
        if (preg_match('/\.html$/u', $file)) {
            $basename = pathinfo($file, PATHINFO_FILENAME);
            $fullpath = $dir . '/' . $file;
            $mtime = filemtime($fullpath);
            $files[] = [
                'name' => $basename,
                'encoded' => rawurlencode($basename),
                'mtime' => $mtime
            ];
        }
    }

    usort($files, function ($a, $b) {
        return $b['mtime'] - $a['mtime'];
    });

    return $files;
}

function show_list_page($title, $message) {
    $files = list_html_files(__DIR__);
    echo "<!DOCTYPE html><html><head><meta charset=\"UTF-8\">";
    echo "<title>{$title}</title>";
    echo "<meta name=\"robots\" content=\"index,follow\">";
    echo "<style>
        body { font-family: sans-serif; line-height: 1.6; padding: 1em; }
        ul { margin-top: 1em; }
    </style>";
    echo "</head><body>";
    echo "<h1>{$title}</h1>";
    echo "<p>{$message}</p>";
    echo "<ul>";
    foreach ($files as $file) {
        $safeName = htmlspecialchars($file['name'], ENT_QUOTES, 'UTF-8');
        echo "<li><a href=\"{$file['encoded']}.html\" target=\"_blank\">{$safeName}</a></li>";
    }
    echo "</ul>";
    echo "</body></html>";
    exit;
}

function show_rss_feed() {
    mb_internal_encoding("UTF-8"); // 念のため

    $files = list_html_files(__DIR__);
    $dir_name = basename(__DIR__);

    // サイトURLを自動で生成（末尾にスラッシュなし）
    $site_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}" . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');

    $channel_title = $dir_name . '禁断の地図';
    $channel_description = $dir_name . ' にある神７の一覧です';

    header('Content-Type: application/rss+xml; charset=UTF-8');

    echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
    echo "<rss version=\"2.0\">\n";
    echo "  <channel>\n";
    echo "    <title>{$channel_title}</title>\n";
    echo "    <link>{$site_url}/</link>\n";
    echo "    <description>{$channel_description}</description>\n";
    echo "    <lastBuildDate>" . date(DATE_RSS) . "</lastBuildDate>\n";

    foreach ($files as $file) {
        $filepath = __DIR__ . '/' . $file['name'] . '.html';
        $mtime = file_exists($filepath) ? date(DATE_RSS, filemtime($filepath)) : date(DATE_RSS);

        $item_url = "{$site_url}/{$file['encoded']}.html";
        $safeName = htmlspecialchars($file['name'], ENT_QUOTES, 'UTF-8');
        echo "    <item>\n";
        echo "      <title>{$safeName}</title>\n";
        echo "      <link>{$item_url}</link>\n";
        echo "      <guid>{$item_url}</guid>\n";
        echo "      <pubDate>{$mtime}</pubDate>\n";
        echo "    </item>\n";
    }

    echo "  </channel>\n";
    echo "</rss>\n";
    exit;
}

// メイン処理
if ($is_rss) {
    show_rss_feed();
} else {
    $uri = $_SERVER['REQUEST_URI'];
    $path = parse_url($uri, PHP_URL_PATH);
    $basename = basename($path);

    // クエリキーが1つだけなら、それをファイル名として扱う
    if (empty($basename) || $basename === 'index.php') {
        if (count($_GET) === 1) {
            $keys = array_keys($_GET);
            $basename = $keys[0];
        }
    }

    $decoded = rawurldecode($basename);
    $filepath = __DIR__ . '/' . $decoded;

    if (file_exists($filepath)) {
        // 拡張子に応じて Content-Type を設定
        $ext = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
        $mime_types = [
            'html' => 'text/html; charset=UTF-8',
            'css'  => 'text/css; charset=UTF-8',
            'js'   => 'application/javascript; charset=UTF-8',
            'png'  => 'image/png',
            'jpg'  => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif'  => 'image/gif',
            'ico'  => 'image/x-icon',
            'svg'  => 'image/svg+xml',
            'webp' => 'image/webp',
        ];

        if (isset($mime_types[$ext])) {
            header('Content-Type: ' . $mime_types[$ext]);
        } else {
            header('Content-Type: application/octet-stream');
        }

        readfile($filepath);
        exit;
    }

    // ファイルが存在しない場合は一覧ページを表示
// メイン処理
if ($is_rss) {
    show_rss_feed();
} else {
    show_list_page(
        'サイトマップ',
        '以下のページをご覧ください:',
        'https://neogamma.loader.jp/'  // ← ここにリダイレクト先を指定！
    );
}
}
