<?php
/**
 * =====================================================================
 * KONTROLLPANEL - ENDRINGSHISTORIKK (CHANGELOG)
 * =====================================================================
 * ver. 1.0.0 (2024-10-24): Første stabile utgave med grunnleggende filbehandling.
 * ver. 1.1.0 (2026-10-25): Lagt til rekursiv søkefunksjon i gjeldende mappe.
 * ver. 1.2.0 (2026-10-25): Lagt til "Kopier" og "Sett tillatelser" (Chmod).
 * ver. 1.3.0 (2026-10-25): Utvidet innlogging med brukernavn ("TT" default) og passord.
 * ver. 1.4.0 (2026-10-25): Konfigurerbar linjehøyde, farger og flerspråklig støtte.
 * ver. 1.4.3 (2026-10-26): Oppdatert standardbruker, passord og linjehøyde til 8px.
 * ver. 1.5.0 (2026-10-26): Lagt til handlingsknappen "Kjør som webside" for 
 *                          php, htm, html og pl i egen fane.
 * ver. 1.5.3.1 (2026-11-01): Stabil utgave med fast venstresidepanel og visning på filnavn.
 * ver. 1.5.6 (2026-11-01): Flyttet handlingsmenyen direkte bak mappe- og filikonene.
 * ver. 1.5.7 (2026-11-01): Satt bakgrunnsfarge for kolonneoverskrifter (th) til gul.
 * ver. 1.5.8 (2026-11-01): Sterkere og tydeligere gulfarge (#ffe066) på overskrifter.
 * ver. 1.5.9 (2026-11-01): Lys blå bakgrunnsfarge på annenhver linje for lesbarhet.
 * ver. 1.5.12 (2026-11-01): Gått over til transparente SVG-ikoner for full fargekontroll.
 * ver. 1.5.13 (2026-11-01): Endret farge på filikonet til rød (#e74c3c) for god kontrast.
 * ver. 1.5.14 (2026-11-01): Lagt til ramme rundt stilinjen (.path-bar).
 * ver. 1.5.15 (2026-11-01): Gjort rammen rundt stilinjen like markant som søkefeltet.
 * ver. 1.5.16 (2026-11-01): Erstattet direkte kopiering med "Kopier og Lim inn" (Copy & Paste).
 * ver. 1.5.17 (2026-11-01): Flyttet "Lim inn" direkte inn som handlingsvalg i menyene.
 * ver. 1.5.18 (2026-11-01): Fjernet unødvendige dialogvinduer og sikret ren intern kopiering.
 * ver. 1.5.19 (2026-11-01): Rettet PHP-syntaksfeil (500-feil) i filredigeringsblokken.
 * ver. 1.5.20 (2026-11-01): Fjernet handlingen "Flytt" helt fra systemet.
 * ver. 1.5.21 (2026-11-01): Fullstendig synkronisering og oppdatering av alle språktabeller.
 * =====================================================================
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ver = "ver. 1.5.21 2026-11-01 HBj ";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ==========================================
// KONSEPTUELLE INNSTILLINGER (KONFIGURASJON)
// ==========================================
$config = [
    'language'        => 'no', // Valgmuligheter: 'no', 'en', 'de', 'fr', 'sv', 'da', 'sm'
    'line_height'     => '8px',
    'folder_color'    => '#f39c12',
    'file_color'      => '#e74c3c',
    'use_login'       => true,
    'username'        => 'TT',
    'password'        => 'tt70131858',
    'system_root'     => false,
    'mkfile'          => true,
    'mkdir'           => true,
    'upload'          => true,
    'download_file'   => true,
    'download_folder' => true,
    'view'            => true,
    'edit'            => true,
    'run_web'         => true,
    'rename'          => true,
    'copy'            => true,
    'chmod'           => true,
    'delete'          => true
];

// ==========================================
// SPRÅKTABELLER (FULLSTENDIG OPPDATERT)
// ==========================================
$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',
        'sidebar_title' => 'Mappestruktur',
        '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' => 'Handling',
        'parent_dir' => '.. (Opp et nivå)',
        'type_dir' => 'Mappe',
        'type_file' => 'Fil',
        'action_view' => 'Vis',
        'action_edit' => 'Rediger',
        'action_run_web' => 'Kjør som webside',
        'action_download' => 'Last ned',
        'action_download_zip' => 'Last ned (ZIP)',
        'action_copy' => 'Kopier',
        'action_paste' => 'Lim inn her',
        'action_chmod' => 'Tillatelser',
        'action_delete' => 'Slett',
        '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',
        'sidebar_title' => 'Folder Structure',
        '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 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' => 'Action',
        'parent_dir' => '.. (Parent directory)',
        'type_dir' => 'Folder',
        'type_file' => 'File',
        'action_view' => 'View',
        'action_edit' => 'Edit',
        'action_run_web' => 'Run as webpage',
        'action_download' => 'Download',
        'action_download_zip' => 'Download (ZIP)',
        'action_copy' => 'Copy',
        'action_paste' => 'Paste here',
        'action_chmod' => 'Permissions',
        'action_delete' => 'Delete',
        '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' => 'Kontrollpanel',
        'subtitle' => 'Entwickelt von H. Bjerkan mit Hilfe von Gemini',
        'login_header' => 'Kontrollpanel',
        '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',
        'sidebar_title' => 'Verzeichnisstruktur',
        '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' => 'Ordner durchsuchen...',
        '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' => 'Aktion',
        'parent_dir' => '.. (Übergeordnetes Verzeichnis)',
        'type_dir' => 'Ordner',
        'type_file' => 'Datei',
        'action_view' => 'Anzeigen',
        'action_edit' => 'Bearbeiten',
        'action_run_web' => 'Als Webseite ausführen',
        'action_download' => 'Herunterladen',
        'action_download_zip' => 'Herunterladen (ZIP)',
        'action_copy' => 'Kopieren',
        'action_paste' => 'Hier einfügen',
        'action_chmod' => 'Berechtigungen',
        'action_delete' => 'Löschen',
        '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!'
    ],
    'fr' => [
        'title' => 'Panneau de contrôle',
        'subtitle' => 'Développé par H. Bjerkan avec l’aide de Gemini',
        'login_header' => 'Panneau de contrôle',
        'username' => "Nom d'utilisateur",
        'password' => 'Mot de passe',
        'login_btn' => 'Se connecter',
        'login_error' => "Nom d'utilisateur ou mot de passe incorrect !",
        'logout' => 'Se déconnecter',
        'logged_in_as' => 'Connecté en tant que :',
        'guest' => 'Invité',
        'home_root' => 'Accueil / Racine',
        'sidebar_title' => 'Structure des dossiers',
        'path_label' => 'Chemin :',
        'new_file_placeholder' => 'Nouveau nom de fichier...',
        'new_file_btn' => '+ Nouveau fichier',
        'new_folder_placeholder' => 'Nouveau nom de dossier...',
        'new_folder_btn' => '+ Nouveau dossier',
        'upload_files_btn' => 'Téléverser fichier(s)',
        'upload_folder_btn' => 'Téléverser dossier',
        'search_placeholder' => 'Rechercher dans le dossier...',
        'search_btn' => 'Rechercher',
        'reset_btn' => 'Réinitialiser',
        'search_results' => 'Résultats de recherche pour',
        'found_count' => 'trouvé(s)',
        'no_results' => 'Aucun fichier ou dossier trouvé.',
        'th_name' => 'Nom',
        'th_folder' => 'Dossier',
        'th_type' => 'Type',
        'th_size' => 'Taille',
        'th_actions' => 'Action',
        'parent_dir' => '.. (Dossier parent)',
        'type_dir' => 'Dossier',
        'type_file' => 'Fichier',
        'action_view' => 'Voir',
        'action_edit' => 'Modifier',
        'action_run_web' => 'Exécuter comme page web',
        'action_download' => 'Télécharger',
        'action_download_zip' => 'Télécharger (ZIP)',
        'action_copy' => 'Copier',
        'action_paste' => 'Coller ici',
        'action_chmod' => 'Permissions',
        'action_delete' => 'Supprimer',
        'prompt_chmod' => "Définir les permissions (ex. 0644 pour les fichiers ou 0755 pour les dossiers) :",
        'confirm_delete' => "Voulez-vous supprimer",
        'back_to_files' => 'Retour',
        'save_changes' => 'Enregistrer les modifications',
        'save_success' => 'Modifications enregistrées avec succès !'
    ],
    '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',
        'sidebar_title' => 'Mappstruktur',
        '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ärd',
        'parent_dir' => '.. (Upp en nivå)',
        'type_dir' => 'Mapp',
        'type_file' => 'Fil',
        'action_view' => 'Visa',
        'action_edit' => 'Redigera',
        'action_run_web' => 'Kör som webbsida',
        'action_download' => 'Ladda ner',
        'action_download_zip' => 'Ladda ner (ZIP)',
        'action_copy' => 'Kopiera',
        'action_paste' => 'Klistra in här',
        'action_chmod' => 'Behörigheter',
        'action_delete' => 'Ta bort',
        '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 har sparats!'
    ],
    'da' => [
        'title' => 'Kontrolpanel',
        'subtitle' => 'Udviklet af H. Bjerkan ved hjælp af Gemini',
        'login_header' => 'Kontrolpanel',
        'username' => 'Brugernavn',
        'password' => 'Adgangskode',
        'login_btn' => 'Log ind',
        'login_error' => 'Forkert brugernavn eller adgangskode!',
        'logout' => 'Log ud',
        'logged_in_as' => 'Logget ind som:',
        'guest' => 'Gæst',
        'home_root' => 'Hjem / Rodmappe',
        'sidebar_title' => 'Mappestruktur',
        'path_label' => 'Sti:',
        'new_file_placeholder' => 'Nyt filnavn...',
        'new_file_btn' => '+ Ny fil',
        'new_folder_placeholder' => 'Nyt mappenavn...',
        'new_folder_btn' => '+ Ny mappe',
        'upload_files_btn' => 'Upload fil(er)',
        'upload_folder_btn' => 'Upload mappe',
        'search_placeholder' => 'Søg i mappe...',
        'search_btn' => 'Søg',
        'reset_btn' => 'Nulstil',
        'search_results' => 'Søgeresultater for',
        'found_count' => 'fundet',
        'no_results' => 'Ingen filer eller mapper fundet.',
        'th_name' => 'Navn',
        'th_folder' => 'Mappe',
        'th_type' => 'Type',
        'th_size' => 'Størrelse',
        'th_actions' => 'Handling',
        'parent_dir' => '.. (Op et niveau)',
        'type_dir' => 'Mappe',
        'type_file' => 'Fil',
        'action_view' => 'Vis',
        'action_edit' => 'Rediger',
        'action_run_web' => 'Kør som webside',
        'action_download' => 'Download',
        'action_download_zip' => 'Download (ZIP)',
        'action_copy' => 'Kopier',
        'action_paste' => 'Sæt ind her',
        'action_chmod' => 'Tilladelser',
        'action_delete' => 'Slet',
        'prompt_chmod' => "Indstil tilladelser (f.eks. 0644 for filer eller 0755 for mapper):",
        'confirm_delete' => "Vil du slette",
        'back_to_files' => 'Tilbage',
        'save_changes' => 'Gem ændringer',
        'save_success' => 'Ændringerne blev gemt med succes!'
    ],
    'sm' => [
        'title' => 'Stivrenbálká',
        'subtitle' => 'H. Bjerkan ovddidan oktan Gemini veahkiin',
        'login_header' => 'Stivrenbálká',
        'username' => 'Geavaheaddjinamma',
        'password' => 'Bálvassánni',
        'login_btn' => 'Logge sisa',
        'login_error' => 'Boisten geavaheaddjinamma dahje bálvassánni!',
        'logout' => 'Logge olggos',
        'logged_in_as' => 'Sisaloggejuvvon:',
        'guest' => 'Guossi',
        'home_root' => 'Ruoktu / Vuođđobihtá',
        'sidebar_title' => 'Kansijarádju',
        'path_label' => 'Bálggis:',
        'new_file_placeholder' => 'Ođđa fiilanamma...',
        'new_file_btn' => '+ Ođđa fiila',
        'new_folder_placeholder' => 'Ođđa kansijanamma...',
        'new_folder_btn' => '+ Ođđa kansija',
        'upload_files_btn' => 'Sádde fiilla(id)',
        'upload_folder_btn' => 'Sádde kansijá',
        'search_placeholder' => 'Oza kansijas...',
        'search_btn' => 'Oza',
        'reset_btn' => 'Máhcat',
        'search_results' => 'Ozamihtut',
        'found_count' => 'gávdnon',
        'no_results' => 'Eai fiillat iige kansijat gávdnon.',
        'th_name' => 'Namma',
        'th_folder' => 'Kansija',
        'th_type' => 'Šlája',
        'th_size' => 'Sturrodat',
        'th_actions' => 'Doaimma',
        'parent_dir' => '.. (Bajit dásis)',
        'type_dir' => 'Kansija',
        'type_file' => 'Fiila',
        'action_view' => 'Čájet',
        'action_edit' => 'Rievdat',
        'action_run_web' => 'Vuodje neahttasiidun',
        'action_download' => 'Vieččal',
        'action_download_zip' => 'Vieččal (ZIP)',
        'action_copy' => 'Kopiere',
        'action_paste' => 'Liibme sisa dáppe',
        'action_chmod' => 'Lohpevuođat',
        'action_delete' => 'Sihko',
        'prompt_chmod' => "Bidja lohpevuođaid (ovdamearkka dihte 0644 fiillaide dahje 0755 kansijaide):",
        'confirm_delete' => "Haluatgo sihkut",
        'back_to_files' => 'Ruovttoluotta',
        'save_changes' => 'Vuorkká rievdadusaid',
        'save_success' => 'Rievdadusat leat vuorkkájuvvon!'
    ]
];

$current_lang = isset($lang[$config['language']]) ? $config['language'] : 'no';
$t = $lang[$current_lang];

$conf_user = $config['username'];
$conf_pass = $config['password'];

// Innloggingshåndtering
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;
    }
}

$base_dir = $config['system_root'] ? ((DIRECTORY_SEPARATOR === '\\') ? substr(__DIR__, 0, 3) : '/') : 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 = '';
}

$search_query = isset($_GET['q']) ? trim($_GET['q']) : '';

// --- HANDLINGER ---

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;
}

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;
}

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;
}

// Lim inn (Paste) fra menyvalg
if ($config['copy'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'paste') {
    $item_name = basename($_POST['item_name']);
    $source_subpath = trim($_POST['source_path'], '/');
    $source_dir = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $source_subpath);
    
    if ($source_dir && strpos($source_dir, $base_dir) === 0) {
        $old_path = $source_dir . '/' . $item_name;
        if (file_exists($old_path) && $old_path !== __FILE__) {
            $dest_path = $target_dir . '/' . $item_name;
            $counter = 1;
            $info = pathinfo($item_name);
            $ext = isset($info['extension']) ? '.' . $info['extension'] : '';
            $filename_only = $info['filename'];

            while (file_exists($dest_path)) {
                $dest_path = $target_dir . '/' . $filename_only . '_kopi_' . $counter . $ext;
                $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;
}

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;
}

if ($config['delete'] && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    $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) {
        $target_path = $action_dir . '/' . $item_name;
        if (file_exists($target_path) && $target_path !== __FILE__) {
            function recursiveDelete($path) {
                if (is_dir($path)) {
                    $files = array_diff(scandir($path), ['.', '..']);
                    foreach ($files as $file) {
                        recursiveDelete($path . '/' . $file);
                    }
                    @rmdir($path);
                } else {
                    @unlink($path);
                }
            }
            recursiveDelete($target_path);
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

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;
                    }
                }
            }
        }
    }
}

// Vis fil
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=windows-1252',
                'html' => 'text/html; charset=windows-1252',
                '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 = isset($mime_types[$ext]) ? $mime_types[$ext] : 'text/plain; charset=utf-8';
            header('Content-Type: ' . $mime_type);
            readfile($item_to_view);
            exit;
        }
    }
}

// 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') {
                @file_put_contents($item_to_edit, $_POST['file_content']);
                $save_message = $t['save_success'];
            }
            
            $file_content = file_get_contents($item_to_edit);
            ?>
            <!DOCTYPE html>
            <html lang="<?php echo $current_lang; ?>">
            <head>
                <meta charset="UTF-8">
                <title><?php echo $t['action_edit']; ?>: <?php echo htmlspecialchars(basename($item_to_edit)); ?></title>
                <style>
                    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 20px; background: #f8f9fa; }
                    .edit-container { background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
                    textarea { width: 100%; height: 500px; font-family: monospace; font-size: 13px; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; margin-top: 10px; }
                    .btn { background: #3498db; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer; text-decoration: none; display: inline-block; font-size: 13px; }
                    .btn-back { background: #95a5a6; margin-right: 10px; }
                    .btn:hover { opacity: 0.9; }
                    .msg { background: #2ecc71; color: white; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
                </style>
            </head>
            <body>
                <div class="edit-container">
                    <?php if (isset($save_message)): ?>
                        <div class="msg"><?php echo $save_message; ?></div>
                    <?php endif; ?>
                    <h2><?php echo $t['action_edit']; ?>: <?php echo htmlspecialchars(basename($item_to_edit)); ?></h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="save_file">
                        <a href="?path=<?php echo urlencode($e_path); ?>" class="btn btn-back"><?php echo $t['back_to_files']; ?></a>
                        <button type="submit" class="btn"><?php echo $t['save_changes']; ?></button>
                        <br><br>
                        <textarea name="file_content"><?php echo htmlspecialchars($file_content); ?></textarea>
                    </form>
                </div>
            </body>
            </html>
            <?php
            exit;
        }
    }
}

// Les inn filer og mapper
$dirs = [];
$files = [];

if ($search_query !== '') {
    function recursiveSearch($dir, $query, $base_dir, &$dirs_result, &$files_result) {
        $items = @scandir($dir);
        if ($items === false) return;
        
        foreach ($items as $item) {
            if ($item === '.' || $item === '..') continue;
            $full_path = $dir . '/' . $item;
            $relative_path = ltrim(substr($full_path, strlen($base_dir)), '/\\');
            
            if (mb_stripos($item, $query) !== false) {
                if (is_dir($full_path)) {
                    $dirs_result[] = [
                        'name' => $item,
                        'path' => $relative_path,
                        'folder' => dirname($relative_path) === '.' ? '' : dirname($relative_path)
                    ];
                } else {
                    $files_result[] = [
                        'name' => $item,
                        'path' => $relative_path,
                        'folder' => dirname($relative_path) === '.' ? '' : dirname($relative_path)
                    ];
                }
            }
            if (is_dir($full_path)) {
                recursiveSearch($full_path, $query, $base_dir, $dirs_result, $files_result);
            }
        }
    }
    recursiveSearch($target_dir, $search_query, $base_dir, $dirs, $files);
} else {
    $scan_items = @scandir($target_dir);
    if ($scan_items !== false) {
        foreach ($scan_items as $item) {
            if ($item === '.' || $item === '..') continue;
            $full_path = $target_dir . '/' . $item;
            if (is_dir($full_path)) {
                $dirs[] = ['name' => $item, 'path' => ($current_path !== '' ? $current_path . '/' : '') . $item];
            } else {
                $files[] = ['name' => $item, 'path' => ($current_path !== '' ? $current_path . '/' : '') . $item];
            }
        }
    }
}

// Hjelpefunksjoner for mappetreet i sidepanelet
function getFolderTree($dir, $base_dir, $current_path) {
    $result = '';
    $items = @scandir($dir);
    if ($items === false) return $result;

    $result .= '<ul>';
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        $full_path = $dir . '/' . $item;
        if (is_dir($full_path)) {
            $rel_path = ltrim(substr($full_path, strlen($base_dir)), '/\\');
            $is_active = ($current_path === $rel_path) ? ' style="font-weight:bold; color:#2980b9;"' : '';
            $result .= '<li>📁 <a href="?path=' . urlencode($rel_path) . '"' . $is_active . '>' . htmlspecialchars($item) . '</a>';
            $result .= getFolderTree($full_path, $base_dir, $current_path);
            $result .= '</li>';
        }
    }
    $result .= '</ul>';
    return $result;
}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <title><?php echo htmlspecialchars($t['title']); ?></title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 13px; margin: 0; background: #f8f9fa; color: #333; display: flex; flex-direction: column; height: 100vh; }
        .header { display: flex; justify-content: space-between; align-items: flex-start; padding: 15px 20px; border-bottom: 2px solid #e9ecef; background: white; }
        .header-title h1 { margin: 0; font-size: 20px; }
        .header-version { font-size: 10px; color: #95a5a6; font-weight: normal; margin-bottom: 4px; }
        .header-subtitle { font-size: 12px; color: #666; margin-top: 4px; }
        .user-info { font-size: 12px; text-align: right; }
        .user-info a { color: #e74c3c; text-decoration: none; margin-left: 8px; }
        
        .main-layout { display: flex; flex: 1; overflow: hidden; }
        
        /* FAST SIDEPANEL TIL VENSTRE */
        .sidebar { width: 260px; background: #fff; border-right: 1px solid #e9ecef; padding: 15px; overflow-y: auto; box-sizing: border-box; }
        .sidebar h3 { font-size: 14px; margin-top: 0; color: #2c3e50; border-bottom: 1px solid #eee; padding-bottom: 8px; }
        .sidebar ul { list-style: none; padding-left: 15px; margin: 5px 0; }
        .sidebar li { margin: 4px 0; }
        .sidebar a { text-decoration: none; color: #333; font-size: 12px; }
        .sidebar a:hover { text-decoration: underline; color: #2980b9; }

        .content-area { flex: 1; padding: 20px; overflow-y: auto; background: #f8f9fa; box-sizing: border-box; }

        .toolbar { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; margin-bottom: 15px; background: white; padding: 12px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .toolbar form { display: flex; gap: 5px; align-items: center; margin: 0; }
        input[type="text"] { padding: 6px 10px; border: 1px solid #ccc; border-radius: 4px; font-size: 12px; }
        .btn { background: #3498db; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; text-decoration: none; display: inline-block; }
        .btn:hover { opacity: 0.9; }
        .btn-reset { background: #95a5a6; }
        
        /* STILINJE MED LIK RAMME SOM SØKEFELTET */
        .path-bar { font-size: 13px; margin-bottom: 15px; background: #ffffff; border: 1px solid #ccc; padding: 8px 10px; border-radius: 4px; box-shadow: 0 1px 2px rgba(0,0,0,0.02); }
        .path-bar a { color: #2980b9; text-decoration: none; }
        .path-bar a:hover { text-decoration: underline; }
        
        /* TABELL OG LINJEHØYDE */
        table { width: 100%; border-collapse: collapse; background: white; border-radius: 6px; overflow: visible; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        th, td { padding: <?php echo $config['line_height']; ?> 8px; text-align: left; border-bottom: 1px solid #eee; vertical-align: middle; }
        
        /* GUL OVERSKRIFT */
        th { background: #ffe066; color: #5f4300; font-weight: 700; font-size: 12px; border-bottom: 2px solid #fcc419; }
        
        /* LYS BLÅ BAKGRUNNSFARGE PÅ ANNENHVER LINJE (ZEBRA-STRIPER) */
        tr.file-row:nth-child(even) { background-color: #f0f7ff; }
        tr.file-row:hover { background: #e2e8f0; }
        
        .icon-cell { width: 40px; text-align: center; overflow: visible !important; }
        .icon-menu-btn { 
            background: none; 
            border: none; 
            padding: 2px 4px; 
            cursor: pointer; 
            font-size: 1.1rem; 
            border-radius: 3px; 
            line-height: 1; 
            vertical-align: middle;
        }
        .icon-menu-btn:hover { background: #cbd5e1; }
        
        /* TRANSPARENTE OG FARGEKONTROLLERTE SVG-IKONER */
        .svg-icon {
            width: 16px;
            height: 16px;
            vertical-align: middle;
            fill: currentColor;
        }
        
        .action-dropdown-wrapper { position: relative; display: inline-block; }
        .dropdown-menu { 
            display: none; 
            position: absolute; 
            top: 100%; 
            left: 0; 
            z-index: 99999; 
            background: #ffffff; 
            border: 1px solid #ccc; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.15); 
            min-width: 150px; 
            border-radius: 4px;
            white-space: nowrap;
            text-align: left;
        }
        .dropdown-menu a { display: block; padding: 6px 12px; text-decoration: none; color: #333; font-size: 12px; }
        .dropdown-menu a:hover { background: #3498db; color: #fff; }
        .dropdown-menu a.text-danger:hover { background: #e74c3c; color: #fff; }
        .dropdown-menu a.paste-action { background: #e8f8f5; color: #16a085; font-weight: bold; border-top: 1px solid #eee; display: none; }
        .dropdown-menu a.paste-action:hover { background: #16a085; color: #fff; }

        .name-cell a { text-decoration: none; color: #2980b9; }
        .name-cell a:hover { text-decoration: underline; }
    </style>
    <script>
        function toggleRowMenu(event, btn) {
            event.stopPropagation();
            var currentMenu = btn.nextElementSibling;
            
            // Sjekk om det ligger noe klart i SessionStorage
            var copiedItem = sessionStorage.getItem('cp_item_name');
            var pasteLink = currentMenu.querySelector('.paste-action');
            if (pasteLink) {
                if (copiedItem) {
                    pasteLink.style.display = 'block';
                    pasteLink.innerText = "📋 " + "<?php echo addslashes($t['action_paste']); ?> (" + copiedItem + ")";
                } else {
                    pasteLink.style.display = 'none';
                }
            }

            // Lukk alle andre åpne menyer
            document.querySelectorAll('.dropdown-menu').forEach(function(m) {
                if (m !== currentMenu) {
                    m.style.display = 'none';
                }
            });

            // Toggle visning for denne menyen
            currentMenu.style.display = (currentMenu.style.display === 'block') ? 'none' : 'block';
        }

        // Lukk menyen når brukeren klikker utenfor
        document.addEventListener('click', function() {
            document.querySelectorAll('.dropdown-menu').forEach(function(m) {
                m.style.display = 'none';
            });
        });

        // Lagre i nettleserens SessionStorage
        function copyItemToClipboard(actionPath, itemName) {
            sessionStorage.setItem('cp_item_name', itemName);
            sessionStorage.setItem('cp_source_path', actionPath);
        }

        // Lim inn i valgt mappe
        function pasteItem(targetPath) {
            var itemName = sessionStorage.getItem('cp_item_name');
            var sourcePath = sessionStorage.getItem('cp_source_path');
            if (!itemName) return;

            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '?path=' + encodeURIComponent(targetPath);
            form.innerHTML = '<input type="hidden" name="action" value="paste">' +
                             '<input type="hidden" name="source_path" value="' + sourcePath + '">' +
                             '<input type="hidden" name="item_name" value="' + itemName + '">';
            document.body.appendChild(form);
            form.submit();
        }

        function chmodItem(actionPath, itemName) {
            var perms = prompt("<?php echo addslashes($t['prompt_chmod']); ?>", "0644");
            if (perms !== null && perms.trim() !== '') {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = '<input type="hidden" name="action" value="chmod">' +
                                 '<input type="hidden" name="action_path" value="' + actionPath + '">' +
                                 '<input type="hidden" name="item_name" value="' + itemName + '">' +
                                 '<input type="hidden" name="permissions" value="' + perms + '">';
                document.body.appendChild(form);
                form.submit();
            }
        }

        function deleteItem(actionPath, itemName) {
            if (confirm("<?php echo addslashes($t['confirm_delete']); ?> " + itemName + "?")) {
                var form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = '<input type="hidden" name="action" value="delete">' +
                                 '<input type="hidden" name="action_path" value="' + actionPath + '">' +
                                 '<input type="hidden" name="item_name" value="' + itemName + '">';
                document.body.appendChild(form);
                form.submit();
            }
        }

        function uploadFolder(input) {
            var files = input.files;
            if (files.length === 0) return;
            var form = document.getElementById('uploadForm');
            
            for (var i = 0; i < files.length; i++) {
                var inputRel = document.createElement('input');
                inputRel.type = 'hidden';
                inputRel.name = 'relative_paths[]';
                inputRel.value = files[i].webkitRelativePath || files[i].name;
                form.appendChild(inputRel);
            }
            form.submit();
        }
    </script>
</head>
<body>

<div class="header">
    <div class="header-title">
        <div class="header-version"><?php echo htmlspecialchars($ver); ?></div>
        <h1><?php echo htmlspecialchars($t['title']); ?></h1>
        <div class="header-subtitle"><?php echo htmlspecialchars($t['subtitle']); ?></div>
    </div>
    <?php if ($config['use_login']): ?>
        <div class="user-info">
            <?php echo $t['logged_in_as']; ?> <strong><?php echo htmlspecialchars($_SESSION['username'] ?? $t['guest']); ?></strong>
            <a href="?action=logout"><?php echo $t['logout']; ?></a>
        </div>
    <?php endif; ?>
</div>

<div class="main-layout">
    <!-- VENSTRE SIDEPANEL FOR MAPPESTRUKTUR -->
    <div class="sidebar">
        <h3>📂 <?php echo htmlspecialchars($t['sidebar_title']); ?></h3>
        <div>
            <a href="?"><strong><?php echo htmlspecialchars($t['home_root']); ?></strong></a>
            <?php echo getFolderTree($base_dir, $base_dir, $current_path); ?>
        </div>
    </div>

    <!-- HOVEDINNHOLD TIL HØYRE -->
    <div class="content-area">
        <div class="toolbar">
            <?php if ($config['mkfile']): ?>
                <form method="POST">
                    <input type="hidden" name="action" value="mkfile">
                    <input type="text" name="file_name" placeholder="<?php echo $t['new_file_placeholder']; ?>" required>
                    <button type="submit" class="btn"><?php echo $t['new_file_btn']; ?></button>
                </form>
            <?php endif; ?>

            <?php if ($config['mkdir']): ?>
                <form method="POST">
                    <input type="hidden" name="action" value="mkdir">
                    <input type="text" name="folder_name" placeholder="<?php echo $t['new_folder_placeholder']; ?>" required>
                    <button type="submit" class="btn"><?php echo $t['new_folder_btn']; ?></button>
                </form>
            <?php endif; ?>

            <?php if ($config['upload']): ?>
                <form id="uploadForm" method="POST" enctype="multipart/form-data">
                    <input type="file" id="fileInput" name="files[]" multiple style="display:none;" onchange="this.form.submit()">
                    <button type="button" class="btn" onclick="document.getElementById('fileInput').click()"><?php echo $t['upload_files_btn']; ?></button>
                    
                    <input type="file" id="folderInput" name="files[]" webkitdirectory directory multiple style="display:none;" onchange="uploadFolder(this)">
                    <button type="button" class="btn" onclick="document.getElementById('folderInput').click()"><?php echo $t['upload_folder_btn']; ?></button>
                </form>
            <?php endif; ?>

            <form method="GET" style="margin-left: auto;">
                <?php if ($current_path !== ''): ?>
                    <input type="hidden" name="path" value="<?php echo htmlspecialchars($current_path); ?>">
                <?php endif; ?>
                <input type="text" name="q" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="<?php echo $t['search_placeholder']; ?>">
                <button type="submit" class="btn"><?php echo $t['search_btn']; ?></button>
                <?php if ($search_query !== ''): ?>
                    <a href="?path=<?php echo urlencode($current_path); ?>" class="btn btn-reset"><?php echo $t['reset_btn']; ?></a>
                <?php endif; ?>
            </form>
        </div>

        <div class="path-bar">
            <strong><?php echo $t['path_label']; ?></strong>
            <a href="?"><?php echo $t['home_root']; ?></a>
            <?php
            if ($current_path !== '') {
                $parts = explode('/', trim($current_path, '/'));
                $accum = '';
                foreach ($parts as $part) {
                    $accum .= ($accum === '' ? '' : '/') . $part;
                    echo ' / <a href="?path=' . urlencode($accum) . '">' . htmlspecialchars($part) . '</a>';
                }
            }
            ?>
        </div>

        <?php if ($search_query !== ''): ?>
            <div style="margin-bottom: 15px; font-weight: bold; color: #2c3e50;">
                <?php echo $t['search_results']; ?> "<?php echo htmlspecialchars($search_query); ?>" (<?php echo count($dirs) + count($files); ?> <?php echo $t['found_count']; ?>):
            </div>
        <?php endif; ?>

        <table>
            <thead>
                <tr>
                    <th style="width: 40px; text-align: center;">📁/📄</th>
                    <th><?php echo $t['th_name']; ?></th>
                    <?php if ($search_query !== ''): ?>
                        <th><?php echo $t['th_folder']; ?></th>
                    <?php endif; ?>
                    <th><?php echo $t['th_type']; ?></th>
                    <th><?php echo $t['th_size']; ?></th>
                </tr>
            </thead>
            <tbody>
                <?php if ($search_query === '' && $current_path !== ''): ?>
                    <?php
                    $parent_path = dirname($current_path);
                    if ($parent_path === '.' || $parent_path === '\\') $parent_path = '';
                    ?>
                    <tr class="file-row">
                        <td style="text-align: center;">📁</td>
                        <td class="name-cell" colspan="<?php echo $search_query !== '' ? 4 : 3; ?>">
                            <a href="?path=<?php echo urlencode($parent_path); ?>"><strong><?php echo $t['parent_dir']; ?></strong></a>
                        </td>
                    </tr>
                <?php endif; ?>

                <?php if (empty($dirs) && empty($files)): ?>
                    <tr>
                        <td colspan="<?php echo $search_query !== '' ? 5 : 4; ?>" style="text-align: center; color: #7f8c8d; padding: 20px;">
                            <?php echo $t['no_results']; ?>
                        </td>
                    </tr>
                <?php endif; ?>

                <!-- MAPPER -->
                <?php foreach ($dirs as $d): ?>
                    <?php
                    $d_action_path = dirname($d['path']);
                    if ($d_action_path === '.' || $d_action_path === '\\') $d_action_path = '';
                    ?>
                    <tr class="file-row">
                        <td class="icon-cell">
                            <div class="action-dropdown-wrapper">
                                <button type="button" class="icon-menu-btn" onclick="toggleRowMenu(event, this)" title="Handlinger">
                                    <svg class="svg-icon" style="color: <?php echo $config['folder_color']; ?>;" viewBox="0 0 24 24"><path d="M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z"/></svg>
                                </button>
                                <div class="dropdown-menu">
                                    <a href="?path=<?php echo urlencode($d['path']); ?>"><?php echo $t['action_view']; ?></a>
                                    <?php if ($config['download_folder']): ?>
                                        <a href="?path=<?php echo urlencode($current_path); ?>&download=<?php echo urlencode($d['name']); ?>&dl_path=<?php echo urlencode($d_action_path); ?>"><?php echo $t['action_download_zip']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['copy']): ?>
                                        <a href="#" onclick="copyItemToClipboard('<?php echo addslashes($d_action_path); ?>', '<?php echo addslashes($d['name']); ?>'); return false;"><?php echo $t['action_copy']; ?></a>
                                        <a href="#" class="paste-action" onclick="pasteItem('<?php echo addslashes($d['path']); ?>'); return false;"><?php echo $t['action_paste']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['chmod']): ?>
                                        <a href="#" onclick="chmodItem('<?php echo addslashes($d_action_path); ?>', '<?php echo addslashes($d['name']); ?>'); return false;"><?php echo $t['action_chmod']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['delete']): ?>
                                        <a href="#" onclick="deleteItem('<?php echo addslashes($d_action_path); ?>', '<?php echo addslashes($d['name']); ?>'); return false;" class="text-danger"><?php echo $t['action_delete']; ?></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td class="name-cell">
                            <a href="?path=<?php echo urlencode($d['path']); ?>"><strong><?php echo htmlspecialchars($d['name']); ?></strong></a>
                        </td>
                        <?php if ($search_query !== ''): ?>
                            <td style="color: #7f8c8d;"><?php echo htmlspecialchars($d['folder']); ?></td>
                        <?php endif; ?>
                        <td><?php echo $t['type_dir']; ?></td>
                        <td>-</td>
                    </tr>
                <?php endforeach; ?>

                <!-- FILER -->
                <?php foreach ($files as $f): ?>
                    <?php
                    $f_action_path = dirname($f['path']);
                    if ($f_action_path === '.' || $f_action_path === '\\') $f_action_path = '';
                    
                    $full_file_path = $base_dir . '/' . $f['path'];
                    $file_size = file_exists($full_file_path) ? number_format(filesize($full_file_path)) . ' B' : '-';
                    $ext = pathinfo($f['name'], PATHINFO_EXTENSION);
                    ?>
                    <tr class="file-row">
                        <td class="icon-cell">
                            <div class="action-dropdown-wrapper">
                                <button type="button" class="icon-menu-btn" onclick="toggleRowMenu(event, this)" title="Handlinger">
                                    <svg class="svg-icon" style="color: <?php echo $config['file_color']; ?>;" viewBox="0 0 24 24"><path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z"/></svg>
                                </button>
                                <div class="dropdown-menu">
                                    <?php if ($config['view']): ?>
                                        <a href="?path=<?php echo urlencode($current_path); ?>&view=<?php echo urlencode($f['name']); ?>&v_path=<?php echo urlencode($f_action_path); ?>" target="_blank"><?php echo $t['action_view']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['edit']): ?>
                                        <a href="?path=<?php echo urlencode($current_path); ?>&edit=<?php echo urlencode($f['name']); ?>&e_path=<?php echo urlencode($f_action_path); ?>"><?php echo $t['action_edit']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['run_web'] && in_array(strtolower($ext), ['php', 'htm', 'html', 'pl'])): ?>
                                        <a href="<?php echo htmlspecialchars($f['name']); ?>" target="_blank"><?php echo $t['action_run_web']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['download_file']): ?>
                                        <a href="?path=<?php echo urlencode($current_path); ?>&download=<?php echo urlencode($f['name']); ?>&dl_path=<?php echo urlencode($f_action_path); ?>"><?php echo $t['action_download']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['copy']): ?>
                                        <a href="#" onclick="copyItemToClipboard('<?php echo addslashes($f_action_path); ?>', '<?php echo addslashes($f['name']); ?>'); return false;"><?php echo $t['action_copy']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['chmod']): ?>
                                        <a href="#" onclick="chmodItem('<?php echo addslashes($f_action_path); ?>', '<?php echo addslashes($f['name']); ?>'); return false;"><?php echo $t['action_chmod']; ?></a>
                                    <?php endif; ?>
                                    <?php if ($config['delete']): ?>
                                        <a href="#" onclick="deleteItem('<?php echo addslashes($f_action_path); ?>', '<?php echo addslashes($f['name']); ?>'); return false;" class="text-danger"><?php echo $t['action_delete']; ?></a>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td class="name-cell">
                            <?php if ($config['view']): ?>
                                <a href="?path=<?php echo urlencode($current_path); ?>&view=<?php echo urlencode($f['name']); ?>&v_path=<?php echo urlencode($f_action_path); ?>" target="_blank"><?php echo htmlspecialchars($f['name']); ?></a>
                            <?php else: ?>
                                <?php echo htmlspecialchars($f['name']); ?>
                            <?php endif; ?>
                        </td>
                        <?php if ($search_query !== ''): ?>
                            <td style="color: #7f8c8d;"><?php echo htmlspecialchars($f['folder']); ?></td>
                        <?php endif; ?>
                        <td><?php echo $t['type_file']; ?></td>
                        <td><?php echo $file_size; ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

</body>
</html>