<?php
// 遍历demos文件夹下的所有文件夹，然后再遍历所有文件
$directory = new DirectoryIterator(dirname(__FILE__));
$folders = [];
$files = [];

foreach ($directory as $folderinfo) {
  if ($folderinfo->isDir() && !$folderinfo->isDot()) {
    $folders[] = $folderinfo->getFilename();
  }
}

foreach ($folders as $folder) {
  $subDirectory = new DirectoryIterator(dirname(__FILE__) . '/' . $folder);
  foreach ($subDirectory as $fileinfo) {
    if ($fileinfo->isFile() && $fileinfo->getExtension() == 'html') {
      $files[] = $folder . '/' . $fileinfo->getFilename();
    }
  }
}
sort($folders);
sort($files);
?>

  <div class="row">
    <div class="col-3">
      <div class="list-group">
        <?php foreach ($files as $file): ?>
          <a href="?file=<?php echo urlencode($file); ?>" class="list-group-item list-group-item-action">
            <?php echo htmlspecialchars($file); ?>
          </a>
        <?php endforeach; ?>
      </div>
    </div>
    <div class="col-9">
      <div class="content">
        <?php
        if (isset($_GET['file'])) {
          $file = $_GET['file'];
          // Validate file path to prevent directory traversal
          $realPath = realpath(dirname(__FILE__) . '/' . $file);
          $basePath = realpath(dirname(__FILE__));
          
          if ($realPath && strpos($realPath, $basePath) === 0 && file_exists($realPath) && is_readable($realPath)) {
            if (pathinfo($realPath, PATHINFO_EXTENSION) == 'php') {
              include $realPath;
            } else {
              echo file_get_contents($realPath);
            }
          } else {
            echo '<p>File not found or not readable.</p>';
          }
        } else {
          echo '<p>Select a file from the list.</p>';
        }
        ?>
      </div>
    </div>
  </div>