Vis: Edit_Index.php

Tilbage

<?php
/**
 * =====================================================================
 * KONTROLLPANEL - ENDRINGSHISTORIKK (CHANGELOG)
 * =====================================================================
 * ver. 1.0.0 (2026-10-25): Første stabile utgave med grunnleggende filbehandling,
 *                          oppretting, opplasting, redigering og sletting.
 * ver. 1.1.0 (2026-10-25): Lagt til rekursiv søkefunksjon i gjeldende mappe.
 * ver. 1.1.1 (2026-10-25): Inkludert "Valg"-menyen direkte i søkeresultatene.
 * ver. 1.1.2 (2026-10-25): Flyttet søkefeltet opp i verktøylinjen for bedre plass.
 * ver. 1.2.0 (2026-10-25): Lagt til "Kopier" og "Sett tillatelser" (Chmod).
 * ver. 1.2.1 (2026-10-25): Feilretting av syntaks i redigeringsvisning.
 * ver. 1.2.2 (2026-10-25): Lagt til konfigurasjon for valg av systemrot / skriptets mappe.
 * ver. 1.3.0 (2026-10-25): Utvidet innlogging med brukernavn ("TT" default) og passord.
 * ver. 1.3.1 (2026-10-25): Automatisk oppover-visning for nedtrekksmenyer nederst på skjermen.
 * ver. 1.4.0 (2026-10-25): Lagt til endringshistorikk, konfigurerbar linjehøyde, 
 *                          farge på ikoner og full flerspråklig støtte (NO, EN, DE, SV).
 * =====================================================================
 */

// Slå på feilsøking midlertidig for å se eventuelle feilmeldinger
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ver = "ver. 1.4.0 2026-10-25 HBj ";

session_start();

// ==========================================
// KONSEPTUELLE INNSTILLINGER (KONFIGURASJON)
// ==========================================
$config = [
    'language'        => 'no',     // Språk: 'no' (Norsk), 'en' (Engelsk), 'de' (Tysk), 'sv' (Svensk)
    'line_height'     => '8px',   // Linjehøyde / polstring i tabellrader (f.eks. '10px' kompakt, '16px' luftig)
    'folder_color'    => '#f39c12',// Farge på mappe-ikoner
    'file_color'      => '#7f8c8d',// Farge på fil-ikoner
    'use_login'       => true,     // Bruk innlogging med brukernavn og passord (false deaktiverer)
    'username'        => 'TT',     // Standard brukernavn
    'password'        => '123456', // Passord
    'system_root'     => false,    // Start fra systemrot (true) eller skriptets mappe (false)
    'mkfile'          => true,     // Ny fil
    'mkdir'           => true,     // Ny mappe
    'upload'          => true,     // Last opp fil(er) / mapper
    'download_file'   => true,     // Last ned fil
    'download_folder' => true,     // Last ned mappe
    'view'            => true,     // Vis
    'edit'            => true,     // Rediger
    'rename'          => true,     // Nytt navn
    'copy'            => true,     // Kopier
    'move'            => true,     // Flytt
    'chmod'           => true,     // Sett tillatelser
    'delete'          => true      // Slett
];

// ==========================================
// SPRÅKTABELLER (OVERSETTELSER)
// ==========================================
$lang = [
    'no' => [
        'title' => 'Kontrollpanel',
        'subtitle' => 'Utviklet av H. Bjerkan ved hjelp av Gemini',
        'login_header' => 'Kontrollpanel',
        'username' => 'Brukernavn',
        'password' => 'Passord',
        'login_btn' => 'Logg inn',
        'login_error' => 'Feil brukernavn eller passord!',
        'logout' => 'Logg ut',
        'logged_in_as' => 'Innlogget som:',
        'guest' => 'Gjest',
        'home_root' => 'Hjem / Rotmappe',
        'path_label' => 'Sti:',
        'new_file_placeholder' => 'Nytt filnavn...',
        'new_file_btn' => '+ Ny fil',
        'new_folder_placeholder' => 'Nytt mappenavn...',
        'new_folder_btn' => '+ Ny mappe',
        'upload_files_btn' => 'Last opp fil(er)',
        'upload_folder_btn' => 'Last opp mappe',
        'search_placeholder' => 'Søk i mappe...',
        'search_btn' => 'Søk',
        'reset_btn' => 'Nullstill',
        'search_results' => 'Søkeresultater for',
        'found_count' => 'funnet',
        'no_results' => 'Ingen filer eller mapper funnet.',
        'th_name' => 'Navn',
        'th_folder' => 'Mappe',
        'th_type' => 'Type',
        'th_size' => 'Størrelse',
        'th_actions' => 'Handlinger',
        'parent_dir' => '.. (Opp et nivå)',
        'type_dir' => 'Mappe',
        'type_file' => 'Fil',
        'action_choices' => 'Valg ▾',
        'action_view' => 'Vis',
        'action_edit' => 'Rediger',
        'action_download' => 'Last ned',
        'action_download_zip' => 'Last ned (ZIP)',
        'action_copy' => 'Kopier',
        'action_move' => 'Flytt',
        'action_rename' => 'Endre navn',
        'action_chmod' => 'Tillatelser',
        'action_delete' => 'Slett',
        'prompt_move' => "Skriv inn destinasjonsmappe (f.eks. 'mappe1' eller la stå tomt for rotmappen):",
        'prompt_rename' => "Nytt navn:",
        'prompt_chmod' => "Sett tillatelser (f.eks. 0644 for filer eller 0755 for mapper):",
        'confirm_delete' => "Vil du slette",
        'back_to_files' => 'Tilbake',
        'save_changes' => 'Lagre endringer',
        'save_success' => 'Endringene ble lagret vellykket!'
    ],
    'en' => [
        'title' => 'Control Panel',
        'subtitle' => 'Developed by H. Bjerkan using Gemini',
        'login_header' => 'Control Panel',
        'username' => 'Username',
        'password' => 'Password',
        'login_btn' => 'Log in',
        'login_error' => 'Invalid username or password!',
        'logout' => 'Log out',
        'logged_in_as' => 'Logged in as:',
        'guest' => 'Guest',
        'home_root' => 'Home / Root folder',
        'path_label' => 'Path:',
        'new_file_placeholder' => 'New filename...',
        'new_file_btn' => '+ New file',
        'new_folder_placeholder' => 'New folder name...',
        'new_folder_btn' => '+ New folder',
        'upload_files_btn' => 'Upload file(s)',
        'upload_folder_btn' => 'Upload folder',
        'search_placeholder' => 'Search in folder...',
        'search_btn' => 'Search',
        'reset_btn' => 'Reset',
        'search_results' => 'Search results for',
        'found_count' => 'found',
        'no_results' => 'No files or folders found.',
        'th_name' => 'Name',
        'th_folder' => 'Folder',
        'th_type' => 'Type',
        'th_size' => 'Size',
        'th_actions' => 'Actions',
        'parent_dir' => '.. (Up one level)',
        'type_dir' => 'Folder',
        'type_file' => 'File',
        'action_choices' => 'Actions ▾',
        'action_view' => 'View',
        'action_edit' => 'Edit',
        'action_download' => 'Download',
        'action_download_zip' => 'Download (ZIP)',
        'action_copy' => 'Copy',
        'action_move' => 'Move',
        'action_rename' => 'Rename',
        'action_chmod' => 'Permissions',
        'action_delete' => 'Delete',
        'prompt_move' => "Enter destination folder (e.g. 'folder1' or leave blank for root):",
        'prompt_rename' => "New name:",
        'prompt_chmod' => "Set permissions (e.g. 0644 for files or 0755 for folders):",
        'confirm_delete' => "Do you want to delete",
        'back_to_files' => 'Back',
        'save_changes' => 'Save changes',
        'save_success' => 'Changes saved successfully!'
    ],
    'de' => [
        'title' => 'Steuerpult',
        'subtitle' => 'Entwickelt von H. Bjerkan mit Hilfe von Gemini',
        'login_header' => 'Steuerpult',
        'username' => 'Benutzername',
        'password' => 'Passwort',
        'login_btn' => 'Anmelden',
        'login_error' => 'Ungültiger Benutzername oder Passwort!',
        'logout' => 'Abmelden',
        'logged_in_as' => 'Angemeldet als:',
        'guest' => 'Gast',
        'home_root' => 'Start / Stammverzeichnis',
        'path_label' => 'Pfad:',
        'new_file_placeholder' => 'Neuer Dateiname...',
        'new_file_btn' => '+ Neue Datei',
        'new_folder_placeholder' => 'Neuer Ordnername...',
        'new_folder_btn' => '+ Neuer Ordner',
        'upload_files_btn' => 'Datei(en) hochladen',
        'upload_folder_btn' => 'Ordner hochladen',
        'search_placeholder' => 'Im Ordner suchen...',
        'search_btn' => 'Suchen',
        'reset_btn' => 'Zurücksetzen',
        'search_results' => 'Suchergebnisse für',
        'found_count' => 'gefunden',
        'no_results' => 'Keine Dateien oder Ordner gefunden.',
        'th_name' => 'Name',
        'th_folder' => 'Ordner',
        'th_type' => 'Typ',
        'th_size' => 'Größe',
        'th_actions' => 'Aktionen',
        'parent_dir' => '.. (Eine Ebene höher)',
        'type_dir' => 'Ordner',
        'type_file' => 'Datei',
        'action_choices' => 'Aktionen ▾',
        'action_view' => 'Ansehen',
        'action_edit' => 'Bearbeiten',
        'action_download' => 'Herunterladen',
        'action_download_zip' => 'Herunterladen (ZIP)',
        'action_copy' => 'Kopieren',
        'action_move' => 'Verschieben',
        'action_rename' => 'Umbenennen',
        'action_chmod' => 'Berechtigungen',
        'action_delete' => 'Löschen',
        'prompt_move' => "Zielordner eingeben (z.B. 'ordner1' oder leer lassen für Stammverzeichnis):",
        'prompt_rename' => "Neuer Name:",
        'prompt_chmod' => "Berechtigungen festlegen (z.B. 0644 für Dateien oder 0755 für Ordner):",
        'confirm_delete' => "Möchten Sie löschen",
        'back_to_files' => 'Zurück',
        'save_changes' => 'Änderungen speichern',
        'save_success' => 'Änderungen erfolgreich gespeichert!'
    ],
    'sv' => [
        'title' => 'Kontrollpanel',
        'subtitle' => 'Utvecklad av H. Bjerkan med hjälp av Gemini',
        'login_header' => 'Kontrollpanel',
        'username' => 'Användarnamn',
        'password' => 'Lösenord',
        'login_btn' => 'Logga in',
        'login_error' => 'Felaktigt användarnamn eller lösenord!',
        'logout' => 'Logga ut',
        'logged_in_as' => 'Inloggad som:',
        'guest' => 'Gäst',
        'home_root' => 'Hem / Rotmapp',
        'path_label' => 'Sökväg:',
        'new_file_placeholder' => 'Nytt filnamn...',
        'new_file_btn' => '+ Ny fil',
        'new_folder_placeholder' => 'Nytt mappnamn...',
        'new_folder_btn' => '+ Ny mapp',
        'upload_files_btn' => 'Ladda upp fil(er)',
        'upload_folder_btn' => 'Ladda upp mapp',
        'search_placeholder' => 'Sök i mapp...',
        'search_btn' => 'Sök',
        'reset_btn' => 'Återställ',
        'search_results' => 'Sökresultat för',
        'found_count' => 'hittade',
        'no_results' => 'Inga filer eller mappar hittades.',
        'th_name' => 'Namn',
        'th_folder' => 'Mapp',
        'th_type' => 'Typ',
        'th_size' => 'Storlek',
        'th_actions' => 'Åtgärder',
        'parent_dir' => '.. (Upp en nivå)',
        'type_dir' => 'Mapp',
        'type_file' => 'Fil',
        'action_choices' => 'Åtgärder ▾',
        'action_view' => 'Visa',
        'action_edit' => 'Redigera',
        'action_download' => 'Ladda ner',
        'action_download_zip' => 'Ladda ner (ZIP)',
        'action_copy' => 'Kopiera',
        'action_move' => 'Flytta',
        'action_rename' => 'Byt namn',
        'action_chmod' => 'Behörigheter',
        'action_delete' => 'Ta bort',
        'prompt_move' => "Ange destinationsmapp (t.ex. 'mapp1' eller lämna tomt för rotmappen):",
        'prompt_rename' => "Nytt namn:",
        'prompt_chmod' => "Ange behörigheter (t.ex. 0644 för filer eller 0755 för mappar):",
        'confirm_delete' => "Vill du radera",
        'back_to_files' => 'Tillbaka',
        'save_changes' => 'Spara ändringar',
        'save_success' => 'Ändringarna sparades utan problem!'
    ]
];

// Velg aktivt språk (fallback til 'no' hvis koden ikke finnes)
$current_lang = isset($lang[$config['language']]) ? $config['language'] : 'no';
$t = $lang[$current_lang];

$conf_user = $config['username'];
$conf_pass = $config['password'];

// Innloggingshåndtering (respekterer konfigurasjon)
if ($config['use_login']) {
    if (isset($_POST['action']) && $_POST['action'] === 'login') {
        $input_user = isset($_POST['username']) ? trim($_POST['username']) : '';
        $input_pass = isset($_POST['password']) ? $_POST['password'] : '';

        if ($input_user === $conf_user && $input_pass === $conf_pass) {
            $_SESSION['loggedin'] = true;
            $_SESSION['username'] = $input_user;
            header("Location: " . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $login_error = $t['login_error'];
        }
    }

    if (isset($_GET['action']) && $_GET['action'] === 'logout') {
        session_destroy();
        header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
        exit;
    }

    if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
        ?>
        <!DOCTYPE html>
        <html lang="<?php echo $current_lang; ?>">
        <head>
            <meta charset="UTF-8">
            <title><?php echo htmlspecialchars($t['login_header']); ?></title>
            <style>
                body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f8f9fa; margin: 0; }
                .login-box { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 320px; text-align: left; position: relative; }
                .login-version { font-size: 10px; color: #95a5a6; font-weight: normal; margin-bottom: 8px; }
                .login-box h2 { margin-top: 0; margin-bottom: 5px; text-align: center; }
                .login-subtitle { font-size: 12px; color: #666; margin-bottom: 20px; text-align: center; }
                input[type="text"], input[type="password"] { width: 100%; padding: 10px; margin: 8px 0; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
                button { width: 100%; background: #3498db; color: white; border: none; padding: 10px; border-radius: 4px; cursor: pointer; font-size: 14px; margin-top: 10px; }
                button:hover { opacity: 0.9; }
                .error { color: #e74c3c; font-size: 13px; margin-bottom: 10px; text-align: center; }
            </style>
        </head>
        <body>
            <div class="login-box">
                <div class="login-version"><?php echo htmlspecialchars($ver); ?></div>
                <h2><?php echo htmlspecialchars($t['login_header']); ?></h2>
                <div class="login-subtitle"><?php echo htmlspecialchars($t['subtitle']); ?></div>
                <?php if (isset($login_error)): ?>
                    <div class="error"><?php echo $login_error; ?></div>
                <?php endif; ?>
                <form method="POST">
                    <input type="hidden" name="action" value="login">
                    <label style="font-size: 12px; color: #555; font-weight: bold;"><?php echo htmlspecialchars($t['username']); ?></label>
                    <input type="text" name="username" value="<?php echo htmlspecialchars($conf_user); ?>" required autofocus>
                    <label style="font-size: 12px; color: #555; font-weight: bold;"><?php echo htmlspecialchars($t['password']); ?></label>
                    <input type="password" name="password" placeholder="<?php echo htmlspecialchars($t['password']); ?>" required>
                    <button type="submit"><?php echo htmlspecialchars($t['login_btn']); ?></button>
                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Sett startpunktet (base_dir) basert på konfigurasjon
if ($config['system_root']) {
    $base_dir = (DIRECTORY_SEPARATOR === '\\') ? substr(__DIR__, 0, 3) : '/';
} else {
    $base_dir = realpath(__DIR__);
}

$current_path = isset($_GET['path']) ? $_GET['path'] : '';
$target_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $current_path);

if ($target_dir === false || strpos($target_dir, $base_dir) !== 0) {
    $target_dir = $base_dir;
    $current_path = '';
}

// Håndter søkesti hvis det utføres handlinger fra søkeresultatet
$action_path = isset($_POST['action_path']) ? $_POST['path'] : $current_path;
$search_query = isset($_GET['q']) ? trim($_GET['q']) : '';

// --- HANDLINGER ---

// 3. Opprett ny mappe
if ($config['mkdir'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'mkdir') {
    $new_folder = trim($_POST['folder_name']);
    if (!empty($new_folder)) {
        $path_to_create = $target_dir . '/' . $new_folder;
        if (!file_exists($path_to_create)) {
            mkdir($path_to_create, 0777, true);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 4. Opprett ny fil
if ($config['mkfile'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'mkfile') {
    $new_file = trim($_POST['file_name']);
    if (!empty($new_file)) {
        $path_to_create = $target_dir . '/' . $new_file;
        if (!file_exists($path_to_create) && $path_to_create !== __FILE__) {
            file_put_contents($path_to_create, '');
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 5. Last opp filer / mapper
if ($config['upload'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['files'])) {
    $file_count = count($_FILES['files']['name']);
    $relative_paths = isset($_POST['relative_paths']) ? $_POST['relative_paths'] : [];

    for ($i = 0; $i < $file_count; $i++) {
        if ($_FILES['files']['error'][$i] === UPLOAD_ERR_OK) {
            $tmp_name = $_FILES['files']['tmp_name'][$i];
            $rel_path = !empty($relative_paths[$i]) ? $relative_paths[$i] : $_FILES['files']['name'][$i];
            $dest_path = $target_dir . '/' . $rel_path;
            
            $dest_dir = dirname($dest_path);
            if (!is_dir($dest_dir)) {
                mkdir($dest_dir, 0777, true);
            }
            
            move_uploaded_file($tmp_name, $dest_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 11. Kopier fil eller mappe
if ($config['copy'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'copy') {
    $item_name = basename($_POST['item_name']);
    $action_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
    
    if ($action_dir && strpos($action_dir, $base_dir) === 0) {
        $old_path = $action_dir . '/' . $item_name;
        if (file_exists($old_path) && $old_path !== __FILE__) {
            $copy_name = 'Kopi_av_' . $item_name;
            $dest_path = $action_dir . '/' . $copy_name;
            $counter = 1;
            while (file_exists($dest_path)) {
                $copy_name = 'Kopi_' . $counter . '_av_' . $item_name;
                $dest_path = $action_dir . '/' . $copy_name;
                $counter++;
            }
            
            function recursiveCopy($source, $dest) {
                if (is_dir($source)) {
                    @mkdir($dest, 0777, true);
                    $iterator = dir($source);
                    while (false !== ($entry = $iterator->read())) {
                        if ($entry == '.' || $entry == '..') continue;
                        recursiveCopy("$source/$entry", "$dest/$entry");
                    }
                    $iterator->close();
                } else {
                    @copy($source, $dest);
                }
            }
            
            recursiveCopy($old_path, $dest_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 12. Flytt fil eller mappe
if ($config['move'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'move') {
    $item_name = basename($_POST['item_name']);
    $destination_subpath = trim($_POST['destination'], '/');
    $action_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
    
    $old_path = $action_dir . '/' . $item_name;
    $dest_base = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $destination_subpath);

    if (file_exists($old_path) && $dest_base !== false && strpos($dest_base, $base_dir) === 0) {
        $new_path = $dest_base . '/' . $item_name;
        if ($old_path !== __FILE__ && strpos($dest_base, $old_path) !== 0) {
            rename($old_path, $new_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 13. Sett tillatelser (Chmod)
if ($config['chmod'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'chmod') {
    $item_name = basename($_POST['item_name']);
    $action_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
    $new_perms = trim($_POST['permissions']);
    
    if ($action_dir && strpos($action_dir, $base_dir) === 0 && preg_match('/^[0-7]{3,4}$/', $new_perms)) {
        $target_path = $action_dir . '/' . $item_name;
        if (file_exists($target_path) && $target_path !== __FILE__) {
            @chmod($target_path, octdec($new_perms));
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 6 & 7. Last ned fil eller mappe (ZIP) fra søk eller standard
if (isset($_GET['download'])) {
    $dl_path = isset($_GET['dl_path']) ? $_GET['dl_path'] : $current_path;
    $dl_target_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $dl_path);
    
    if ($dl_target_dir && strpos($dl_target_dir, $base_dir) === 0) {
        $item_to_download = realpath($dl_target_dir . '/' . $_GET['download']);
        if ($item_to_download && strpos($item_to_download, $base_dir) === 0) {
            
            if (is_file($item_to_download) && $config['download_file']) {
                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . basename($item_to_download) . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($item_to_download));
                readfile($item_to_download);
                exit;
            }
            
            elseif (is_dir($item_to_download) && $config['download_folder'] && class_exists('ZipArchive')) {
                $folder_name = basename($item_to_download);
                $zip_filename = sys_get_temp_dir() . '/' . $folder_name . '_' . time() . '.zip';
                
                $zip = new ZipArchive();
                if ($zip->open($zip_filename, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                    $files = new RecursiveIteratorIterator(
                        new RecursiveDirectoryIterator($item_to_download, RecursiveDirectoryIterator::SKIP_DOTS),
                        RecursiveIteratorIterator::LEAVES_ONLY
                    );
                    
                    foreach ($files as $name => $file) {
                        if (!$file->isDir()) {
                            $filePath = $file->getRealPath();
                            $relativePath = substr($filePath, strlen($item_to_download) + 1);
                            $zip->addFile($filePath, $relativePath);
                        }
                    }
                    $zip->close();
                    
                    if (file_exists($zip_filename)) {
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/zip');
                        header('Content-Disposition: attachment; filename="' . $folder_name . '.zip"');
                        header('Expires: 0');
                        header('Cache-Control: must-revalidate');
                        header('Pragma: public');
                        header('Content-Length: ' . filesize($zip_filename));
                        readfile($zip_filename);
                        @unlink($zip_filename);
                        exit;
                    }
                }
            }
        }
    }
}

// 8. Vis / Åpne fil i nettleser
if ($config['view'] && isset($_GET['view'])) {
    $v_path = isset($_GET['v_path']) ? $_GET['v_path'] : $current_path;
    $v_target_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $v_path);
    
    if ($v_target_dir && strpos($v_target_dir, $base_dir) === 0) {
        $item_to_view = realpath($v_target_dir . '/' . $_GET['view']);
        if ($item_to_view && strpos($item_to_view, $base_dir) === 0 && is_file($item_to_view)) {
            $ext = strtolower(pathinfo($item_to_view, PATHINFO_EXTENSION));
            $mime_types = [
                'txt'  => 'text/plain; charset=utf-8',
                'htm'  => 'text/html; charset=utf-8',
                'html' => 'text/html; charset=utf-8',
                'php'  => 'text/plain; charset=utf-8',
                'css'  => 'text/css; charset=utf-8',
                'js'   => 'application/javascript; charset=utf-8',
                'json' => 'application/json; charset=utf-8',
                'jpg'  => 'image/jpeg',
                'jpeg' => 'image/jpeg',
                'png'  => 'image/png',
                'gif'  => 'image/gif',
                'svg'  => 'image/svg+xml',
                'pdf'  => 'application/pdf'
            ];
            
            $mime_type = $mime_types[$ext] ?? (function_exists('mime_content_type') ? mime_content_type($item_to_view) : false) ?: 'application/octet-stream';
            
            header('Content-Type: ' . $mime_type);
            header('Content-Disposition: inline; filename="' . basename($item_to_view) . '"');
            header('Content-Length: ' . filesize($item_to_view));
            readfile($item_to_view);
            exit;
        }
    }
}

// 9. Rediger fil
if ($config['edit'] && isset($_GET['edit'])) {
    $e_path = isset($_GET['e_path']) ? $_GET['e_path'] : $current_path;
    $e_target_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $e_path);
    
    if ($e_target_dir && strpos($e_target_dir, $base_dir) === 0) {
        $item_to_edit = realpath($e_target_dir . '/' . $_GET['edit']);
        if ($item_to_edit && strpos($item_to_edit, $base_dir) === 0 && is_file($item_to_edit)) {
            
            if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_file') {
                $new_content = $_POST['file_content'];
                file_put_contents($item_to_edit, $new_content);
                header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : '') . "&edit=" . urlencode($_GET['edit']) . "&e_path=" . urlencode($e_path) . "&saved=1");
                exit;
            }
            
            $file_content = file_get_contents($item_to_edit);
            $is_saved = isset($_GET['saved']);
            ?>
            <!DOCTYPE html>
            <html lang="<?php echo $current_lang; ?>">
            <head>
                <meta charset="UTF-8">
                <title>Redigerer: <?php echo htmlspecialchars(basename($item_to_edit)); ?></title>
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; background: #f8f9fa; color: #333; display: flex; flex-direction: column; height: 100vh; }
                    .editor-header { background: #2c3e50; color: white; padding: 15px 25px; display: flex; justify-content: space-between; align-items: center; }
                    .editor-main { flex: 1; display: flex; flex-direction: column; padding: 20px; gap: 15px; }
                    textarea { flex: 1; font-family: Consolas, Monaco, monospace; font-size: 14px; padding: 15px; border: 1px solid #dee2e6; border-radius: 6px; resize: none; background: #fff; line-height: 1.5; }
                    .btn { background: #3498db; color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 500; text-decoration: none; display: inline-block; }
                    .btn-success { background: #27ae60; }
                    .btn:hover { opacity: 0.9; }
                    .alert-saved { background: #d4edda; color: #155724; padding: 10px 15px; border-radius: 4px; border: 1px solid #c3e6cb; }
                </style>
            </head>
            <body>
                <div class="editor-header">
                    <div><strong><?php echo htmlspecialchars($t['th_type']); ?>:</strong> /<?php echo htmlspecialchars(ltrim(str_replace($base_dir, '', $item_to_edit), '/')); ?></div>
                    <div>
                        <a href="?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>" class="btn" style="background: #7f8c8d;"><?php echo htmlspecialchars($t['back_to_files']); ?></a>
                    </div>
                </div>
                <div class="editor-main">
                    <?php if ($is_saved): ?>
                        <div class="alert-saved"><?php echo htmlspecialchars($t['save_success']); ?></div>
                    <?php endif; ?>
                    <form method="POST" style="flex: 1; display: flex; flex-direction: column; gap: 15px; margin: 0;">
                        <input type="hidden" name="action" value="save_file">
                        <textarea name="file_content"><?php echo htmlspecialchars($file_content); ?></textarea>
                        <div>
                            <button type="submit" class="btn btn-success"><?php echo htmlspecialchars($t['save_changes']); ?></button>
                        </div>
                    </form>
                </div>
            </body>
            </html>
            <?php
            exit;
        }
    }
}

// 10. Endre navn på fil eller mappe
if ($config['rename'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'rename') {
    $old_name = basename($_POST['old_name']);
    $new_name = basename($_POST['new_name']);
    $action_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
    
    if (!empty($new_name) && $action_dir && strpos($action_dir, $base_dir) === 0) {
        $old_path = $action_dir . '/' . $old_name;
        $new_path = $action_dir . '/' . $new_name;
        
        if (file_exists($old_path) && $old_path !== __FILE__ && !file_exists($new_path)) {
            rename($old_path, $new_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// 14. Slett fil eller mappe
if ($config['delete'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $item_to_delete = basename($_POST['item_name']);
    $action_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
    
    if ($action_dir && strpos($action_dir, $base_dir) === 0) {
        $target_path = $action_dir . '/' . $item_to_delete;
        
        if (file_exists($target_path) && realpath($target_path) !== __FILE__ && strpos(realpath($target_path), $base_dir) === 0) {
            
            function deleteRecursive($path) {
                if (is_dir($path)) {
                    $objects = @scandir($path);
                    if ($objects) {
                        foreach ($objects as $object) {
                            if ($object != "." && $object != "..") {
                                deleteRecursive($path . "/" . $object);
                            }
                        }
                    }
                    @rmdir($path);
                } else {
                    @unlink($path);
                }
            }
            
            deleteRecursive($target_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// Rekursiv funksjon for sidemenyen
function renderDirectoryTree($current_dir, $base_dir, $current_path, $depth = 0) {
    if ($depth > 3 && $base_dir === '/') return;
    $scan_items = @scandir($current_dir);
    if ($scan_items === false) return;
    
    $items = array_diff($scan_items, ['.', '..']);
    $dirs = [];
    foreach ($items as $item) {
        $path = $current_dir . '/' . $item;
        if (@is_dir($path) && !@is_link($path)) {
            $dirs[] = $item;
        }
    }
    usort($dirs, 'strcasecmp');
    
    if (!empty($dirs)) {
        echo '<ul style="list-style: none; padding-left: 15px; margin: 0;">';
        foreach ($dirs as $dir) {
            $abs_path = $current_dir . '/' . $dir;
            $rel_path = ltrim(str_replace($base_dir, '', $abs_path), '/');
            $is_active = ($current_path === $rel_path);
            $active_style = $is_active ? 'color: white; background: rgba(255,255,255,0.08); border-left-color: var(--accent); font-weight: bold;' : '';
            
            echo '<li>';
            echo '<a href="?path=' . urlencode($rel_path) . '" style="' . $active_style . '">';
            echo '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 5px; color: ' . htmlspecialchars($GLOBALS['config']['folder_color']) . ';"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>';
            echo htmlspecialchars($dir) . '</a>';
            if ($depth < 2) {
                renderDirectoryTree($abs_path, $base_dir, $current_path, $depth + 1);
            }
            echo '</li>';
        }
        echo '</ul>';
    }
}

// Håndtering av søk eller standard visning
$search_results = [];
if ($search_query !== '') {
    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($target_dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::SELF_FIRST
    );
    
    foreach ($iterator as $file) {
        if (stripos($file->getFilename(), $search_query) !== false) {
            $abs_path = $file->getRealPath();
            if ($abs_path !== __FILE__) {
                $rel_path = ltrim(str_replace($base_dir, '', $abs_path), '/');
                $search_results[] = [
                    'name' => $file->getFilename(),
                    'path' => $rel_path,
                    'is_dir' => $file->isDir(),
                    'size' => $file->isFile() ? $file->getSize() : 0,
                    'dir_rel' => ltrim(str_replace($base_dir, '', dirname($abs_path)), '/')
                ];
            }
        }
    }
    $items = [];
} else {
    $scan_result = @scandir($target_dir);
    $items = $scan_result !== false ? array_diff($scan_result, ['.', '..']) : [];
    usort($items, function($a, $b) use ($target_dir) {
        $a_is_dir = @is_dir($target_dir . '/' . $a);
        $b_is_dir = @is_dir($target_dir . '/' . $b);
        
        if ($a_is_dir && !$b_is_dir) return -1;
        if (!$a_is_dir && $b_is_dir) return 1;
        
        return strcasecmp($a, $b);
    });
}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($t['title']); ?> - Filbehandler</title>
    <style>
        :root {
            --primary: #2c3e50;
            --accent: #3498db;
            --bg: #f8f9fa;
            --border: #dee2e6;
            --row-padding: <?php echo htmlspecialchars($config['line_height']); ?>;
        }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; background: var(--bg); color: #333; display: flex; height: 100vh; overflow: hidden; }
        
        .cp-sidebar { width: 280px; background: var(--primary); color: white; display: flex; flex-direction: column; }
        .cp-sidebar-header { padding: 20px; background: #1a252f; }
        .cp-sidebar-version { font-size: 10px; color: #95a5a6; font-weight: normal; margin-bottom: 4px; }
        .cp-sidebar-title { font-size: 18px; font-weight: bold; }
        .cp-sidebar-menu { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .cp-sidebar-menu li a { display: block; padding: 10px 20px; color: #bdc3c7; text-decoration: none; font-size: 14px; border-left: 4px solid transparent; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .cp-sidebar-menu li a:hover { background: rgba(255,255,255,0.05); color: white; border-left-color: var(--accent); }

        .cp-main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
        .cp-topbar { background: white; padding: 15px 25px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        .cp-toolbar { background: white; padding: 10px 25px; border-bottom: 1px solid var(--border); display: flex; gap: 15px; align-items: center; flex-wrap: wrap; }
        
        .btn { background: var(--accent); color: white; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 500; display: inline-flex; align-items: center; gap: 5px; text-decoration: none; }
        .btn:hover { opacity: 0.9; }
        .btn-success { background: #27ae60; }
        
        .cp-content { flex: 1; padding: 25px; overflow-y: auto; }
        table { width: 100%; border-collapse: collapse; background: white; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        th, td { padding: var(--row-padding) 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 14px; }
        
        th { background: #f1c40f; font-weight: bold; color: #2c3e50; }
        
        tbody tr:nth-child(odd) { background-color: #eef6fc; }
        tbody tr:nth-child(even) { background-color: #ffffff; }
        tbody tr:hover { background-color: #d4e6f1; }
        
        .breadcrumb { font-size: 14px; color: #666; background: #eee; padding: 6px 12px; border-radius: 4px; }
        
        .item-icon { vertical-align: -3px; margin-right: 8px; }

        /* Nedtrekksmeny ("Valg") */
        .dropdown { position: relative; display: inline-block; }
        .dropbtn { background: var(--accent); color: white; padding: 6px 12px; font-size: 13px; border: none; border-radius: 4px; cursor: pointer; font-weight: 500; }
        .dropbtn:hover { opacity: 0.9; }
        .dropdown-content { display: none; position: absolute; right: 0; background-color: white; min-width: 150px; box-shadow: 0 8px 16px rgba(0,0,0,0.15); z-index: 100; border-radius: 6px; border: 1px solid var(--border); overflow: hidden; top: 100%; margin-top: 2px; }
        
        /* Automatisk oppover-visning for elementer nederst */
        .dropdown.dropup .dropdown-content { top: auto; bottom: 100%; margin-top: 0; margin-bottom: 2px; }

        .dropdown-content a, .dropdown-content button { color: #333; padding: 8px 14px; text-decoration: none; display: block; text-align: left; background: none; border: none; width: 100%; font-size: 13px; cursor: pointer; box-sizing: border-box; }
        .dropdown-content a:hover, .dropdown-content button:hover { background-color: #f1f2f6; color: var(--accent); }
        .dropdown-content .menu-delete { color: #e74c3c; }
        .dropdown-content .menu-delete:hover { background-color: #fadbd8; }
        .dropdown.show .dropdown-content { display: block; }
    </style>
</head>
<body>

    <div class="cp-sidebar">
        <div class="cp-sidebar-header">
            <div class="cp-sidebar-version"><?php echo htmlspecialchars($ver); ?></div>
            <div class="cp-sidebar-title"><?php echo htmlspecialchars($t['title']); ?></div>
        </div>
        <ul class="cp-sidebar-menu">
            <?php if ($config['use_login']): ?>
            <li>
                <a href="?action=logout" style="color: #e74c3c; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 5px; font-weight: bold;"><?php echo htmlspecialchars($t['logout']); ?> (<?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?>)</a>
            </li>
            <?php endif; ?>
            <li>
                <a href="?path=" style="<?php echo ($current_path === '') ? 'color: white; background: rgba(255,255,255,0.08); border-left-color: var(--accent); font-weight: bold;' : ''; ?>">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="vertical-align: -2px; margin-right: 5px; color: <?php echo htmlspecialchars($config['folder_color']); ?>;"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
                    <?php echo htmlspecialchars($t['home_root']); ?>
                </a>
                <?php renderDirectoryTree($target_dir, $base_dir, $current_path); ?>
            </li>
        </ul>
    </div>

    <div class="cp-main">
        <div class="cp-topbar">
            <div class="breadcrumb"><?php echo htmlspecialchars($t['path_label']); ?> /<?php echo htmlspecialchars($current_path); ?></div>
            <div><?php echo htmlspecialchars($t['logged_in_as']); ?> <strong><?php echo htmlspecialchars($_SESSION['username'] ?? $t['guest']); ?></strong></div>
        </div>

        <div class="cp-toolbar">
            <?php if ($config['mkfile']): ?>
            <form method="POST" style="display:inline-flex; gap:5px; margin:0;">
                <input type="hidden" name="action" value="mkfile">
                <input type="text" name="file_name" placeholder="<?php echo htmlspecialchars($t['new_file_placeholder']); ?>" required style="padding:6px; border:1px solid var(--border); border-radius:4px; font-size:13px;">
                <button type="submit" class="btn"><?php echo htmlspecialchars($t['new_file_btn']); ?></button>
            </form>
            <?php endif; ?>

            <?php if ($config['mkdir']): ?>
            <form method="POST" style="display:inline-flex; gap:5px; margin:0;">
                <input type="hidden" name="action" value="mkdir">
                <input type="text" name="folder_name" placeholder="<?php echo htmlspecialchars($t['new_folder_placeholder']); ?>" required style="padding:6px; border:1px solid var(--border); border-radius:4px; font-size:13px;">
                <button type="submit" class="btn"><?php echo htmlspecialchars($t['new_folder_btn']); ?></button>
            </form>
            <?php endif; ?>

            <?php if ($config['upload']): ?>
            <form method="POST" enctype="multipart/form-data" id="uploadForm" style="display:inline-flex; gap:5px; margin:0;">
                <input type="file" name="files[]" id="fileInput" multiple style="display:none;" onchange="prepareUpload(this)">
                <button type="button" class="btn btn-success" onclick="document.getElementById('fileInput').removeAttribute('webkitdirectory'); document.getElementById('fileInput').click();"><?php echo htmlspecialchars($t['upload_files_btn']); ?></button>
                <button type="button" class="btn btn-success" onclick="document.getElementById('fileInput').setAttribute('webkitdirectory', ''); document.getElementById('fileInput').click();"><?php echo htmlspecialchars($t['upload_folder_btn']); ?></button>
            </form>
            <?php endif; ?>

            <!-- Søkefelt plassert rett etter opplastingsknappene -->
            <form method="GET" style="display:inline-flex; gap:5px; margin:0; margin-left: auto;">
                <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                <input type="text" name="q" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="<?php echo htmlspecialchars($t['search_placeholder']); ?>" style="padding:6px; border:1px solid var(--border); border-radius:4px; font-size:13px; width: 160px;">
                <button type="submit" class="btn" style="background: #2c3e50;"><?php echo htmlspecialchars($t['search_btn']); ?></button>
                <?php if ($search_query !== ''): ?>
                    <a href="?path=<?php echo urlencode($current_path); ?>" class="btn" style="background: #7f8c8d; text-decoration:none;"><?php echo htmlspecialchars($t['reset_btn']); ?></a>
                <?php endif; ?>
            </form>
        </div>

        <div class="cp-content">
            <?php if ($search_query !== ''): ?>
                <div style="margin-bottom: 15px; font-size: 14px; font-weight: bold; color: #2c3e50;">
                    <?php echo htmlspecialchars($t['search_results']); ?> «<?php echo htmlspecialchars($search_query); ?>» (<?php echo htmlspecialchars($t['found_count']); ?> <?php echo count($search_results); ?>):
                </div>
                <table>
                    <thead>
                        <tr>
                            <th><?php echo htmlspecialchars($t['th_name']); ?></th>
                            <th><?php echo htmlspecialchars($t['th_folder']); ?></th>
                            <th><?php echo htmlspecialchars($t['th_type']); ?></th>
                            <th><?php echo htmlspecialchars($t['th_size']); ?></th>
                            <th style="text-align: right;"><?php echo htmlspecialchars($t['th_actions']); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($search_results)): ?>
                            <tr><td colspan="5" style="text-align: center; color: #7f8c8d;"><?php echo htmlspecialchars($t['no_results']); ?></td></tr>
                        <?php else: ?>
                            <?php foreach ($search_results as $index => $res): ?>
                                <tr>
                                    <td>
                                        <?php if ($res['is_dir']): ?>
                                            <a href="?path=<?php echo urlencode($res['path']); ?>" style="color:var(--accent); text-decoration:none; font-weight:bold; display:inline-flex; align-items:center;">
                                                <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo htmlspecialchars($config['folder_color']); ?>" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
                                                <?php echo htmlspecialchars($res['name']); ?>
                                            </a>
                                        <?php else: ?>
                                            <span style="display:inline-flex; align-items:center;">
                                                <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo htmlspecialchars($config['file_color']); ?>" stroke-width="2"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>
                                                <?php echo htmlspecialchars($res['name']); ?>
                                            </span>
                                        <?php endif; ?>
                                    </td>
                                    <td><a href="?path=<?php echo urlencode($res['dir_rel']); ?>" style="color: #666; text-decoration: none;">/<?php echo htmlspecialchars($res['dir_rel']); ?></a></td>
                                    <td><?php echo $res['is_dir'] ? $t['type_dir'] : $t['type_file']; ?></td>
                                    <td><?php echo $res['is_dir'] ? '-' : round($res['size']/1024, 1) . ' KB'; ?></td>
                                    <td style="text-align: right;">
                                        <div class="dropdown" id="drop-search-<?php echo $index; ?>">
                                            <button type="button" class="dropbtn" onclick="toggleMenu(event, 'drop-search-<?php echo $index; ?>')"><?php echo htmlspecialchars($t['action_choices']); ?></button>
                                            <div class="dropdown-content">
                                                <?php if (!$res['is_dir']): ?>
                                                    <?php if ($config['view']): ?>
                                                        <a href="?path=<?php echo urlencode($current_path); ?>&q=<?php echo urlencode($search_query); ?>&view=<?php echo urlencode($res['name']); ?>&v_path=<?php echo urlencode($res['dir_rel']); ?>" target="_blank"><?php echo htmlspecialchars($t['action_view']); ?></a>
                                                    <?php endif; ?>
                                                    <?php if ($config['edit']): ?>
                                                        <a href="?path=<?php echo urlencode($current_path); ?>&q=<?php echo urlencode($search_query); ?>&edit=<?php echo urlencode($res['name']); ?>&e_path=<?php echo urlencode($res['dir_rel']); ?>"><?php echo htmlspecialchars($t['action_edit']); ?></a>
                                                    <?php endif; ?>
                                                <?php endif; ?>

                                                <?php if (($res['is_dir'] && $config['download_folder']) || (!$res['is_dir'] && $config['download_file'])): ?>
                                                    <a href="?path=<?php echo urlencode($current_path); ?>&q=<?php echo urlencode($search_query); ?>&download=<?php echo urlencode($res['name']); ?>&dl_path=<?php echo urlencode($res['dir_rel']); ?>"><?php echo htmlspecialchars($t['action_download'] . ($res['is_dir'] ? ' (ZIP)' : '')); ?></a>
                                                <?php endif; ?>

                                                <?php if ($config['copy']): ?>
                                                    <button type="button" onclick="copyItem('<?php echo htmlspecialchars($res['name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($res['dir_rel'], ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_copy']); ?></button>
                                                <?php endif; ?>

                                                <?php if ($config['move']): ?>
                                                    <button type="button" onclick="moveItem('<?php echo htmlspecialchars($res['name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($res['dir_rel'], ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_move']); ?></button>
                                                <?php endif; ?>

                                                <?php if ($config['rename']): ?>
                                                    <button type="button" onclick="renameItem('<?php echo htmlspecialchars($res['name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($res['dir_rel'], ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_rename']); ?></button>
                                                <?php endif; ?>

                                                <?php if ($config['chmod']): ?>
                                                    <?php 
                                                    $abs_item_path = $base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $res['dir_rel'] . '/' . $res['name'];
                                                    $curr_perms = file_exists($abs_item_path) ? substr(sprintf('%o', fileperms($abs_item_path)), -4) : '0644';
                                                    ?>
                                                    <button type="button" onclick="chmodItem('<?php echo htmlspecialchars($res['name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($res['dir_rel'], ENT_QUOTES); ?>', '<?php echo $curr_perms; ?>')"><?php echo htmlspecialchars($t['action_chmod']); ?></button>
                                                <?php endif; ?>

                                                <?php if ($config['delete']): ?>
                                                    <button type="button" class="menu-delete" onclick="deleteItem('<?php echo htmlspecialchars($res['name'], ENT_QUOTES); ?>', '<?php echo htmlspecialchars($res['dir_rel'], ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_delete']); ?></button>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th><?php echo htmlspecialchars($t['th_name']); ?></th>
                            <th><?php echo htmlspecialchars($t['th_type']); ?></th>
                            <th><?php echo htmlspecialchars($t['th_size']); ?></th>
                            <th style="text-align: right;"><?php echo htmlspecialchars($t['th_actions']); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($current_path !== ''): ?>
                            <?php $parent = dirname($current_path); if ($parent === '.') $parent = ''; ?>
                            <tr>
                                <td colspan="4">
                                    <a href="?path=<?php echo urlencode($parent); ?>" style="color:var(--accent); text-decoration:none; font-weight:bold; display:inline-flex; align-items:center;">
                                        <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path><line x1="12" y1="11" x2="12" y2="17"></line><line x1="9" y1="14" x2="15" y2="14"></line></svg>
                                        <?php echo htmlspecialchars($t['parent_dir']); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($items as $index => $item): 
                            $path = $target_dir . '/' . $item;
                            $is_dir = @is_dir($path);
                            $rel = ltrim($current_path . '/' . $item, '/');
                        ?>
                            <tr>
                                <td>
                                    <?php if ($is_dir): ?>
                                        <a href="?path=<?php echo urlencode($rel); ?>" style="color:var(--accent); text-decoration:none; font-weight:bold; display:inline-flex; align-items:center;">
                                            <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo htmlspecialchars($config['folder_color']); ?>" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
                                            <?php echo htmlspecialchars($item); ?>
                                        </a>
                                    <?php else: ?>
                                        <span style="display:inline-flex; align-items:center;">
                                            <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="<?php echo htmlspecialchars($config['file_color']); ?>" stroke-width="2"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"></path><polyline points="13 2 13 9 20 9"></polyline></svg>
                                            <?php echo htmlspecialchars($item); ?>
                                        </span>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo $is_dir ? $t['type_dir'] : $t['type_file']; ?></td>
                                <td><?php echo $is_dir ? '-' : (@filesize($path) !== false ? round(@filesize($path)/1024, 1) . ' KB' : '-'); ?></td>
                                <td style="text-align: right;">
                                    <div class="dropdown" id="drop-<?php echo $index; ?>">
                                        <button type="button" class="dropbtn" onclick="toggleMenu(event, 'drop-<?php echo $index; ?>')"><?php echo htmlspecialchars($t['action_choices']); ?></button>
                                        <div class="dropdown-content">
                                            <?php if (!$is_dir): ?>
                                                <?php if ($config['view']): ?>
                                                    <a href="?path=<?php echo urlencode($current_path); ?>&view=<?php echo urlencode($item); ?>" target="_blank"><?php echo htmlspecialchars($t['action_view']); ?></a>
                                                <?php endif; ?>
                                                <?php if ($config['edit']): ?>
                                                    <a href="?path=<?php echo urlencode($current_path); ?>&edit=<?php echo urlencode($item); ?>"><?php echo htmlspecialchars($t['action_edit']); ?></a>
                                                <?php endif; ?>
                                            <?php endif; ?>

                                            <?php if (($is_dir && $config['download_folder']) || (!$is_dir && $config['download_file'])): ?>
                                                <a href="?path=<?php echo urlencode($current_path); ?>&download=<?php echo urlencode($item); ?>"><?php echo htmlspecialchars($t['action_download'] . ($is_dir ? ' (ZIP)' : '')); ?></a>
                                            <?php endif; ?>

                                            <?php if ($config['copy']): ?>
                                                <button type="button" onclick="copyItem('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($current_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_copy']); ?></button>
                                            <?php endif; ?>

                                            <?php if ($config['move']): ?>
                                                <button type="button" onclick="moveItem('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($current_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_move']); ?></button>
                                            <?php endif; ?>

                                            <?php if ($config['rename']): ?>
                                                <button type="button" onclick="renameItem('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($current_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_rename']); ?></button>
                                            <?php endif; ?>

                                            <?php if ($config['chmod']): ?>
                                                <?php 
                                                $curr_perms = file_exists($path) ? substr(sprintf('%o', fileperms($path)), -4) : '0644';
                                                ?>
                                                <button type="button" onclick="chmodItem('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($current_path, ENT_QUOTES); ?>', '<?php echo $curr_perms; ?>')"><?php echo htmlspecialchars($t['action_chmod']); ?></button>
                                            <?php endif; ?>

                                            <?php if ($config['delete']): ?>
                                                <button type="button" class="menu-delete" onclick="deleteItem('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($current_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_delete']); ?></button>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <script>
        window.onclick = function(event) {
            if (!event.target.matches('.dropbtn')) {
                document.querySelectorAll('.dropdown').forEach(d => {
                    d.classList.remove('show');
                    d.classList.remove('dropup');
                });
            }
        }

        function toggleMenu(event, dropdownId) {
            event.stopPropagation();
            let dropdown = document.getElementById(dropdownId);
            let willShow = !dropdown.classList.contains('show');

            document.querySelectorAll('.dropdown').forEach(d => {
                d.classList.remove('show');
                d.classList.remove('dropup');
            });

            if (willShow) {
                let rect = dropdown.getBoundingClientRect();
                let windowHeight = window.innerHeight;
                if (rect.bottom + 200 > windowHeight) {
                    dropdown.classList.add('dropup');
                } else {
                    dropdown.classList.remove('dropup');
                }
                dropdown.classList.add('show');
            }
        }

        <?php if ($config['copy']): ?>
        function copyItem(itemName, itemDir) {
            let f = document.createElement('form');
            f.method = 'POST';
            f.action = '?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
            
            let a = document.createElement('input'); a.type='hidden'; a.name='action'; a.value='copy'; f.appendChild(a);
            let i = document.createElement('input'); i.type='hidden'; i.name='item_name'; i.value=itemName; f.appendChild(i);
            let d = document.createElement('input'); d.type='hidden'; d.name='action_path'; d.value=itemDir; f.appendChild(d);
            
            document.body.appendChild(f);
            f.submit();
        }
        <?php endif; ?>

        <?php if ($config['move']): ?>
        function moveItem(itemName, itemDir) {
            let dest = prompt("<?php echo htmlspecialchars($t['prompt_move'], ENT_QUOTES); ?>", "");
            if (dest !== null) {
                let form = document.createElement('form');
                form.method = 'POST';
                form.action = '?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';

                let actionInput = document.createElement('input');
                actionInput.type = 'hidden'; actionInput.name = 'action'; actionInput.value = 'move';
                form.appendChild(actionInput);

                let itemInput = document.createElement('input');
                itemInput.type = 'hidden'; itemInput.name = 'item_name'; itemInput.value = itemName;
                form.appendChild(itemInput);

                let dirInput = document.createElement('input');
                dirInput.type = 'hidden'; dirInput.name = 'action_path'; dirInput.value = itemDir;
                form.appendChild(dirInput);

                let destInput = document.createElement('input');
                destInput.type = 'hidden'; destInput.name = 'destination'; destInput.value = dest;
                form.appendChild(destInput);

                document.body.appendChild(form);
                form.submit();
            }
        }
        <?php endif; ?>

        <?php if ($config['rename']): ?>
        function renameItem(oldName, itemDir) {
            let name = prompt("<?php echo htmlspecialchars($t['prompt_rename'], ENT_QUOTES); ?>", oldName);
            if (name && name !== oldName) {
                let f = document.createElement('form');
                f.method = 'POST';
                f.action = '?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                let a = document.createElement('input'); a.type='hidden'; a.name='action'; a.value='rename'; f.appendChild(a);
                let i = document.createElement('input'); i.type='hidden'; i.name='old_name'; i.value=oldName; f.appendChild(i);
                let d = document.createElement('input'); d.type='hidden'; d.name='action_path'; d.value=itemDir; f.appendChild(d);
                let n = document.createElement('input'); n.type='hidden'; n.name='new_name'; n.value=name; f.appendChild(n);
                
                document.body.appendChild(f);
                f.submit();
            }
        }
        <?php endif; ?>

        <?php if ($config['chmod']): ?>
        function chmodItem(itemName, itemDir, currentPerms) {
            let perms = prompt("<?php echo htmlspecialchars($t['prompt_chmod'], ENT_QUOTES); ?>", currentPerms);
            if (perms && perms !== currentPerms) {
                let f = document.createElement('form');
                f.method = 'POST';
                f.action = '?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                let a = document.createElement('input'); a.type='hidden'; a.name='action'; a.value='chmod'; f.appendChild(a);
                let i = document.createElement('input'); i.type='hidden'; i.name='item_name'; i.value=itemName; f.appendChild(i);
                let d = document.createElement('input'); d.type='hidden'; d.name='action_path'; d.value=itemDir; f.appendChild(d);
                let p = document.createElement('input'); p.type='hidden'; p.name='permissions'; p.value=perms; f.appendChild(p);
                
                document.body.appendChild(f);
                f.submit();
            }
        }
        <?php endif; ?>

        <?php if ($config['delete']): ?>
        function deleteItem(itemName, itemDir) {
            if (confirm("<?php echo htmlspecialchars($t['confirm_delete'], ENT_QUOTES); ?> " + itemName + "?")) {
                let f = document.createElement('form');
                f.method = 'POST';
                f.action = '?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                let a = document.createElement('input'); a.type='hidden'; a.name='action'; a.value='delete'; f.appendChild(a);
                let i = document.createElement('input'); a.type='hidden'; i.name='item_name'; i.value=itemName; f.appendChild(i);
                let d = document.createElement('input'); a.type='hidden'; d.name='action_path'; d.value=itemDir; f.appendChild(d);
                
                document.body.appendChild(f);
                f.submit();
            }
        }
        <?php endif; ?>

        <?php if ($config['upload']): ?>
        function prepareUpload(input) {
            if (input.files.length > 0) {
                let form = document.getElementById('uploadForm');
                document.querySelectorAll('input[name="relative_paths[]"]').forEach(el => el.remove());

                for (let i = 0; i < input.files.length; i++) {
                    let relPathInput = document.createElement('input');
                    relPathInput.type = 'hidden';
                    relPathInput.name = 'relative_paths[]';
                    relPathInput.value = input.files[i].webkitRelativePath || input.files[i].name;
                    form.appendChild(relPathInput);
                }
                form.submit();
            }
        }
        <?php endif; ?>
    </script>
</body>
</html>