<?php
// Set the content type to JSON so the browser knows how to interpret the response.
header('Content-Type: application/json');

$safe_delete_directory = '../'; // The directory where files are located

// Check if the request method is DELETE and the 'file_path' parameter is present.
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && isset($_GET['file_path'])) {
    
    // Sanitize the input to remove any leading or trailing whitespace.
    $relative_path = trim($_GET['file_path']);
    
    // Sanitize and get the full path by resolving symbolic links and relative paths.
    $full_path = realpath($safe_delete_directory . DIRECTORY_SEPARATOR . $relative_path);

    if ($full_path && strpos($full_path, realpath($safe_delete_directory)) === 0) {
        
        // Check if the file exists and is a regular file (not a directory).
        if (file_exists($full_path) && is_file($full_path)) {
            
            // Attempt to delete the file.
            if (unlink($full_path)) {
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Your file has been deleted.'
                ]);
            } else {
                // Return an error if the deletion failed, likely due to file permissions.
                echo json_encode([
                    'status' => 'error',
                    'message' => 'Unable to delete the file. Please check file permissions.'
                ]);
            }
        } else {
            // Return an error if the file was not found.
            echo json_encode([
                'status' => 'error',
                'message' => 'The file was not found.'
            ]);
        }
    } else {
        // Return an error if the path is invalid or attempts to access a different directory.
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid file path provided.'
        ]);
    }
} else {
    // Return an error if the request method or parameter is incorrect.
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request.'
    ]);
}
?>
