<?php
// Set the content type to application/json to ensure the response is correctly interpreted by the client-side JavaScript.
header('Content-Type: application/json');

// Assume the folder name is passed via the query string
$folderName = $_GET['folder_name'] ?? 'instruction'; // Default to 'instruction' if no folder is specified

// Sanitize the folder name to prevent directory traversal
$folderName = basename($folderName);

// Make sure the folder exists
$folderPath = "../$folderName"; // Adjust the path as necessary

if (!is_dir($folderPath)) {
    echo json_encode(['status' => 'error', 'message' => 'Folder not found']);
    exit;
}

// Scan for files and directories in the folder
$files = [];
$dir = opendir($folderPath);

while (($file = readdir($dir)) !== false) {
    // Ignore '.' and '..' directories
    if ($file == '.' || $file == '..') continue;

    $filePath = $folderPath . '/' . $file;
    $isDirectory = is_dir($filePath);

    // Get file size and type
    $fileSize = null;
    $fileType = 'Directory';

    if (!$isDirectory) {
        $fileSize = filesize($filePath);
        $fileExtension = pathinfo($filePath, PATHINFO_EXTENSION);
        if ($fileExtension) {
            $fileType = strtoupper($fileExtension) . ' File';
        } else {
            $fileType = 'File';
        }
    }

    $files[] = [
        'name' => $file,
        'path' => $folderName . '/' . $file,
        'isDirectory' => $isDirectory,
        'size' => $fileSize,
        'type' => $fileType
    ];
}

closedir($dir);

// Return the files as a JSON response
echo json_encode(['status' => 'success', 'files' => $files]);
?>