<?php
header('Content-Type: application/json');

$directory = __DIR__ . '/scripts/';

if (!is_dir($directory)) {
    echo json_encode(["error" => "Scripts directory not found."]);
    exit;
}

if (isset($_GET['script'])) {
    $script = basename($_GET['script']); // Prevent directory traversal
    $filepath = $directory . $script;
    
    if (is_file($filepath) && pathinfo($filepath, PATHINFO_EXTENSION) === 'lua') {
        echo json_encode(["content" => file_get_contents($filepath)]);
    } else {
        echo json_encode(["error" => "File not found."]);
    }
    exit;
}

$files = array_values(array_filter(scandir($directory), function ($file) use ($directory) {
    return is_file($directory . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'lua';
}));

echo json_encode(["files" => $files]);
?>
