$baseDir = __DIR__;

function listHtmlFiles($dir, $relative = '') {
$output = '';
foreach (scandir($dir) as $item) {
if ($item === '.' || $item === '..') continue;
$fullPath = $dir . '/' . $item;
$relPath = $relative ? $relative . '/' . $item : $item;

if (is_dir($fullPath)) {
$output .= listHtmlFiles($fullPath, $relPath);
} elseif (preg_match('/\\.html$/i', $item)) {
$safePath = urlencode($relPath);
$output .= "<li><a href='?file=$safePath'>✏️ Edit $relPath</a></li>";
}
}
return $output;
}

if (isset($_GET['file'])) {
$relFile = $_GET['file'];
$filePath = realpath($baseDir . '/' . $relFile);

// Security: prevent traversal
if (!$filePath || strpos($filePath, $baseDir) !== 0 || !is_file($filePath) || !preg_match('/\\.html$/i', $filePath)) {
exit('⛔ Invalid file.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['content'])) {
file_put_contents($filePath, $_POST['content']);
echo "<p style='color:green;'>✅ File saved: <strong>" . htmlspecialchars($relFile) . "</strong></p>";
}

$content = htmlspecialchars(file_get_contents($filePath));
echo "

Editing: " . htmlspecialchars($relFile) . "

";
echo "
";
echo "<textarea name='content' rows='30' cols='120'>" . $content . "</textarea>

";
echo "<button type='submit'>💾 Save</button> ";
echo "<a href='editor.php'>🔙 Back</a>";
echo "
";
exit;
}

// Show file list
echo "

📂 HTML File Editor

<ul>";
echo listHtmlFiles($baseDir);
echo "</ul>";