<?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');

// Get the folder name from the query string or default to 'instruction'
$folderName = $_POST['folder_name'] ?? 'instruction';

// Define the target directory using the provided folder name.
$target_dir = "../" . $folderName . "/";

// Check if a file was uploaded. The 'fileToUpload' key corresponds to the name of the file input field in the HTML form.
if (isset($_FILES["fileToUpload"]) && $_FILES["fileToUpload"]["error"] == 0) {
    $file_info = $_FILES["fileToUpload"];
    
    // Get the base name of the uploaded file to prevent directory traversal attacks.
    $file_name = basename($file_info["name"]);
    $target_file = $target_dir . $file_name;
    $uploadOk = 1;
    $message = "File uploaded successfully.";

    // Check if the target directory exists. If not, attempt to create it.
    if (!is_dir($target_dir)) {
        if (!mkdir($target_dir, 0777, true)) {
            echo json_encode(["status" => "error", "message" => "Failed to create target directory."]);
            exit;
        }
    }

    // Check if file already exists.
    if (file_exists($target_file)) {
        $message = "A file with the same name already exists.";
        $uploadOk = 0;
    }

    // The file size check has been removed as requested.

    // Attempt to move the uploaded file from the temporary location to the specified target directory.
    if ($uploadOk == 1) {
        if (move_uploaded_file($file_info["tmp_name"], $target_file)) {
            // Success: send a JSON response.
            echo json_encode(["status" => "success", "message" => $message]);
        } else {
            // Failure: send a JSON response with an error message.
            echo json_encode(["status" => "error", "message" => "Sorry, there was an error uploading your file."]);
        }
    } else {
        // Validation failed: send a JSON response with the specific error message.
        echo json_encode(["status" => "error", "message" => $message]);
    }
} else {
    // No file was uploaded or an error occurred during upload.
    echo json_encode(["status" => "error", "message" => "No file uploaded or an upload error occurred."]);
}
?>