<?php
    error_reporting(0);
    session_start();
// Check if a folder removal button is clicked
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_folder'])) {

    $folderToRemove = $_POST['remove_folder'];
    removeFolder($folderToRemove);
    
    $filePath = './get-panel/info-panel.txt';
    $originalWord =  $folderToRemove . "," . "In WebSite";
    $replacementWord = "This Is folder is Removed !?". "," . "This ID is Removed !?";

    $fileContent = file_get_contents($filePath);

    // Replace the word using str_replace
    $modifiedContent = str_replace($originalWord, $replacementWord, $fileContent);

    // Write back to the file
    file_put_contents($filePath, $modifiedContent);

    echo "<script>
        window.location = './main_panel.php';
    </script>";
}

function removeFolder($folder) {
    $basePath = "../"; 

    // Construct the full path to the folder using DIRECTORY_SEPARATOR
    $folderPath = $basePath . DIRECTORY_SEPARATOR . $folder;

    // Use proper validation and sanitization here
    if (isValidFolderPath($folderPath)) {
        // Use recursive function to remove folder and its contents
        deleteFolder($folderPath);

        $_SESSION["message_panel"] = "Folder $folder removed successfully.";
    } else {
        $_SESSION["message_panel"] = "Invalid folder path, Or Already removed.";
    }
}

function isValidFolderPath($path) {
    // Implement proper validation logic here
    return true;
}

function deleteFolder($path) {
    // Recursive function to delete folder and its contents
    $files = is_dir($path) ? array_diff(scandir($path), ['.', '..']) : [];
    foreach ($files as $file) {
        $filePath = $path . DIRECTORY_SEPARATOR . $file;
        (is_dir($filePath)) ? deleteFolder($filePath) : unlink($filePath);
    }
    return rmdir($path);
}
?>
