<?php
/**
 * =====================================================================
 * KONTROLLPANEL (LYST TEMA FOR INNLOGGING) - 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.1 (2026-10-29): Flyttet "Valg ▾"-knappen helt til venstre i tabellraden.
 * ver. 1.5.2 (2026-10-29): Fikset z-index slik at menyen flyter over all grafikk.
 * ver. 1.5.3 (2026-10-29): Plassert handlingsmeny under mappe- og filikon.
 * ver. 1.5.4 (2026-11-03): Fjernet "Valg ▾"-knappen og knyttet meny til ikoner.
 * ver. 1.5.5 (2026-11-03): Fikset syntaksfeil og sikret stabil kjøring.
 * ver. 1.5.6 (2026-11-03): Endret tema for selve listedelen/tabellen til lyst.
 * ver. 1.5.7 (2026-11-03): Ryddet og sikret ren PHP-syntaks for feilfri kjøring.
 * ver. 1.5.8 (2026-11-03): Endret verktøylinje og feltet over listen til lyst tema.
 * ver. 1.5.9 (2026-11-03): Markert annenhver linje tydeligere med mørkere farge.
 * ver. 1.6.0 (2026-11-03): Satt bakgrunnsfargen for kolonneoverskriftene til ren gul.
 * ver. 1.6.1 (2026-11-03): Endret bakgrunnsfargen for venstre sidepanel til mørk grå.
 * ver. 1.6.2 (2026-11-03): Handlingsmenyen popper oppover og legges helt fremst.
 * ver. 1.6.3 (2026-11-03): Meny popper nedover for øvre halvdel, oppover for nedre.
 * ver. 1.6.4 (2026-11-03): Fjernet handlingen Flytt.
 * ver. 1.6.5 (2026-11-03): Fjernet handlingen Kopier fra menyen.
 * ver. 1.6.6 (2026-11-03): Implementert "Kopier og Lim inn" med utklippstavle.
 * ver. 1.6.7 (2026-11-03): Lagt til "Lim inn" direkte i handlingsmenyen.
 * ver. 1.6.8 (2026-11-03): Fullstendig feilsøkt og sikret stabil stiberegning.
 * ver. 1.6.9 (2026-11-03): Oppdatert og strukturert fullstendige språktabeller.
 * ver. 1.7.0 (2026-11-03): Lagt til fil- og mappenavn etter "Lim inn" i handlingsmenyen.
 * ver. 1.7.1 (2026-11-03): Fikset syntaksfeil i PHP/HTML-avslutningen ved innlogging.
 * ver. 1.7.2 (2026-11-03): Endret innloggingsvinduet til lyst tema for helhetlig design.
 * ver. 1.7.3 (2026-11-04): Lagt til språkvelger i topplinjen med ensartede 
 *                          rektangulære SVG-flagg og sesjonslagring.
 * =====================================================================
 */

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ver = "ver. 1.7.3 (Språkvelger med rektangulære flagg) 2026-11-04 HBj ";

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ==========================================
// KONSEPTUELLE INNSTILLINGER (KONFIGURASJON)
// ==========================================
$config = [
    'language'        => 'no', // Standard språk hvis ikke satt i sesjon
    'line_height'     => '8px',
    'folder_color'    => '#f39c12',
    'file_color'      => '#bdc3c7',
    '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,  // Aktiverer Kopier og Lim inn
    'move'            => false, // Deaktivert / fjernet
    'chmod'           => true,
    'delete'          => true
];

// ==========================================
// REKTANGULÆRE SVG-FLAGG (ENSARTET STØRRELSE)
// ==========================================
$svg_flags = [
    'no' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#ba0c2f"/><path d="M0 6h22v4H0z" fill="#fff"/><path d="M6 0h4v16H6z" fill="#fff"/><path d="M0 7h22v2H0z" fill="#00205b"/><path d="M7 0h2v16H7z" fill="#00205b"/></svg>',
    'en' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#012169"/><path d="M0 0l22 16m0-16L0 16" stroke="#fff" stroke-width="3"/><path d="M0 0l22 16m0-16L0 16" stroke="#C8102E" stroke-width="1.5"/><path d="M11 0v16M0 8h22" stroke="#fff" stroke-width="5"/><path d="M11 0v16M0 8h22" stroke="#C8102E" stroke-width="3"/></svg>',
    'de' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="5.3" fill="#000"/><rect width="22" height="5.3" y="5.3" fill="#d00"/><rect width="22" height="5.3" y="10.6" fill="#ffce00"/></svg>',
    'fr' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#ed2939"/><rect width="14.6" height="16" fill="#fff"/><rect width="7.3" height="16" fill="#002395"/></svg>',
    'sv' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#006aa7"/><path d="M7 0h3v16H7zM0 6.5h22v3H0z" fill="#fecc00"/></svg>',
    'da' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#c8102e"/><path d="M7 0h3v16H7zM0 6.5h22v3H0z" fill="#fff"/></svg>',
    'sm' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 22 16" width="22" height="16" style="border-radius:2px; object-fit:cover; display:block;"><rect width="22" height="16" fill="#004b87"/><circle cx="8" cy="8" r="4.5" fill="none" stroke="#e21a22" stroke-width="1.8"/><path d="M8 3.5v9M3.5 8h9" stroke="#004b87" stroke-width="0.8"/><path d="M13 0.5" fill="#00853f"/><path d="M13 0h2v16h-2z" fill="#00853f"/><path d="M15 0h2v16h-2z" fill="#ffcc00"/></svg>'
];

// ==========================================
// SPRÅKTABELLER (KOMPLETTE 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_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',
        'action_rename' => 'Endre navn',
        'action_chmod' => 'Tillatelser',
        'action_delete' => 'Slett',
        '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',
        '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' => 'Actions',
        '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',
        'action_rename' => 'Rename',
        'action_chmod' => 'Permissions',
        'action_delete' => 'Delete',
        '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' => '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',
        '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' => 'Aktionen',
        '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' => 'Einfügen',
        'action_rename' => 'Umbenennen',
        'action_chmod' => 'Berechtigungen',
        'action_delete' => 'Löschen',
        '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!'
    ],
    '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',
        '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' => 'Actions',
        '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',
        'action_rename' => 'Renommer',
        'action_chmod' => 'Permissions',
        'action_delete' => 'Supprimer',
        'prompt_rename' => "Nouveau nom :",
        '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',
        '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_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',
        'action_rename' => 'Byt namn',
        'action_chmod' => 'Behörigheter',
        'action_delete' => 'Ta bort',
        '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 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',
        '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' => 'Handlinger',
        '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',
        'action_rename' => 'Omdøb',
        'action_chmod' => 'Tilladelser',
        'action_delete' => 'Slet',
        'prompt_rename' => "Nyt navn:",
        '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á',
        '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' => 'Doaimmat',
        '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' => 'Lible sisa',
        'action_rename' => 'Molso nama',
        'action_chmod' => 'Lohpevuođat',
        'action_delete' => 'Sihko',
        'prompt_rename' => "Ođđa namma:",
        '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!'
    ]
];

// Håndter språkvalg (lagres i sesjon)
if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $lang)) {
    $_SESSION['language'] = $_GET['lang'];
    $clean_url = strtok($_SERVER["REQUEST_URI"], '?');
    $query_params = [];
    if (isset($_GET['path'])) $query_params['path'] = $_GET['path'];
    if (isset($_GET['q'])) $query_params['q'] = $_GET['q'];
    if (!empty($query_params)) {
        $clean_url .= '?' . http_build_query($query_params);
    }
    header("Location: " . $clean_url);
    exit;
}

$current_lang = isset($_SESSION['language']) && array_key_exists($_SESSION['language'], $lang) ? $_SESSION['language'] : (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: #f4f6f9; color: #2c3e50; margin: 0; }
                .login-box { background: #ffffff; padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.08); width: 320px; text-align: left; position: relative; border: 1px solid #dcdde1; }
                .login-version { font-size: 10px; color: #7f8c8d; font-weight: normal; margin-bottom: 8px; }
                .login-box h2 { margin-top: 0; margin-bottom: 5px; text-align: center; color: #2c3e50; }
                .login-subtitle { font-size: 12px; color: #555; margin-bottom: 20px; text-align: center; }
                input[type="text"], input[type="password"] { width: 100%; padding: 10px; margin: 8px 0; background: #ffffff; color: #333; border: 1px solid #bdc3c7; 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; font-weight: 500; }
                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: #2c3e50; 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: #2c3e50; 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;
}

// Håndter Kopier (lagre i sesjon)
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) {
        $source_path = $action_dir . '/' . $item_name;
        if (file_exists($source_path) && $source_path !== __FILE__) {
            $_SESSION['clipboard'] = [
                'path' => $source_path,
                'name' => $item_name,
                'is_dir' => is_dir($source_path)
            ];
        }
    }
    header("Location: ?path=" . urlencode($current_path) . ($search_query !== '' ? '&q=' . urlencode($search_query) : ''));
    exit;
}

// Håndter Lim inn (kopier fra sesjon til angitt destinasjon)
if ($config['copy'] && ((isset($_GET['action']) && $_GET['action'] === 'paste') || ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'paste'))) {
    if (isset($_SESSION['clipboard']) && file_exists($_SESSION['clipboard']['path'])) {
        $source_path = $_SESSION['clipboard']['path'];
        $item_name = $_SESSION['clipboard']['name'];
        
        $dest_dir = $target_dir;
        if (isset($_POST['action_path']) && $_POST['action_path'] !== '') {
            $specified_target = realpath($base_dir . ($base_dir === '/' || substr($base_dir, -1) === '\\' ? '' : '/') . $_POST['action_path']);
            if ($specified_target && is_dir($specified_target) && strpos($specified_target, $base_dir) === 0) {
                $dest_dir = $specified_target;
                if (isset($_POST['target_folder']) && $_POST['target_folder'] !== '') {
                    $sub_target = $specified_target . '/' . $_POST['target_folder'];
                    if (is_dir($sub_target)) {
                        $dest_dir = $sub_target;
                    }
                }
            }
        }

        if ($source_path !== __FILE__ && strpos($source_path, $base_dir) === 0) {
            $dest_path = $dest_dir . '/' . $item_name;
            $counter = 1;
            
            $info = pathinfo($item_name);
            $ext = isset($info['extension']) ? '.' . $info['extension'] : '';
            $filename_only = $info['filename'];
            
            while (file_exists($dest_path)) {
                if (is_dir($source_path)) {
                    $dest_path = $dest_dir . '/' . $item_name . '_kopi_' . $counter;
                } else {
                    $dest_path = $dest_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($source_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 (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 / Å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=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 = $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;
        }
    }
}

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: #2c3e50; color: #e0e0e0; display: flex; flex-direction: column; height: 100vh; }
                    .editor-header { background: #34495e; color: white; padding: 15px 25px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #4e6d8c; }
                    .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 #4e6d8c; border-radius: 6px; resize: none; background: #1a252f; color: #00ff66; 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: #1e4620; color: #a3e9a4; padding: 10px 15px; border-radius: 4px; border: 1px solid #2e7d32; }
                </style>
            </head>
            <body>
                <div class="editor-header">
                    <div><strong>Redigerer fil:</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: #555;"><?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;
        }
    }
}

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;
}

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;
}

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: #3498db; background: rgba(52,152,219,0.2); 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>';
    }
}

$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 (Lyst tema)</title>
    <style>
        :root {
            --primary: #2c3e50;
            --accent: #3498db;
            --bg: #2c3e50;
            --border: #4e6d8c;
            --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: #e0e0e0; display: flex; height: 100vh; overflow: hidden; }
        
        .cp-sidebar { width: 280px; background: var(--primary); color: #ecf0f1; display: flex; flex-direction: column; border-right: 1px solid var(--border); }
        .cp-sidebar-header { padding: 20px; background: #243342; border-bottom: 1px solid var(--border); }
        .cp-sidebar-version { font-size: 10px; color: #bdc3c7; font-weight: normal; margin-bottom: 4px; }
        .cp-sidebar-title { font-size: 18px; font-weight: bold; color: #ffffff; }
        .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: #cbd5e1; 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.08); color: white; border-left-color: var(--accent); }

        .cp-main { flex: 1; display: flex; flex-direction: column; overflow: hidden; background: #f4f6f9; }
        .cp-topbar { background: #ffffff; padding: 15px 25px; border-bottom: 1px solid #dcdde1; display: flex; justify-content: space-between; align-items: center; color: #333; }
        .cp-toolbar { background: #ffffff; padding: 12px 25px; border-bottom: 1px solid #dcdde1; display: flex; gap: 15px; align-items: center; flex-wrap: wrap; }
        
        input[type="text"] { background: #ffffff; color: #333; border: 1px solid #bdc3c7; border-radius: 4px; padding: 6px 10px; font-size: 13px; }
        
        .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; }
        .btn-warning { background: #d35400; }
        
        /* SPRÅKVELGER MED REKTANGULÆRE FLAGG */
        .lang-dropdown { position: relative; display: inline-block; }
        .lang-btn {
            background: #fff;
            border: 1px solid #bdc3c7;
            border-radius: 4px;
            padding: 4px 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            font-weight: bold;
            color: #333;
        }
        .lang-menu {
            display: none;
            position: absolute;
            right: 0;
            background-color: #fff;
            min-width: 150px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            border-radius: 4px;
            z-index: 99999;
            border: 1px solid #dcdde1;
            overflow: hidden;
        }
        .lang-dropdown:hover .lang-menu { display: block; }
        .lang-option {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 12px;
            text-decoration: none;
            color: #333;
            font-size: 12px;
            transition: background 0.2s;
        }
        .lang-option:hover { background-color: #f0f4f8; }

        /* HELT LYST TEMA FOR LISTEDELEN MED REN GUL OVERSKRIFT OG SEBRASTRIPING */
        .cp-content { flex: 1; padding: 25px; overflow-y: auto; background: #f4f6f9; color: #333; position: relative; }
        table { width: 100%; border-collapse: collapse; background: #ffffff; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); border: 1px solid #dcdde1; }
        th, td { padding: var(--row-padding) 15px; text-align: left; border-bottom: 1px solid #e2e8f0; font-size: 14px; vertical-align: middle; color: #2c3e50; position: relative; }
        
        th { background: #ffeb3b; font-weight: bold; color: #1e293b; border-bottom: 2px solid #fbc02d; position: sticky; top: 0; z-index: 10; }
        
        tbody tr { position: relative; }
        tbody tr.menu-open { z-index: 999999; }
        tbody tr:nth-child(odd) { background-color: #ffffff; }
        tbody tr:nth-child(even) { background-color: #e2e8f0; }
        tbody tr:hover { background-color: #cbd5e1; }
        
        .breadcrumb { font-size: 14px; color: #2980b9; background: #eaedf2; padding: 6px 12px; border-radius: 4px; border: 1px solid #dcdde1; }
        .item-icon { vertical-align: -3px; margin-right: 8px; cursor: pointer; }

        /* HANDLINGSMENY - SMART PLASSERING (NED/OPP) */
        .dropdown { position: relative; display: inline-block; text-align: left; }
        
        .dropdown-content { display: none; position: absolute; left: 0; background-color: #ffffff; min-width: 180px; box-shadow: 0 6px 20px rgba(0,0,0,0.2); z-index: 9999999; border-radius: 6px; border: 1px solid #cbd5e1; text-align: left; }
        .dropdown-content.drop-down { top: 100%; margin-top: 5px; box-shadow: 0 6px 20px rgba(0,0,0,0.2); }
        .dropdown-content.drop-up { bottom: 100%; margin-bottom: 5px; box-shadow: 0 -6px 20px rgba(0,0,0,0.2); }

        .dropdown-content a, .dropdown-content button { color: #333; padding: 9px 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: #3498db; color: #fff; }
        .dropdown-content .menu-delete { color: #e74c3c; }
        .dropdown-content .menu-delete:hover { background-color: #c0392b; color: #fff; }
        .dropdown-content.show { display: block; }

        .name-cell-wrapper { display: flex; align-items: center; gap: 8px; }
    </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">
            <li>
                <a href="?" <?php echo ($current_path === '') ? 'style="color: #3498db; background: rgba(52,152,219,0.2); 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="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path><polyline points="9 22 9 12 15 12 15 22"></polyline></svg>
                    <?php echo htmlspecialchars($t['home_root']); ?>
                </a>
            </li>
            <?php renderDirectoryTree($base_dir, $base_dir, $current_path); ?>
        </ul>
    </div>

    <div class="cp-main">
        <div class="cp-topbar">
            <div>
                <span style="font-weight: 500; color: #555;"><?php echo htmlspecialchars($t['path_label']); ?></span>
                <span class="breadcrumb">/<?php echo htmlspecialchars($current_path); ?></span>
            </div>
            <div style="display: flex; align-items: center; gap: 15px; font-size: 13px;">
                <!-- Språkvelger med rektangulære flagg plassert til venstre for "Innlogget som:" -->
                <div class="lang-dropdown">
                    <button class="lang-btn">
                        <?php echo $svg_flags[$current_lang]; ?>
                        <span><?php echo strtoupper($current_lang); ?></span>
                        <span>▼</span>
                    </button>
                    <div class="lang-menu">
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=no" class="lang-option"><?php echo $svg_flags['no']; ?> Norsk (NO)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=en" class="lang-option"><?php echo $svg_flags['en']; ?> English (EN)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=de" class="lang-option"><?php echo $svg_flags['de']; ?> Deutsch (DE)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=fr" class="lang-option"><?php echo $svg_flags['fr']; ?> Français (FR)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=sv" class="lang-option"><?php echo $svg_flags['sv']; ?> Svenska (SV)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=da" class="lang-option"><?php echo $svg_flags['da']; ?> Dansk (DA)</a>
                        <a href="?<?php echo ($current_path !== '' ? 'path=' . urlencode($current_path) . '&' : ''); ?>lang=sm" class="lang-option"><?php echo $svg_flags['sm']; ?> Sámegiella (SM)</a>
                    </div>
                </div>

                <span style="color: #333;"><?php echo htmlspecialchars($t['logged_in_as']); ?> <strong><?php echo htmlspecialchars(isset($_SESSION['username']) ? $_SESSION['username'] : $t['guest']); ?></strong></span>
                <?php if ($config['use_login']): ?>
                    <a href="?action=logout" class="btn" style="background: #e74c3c; padding: 5px 10px; font-size: 12px;"><?php echo htmlspecialchars($t['logout']); ?></a>
                <?php endif; ?>
            </div>
        </div>

        <div class="cp-toolbar">
            <?php if ($config['mkfile']): ?>
                <form method="POST" style="display: 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>
                    <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: 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>
                    <button type="submit" class="btn btn-success"><?php echo htmlspecialchars($t['new_folder_btn']); ?></button>
                </form>
            <?php endif; ?>

            <?php if ($config['copy'] && isset($_SESSION['clipboard'])): ?>
                <form method="POST" style="margin:0; display:inline-block;">
                    <input type="hidden" name="action" value="paste">
                    <input type="hidden" name="action_path" value="<?php echo htmlspecialchars($current_path); ?>">
                    <button type="submit" class="btn btn-warning" title="Lim inn: <?php echo htmlspecialchars($_SESSION['clipboard']['name']); ?>">
                        📋 <?php echo htmlspecialchars($t['action_paste']); ?> (<?php echo htmlspecialchars($_SESSION['clipboard']['name']); ?>)
                    </button>
                </form>
            <?php endif; ?>

            <?php if ($config['upload']): ?>
                <form method="POST" enctype="multipart/form-data" style="display: flex; gap: 5px; margin: 0; align-items: center;">
                    <label class="btn" style="background: #8e44ad; cursor: pointer; margin: 0;">
                        <span>📂 <?php echo htmlspecialchars($t['upload_files_btn']); ?></span>
                        <input type="file" name="files[]" multiple style="display: none;" onchange="this.form.submit()">
                    </label>
                    <label class="btn" style="background: #9b59b6; cursor: pointer; margin: 0;">
                        <span>📁 <?php echo htmlspecialchars($t['upload_folder_btn']); ?></span>
                        <input type="file" name="files[]" webkitdirectory directory multiple style="display: none;" onchange="handleFolderUpload(event, this.form)">
                    </label>
                </form>
            <?php endif; ?>

            <form method="GET" style="display: flex; gap: 5px; 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 htmlspecialchars($t['search_placeholder']); ?>">
                <button type="submit" class="btn" style="background: #2980b9;"><?php echo htmlspecialchars($t['search_btn']); ?></button>
                <?php if ($search_query !== ''): ?>
                    <a href="?<?php echo $current_path !== '' ? 'path=' . urlencode($current_path) : ''; ?>" class="btn" style="background: #7f8c8d;"><?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; color: #555;">
                    <?php echo htmlspecialchars($t['search_results']); ?> "<strong><?php echo htmlspecialchars($search_query); ?></strong>" (<?php echo count($search_results); ?> <?php echo htmlspecialchars($t['found_count']); ?>):
                </div>
                <?php if (empty($search_results)): ?>
                    <div style="background: #ffffff; padding: 20px; border-radius: 6px; text-align: center; color: #777; border: 1px solid #dcdde1;"><?php echo htmlspecialchars($t['no_results']); ?></div>
                <?php else: ?>
                    <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>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($search_results as $res): ?>
                                <tr>
                                    <td>
                                        <div class="name-cell-wrapper">
                                            <?php if ($res['is_dir']): ?>
                                                <?php renderActionDropdown($res['name'], $res['dir_rel'], $res['is_dir'], $config, $t, $svg_flags); ?>
                                                <a href="?path=<?php echo urlencode($res['path']); ?>" style="color: #2980b9; text-decoration: none; font-weight: 500;"><?php echo htmlspecialchars($res['name']); ?></a>
                                            <?php else: ?>
                                                <?php renderActionDropdown($res['name'], $res['dir_rel'], $res['is_dir'], $config, $t, $svg_flags); ?>
                                                <a href="?path=<?php echo urlencode($res['dir_rel']); ?>&view=<?php echo urlencode($res['name']); ?>&v_path=<?php echo urlencode($res['dir_rel']); ?>" target="_blank" style="color: #2980b9; text-decoration: none; font-weight: 500;"><?php echo htmlspecialchars($res['name']); ?></a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                    <td><span style="color: #666; font-size: 13px;">/<?php echo htmlspecialchars($res['dir_rel']); ?></span></td>
                                    <td><?php echo $res['is_dir'] ? htmlspecialchars($t['type_dir']) : htmlspecialchars($t['type_file']); ?></td>
                                    <td><?php echo $res['is_dir'] ? '-' : number_format($res['size'], 0, ',', ' ') . ' b'; ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            <?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>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($current_path !== ''): 
                            $parent_path = dirname($current_path);
                            if ($parent_path === '.' || $parent_path === '/') $parent_path = '';
                        ?>
                            <tr>
                                <td colspan="3">
                                    <a href="?path=<?php echo urlencode($parent_path); ?>" style="color: #2980b9; text-decoration: none; font-weight: 500;">
                                        ↩ <?php echo htmlspecialchars($t['parent_dir']); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($items as $item):
                            if ($item === basename(__FILE__) && $current_path === '') continue;
                            $abs_item_path = $target_dir . '/' . $item;
                            $is_dir = @is_dir($abs_item_path);
                            $size = $is_dir ? 0 : @filesize($abs_item_path);
                        ?>
                            <tr>
                                <td>
                                    <div class="name-cell-wrapper">
                                        <?php if ($is_dir): ?>
                                            <?php renderActionDropdown($item, $current_path, $is_dir, $config, $t, $svg_flags); ?>
                                            <a href="?path=<?php echo urlencode($current_path !== '' ? $current_path . '/' . $item : $item); ?>" style="color: #2980b9; text-decoration: none; font-weight: 500;"><?php echo htmlspecialchars($item); ?></a>
                                        <?php else: ?>
                                            <?php renderActionDropdown($item, $current_path, $is_dir, $config, $t, $svg_flags); ?>
                                            <a href="?path=<?php echo urlencode($current_path); ?>&view=<?php echo urlencode($item); ?>" target="_blank" style="color: #2980b9; text-decoration: none; font-weight: 500;"><?php echo htmlspecialchars($item); ?></a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td><?php echo $is_dir ? htmlspecialchars($t['type_dir']) : htmlspecialchars($t['type_file']); ?></td>
                                <td><?php echo $is_dir ? '-' : number_format($size, 0, ',', ' ') . ' b'; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function handleFolderUpload(event, form) {
            const files = event.target.files;
            for (let i = 0; i < files.length; i++) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'relative_paths[]';
                input.value = files[i].webkitRelativePath || files[i].name;
                form.appendChild(input);
            }
            form.submit();
        }

        document.addEventListener('click', function(event) {
            if (!event.target.closest('.dropdown')) {
                closeAllDropdowns();
            }
        });

        document.querySelector('.cp-content').addEventListener('scroll', function() {
            closeAllDropdowns();
        });

        function closeAllDropdowns() {
            const dropdowns = document.getElementsByClassName("dropdown-content");
            for (let i = 0; i < dropdowns.length; i++) {
                dropdowns[i].classList.remove('show');
                dropdowns[i].classList.remove('drop-down', 'drop-up');
            }
            const rows = document.querySelectorAll('tbody tr');
            for (let i = 0; i < rows.length; i++) {
                rows[i].classList.remove('menu-open');
            }
        }

        function toggleDropdown(spanElement) {
            const dropdown = spanElement.nextElementSibling;
            const isOpen = dropdown.classList.contains('show');
            const row = spanElement.closest('tr');
            
            closeAllDropdowns();
            
            if (!isOpen) {
                const rect = spanElement.getBoundingClientRect();
                const container = document.querySelector('.cp-content');
                const containerRect = container.getBoundingClientRect();
                const middleY = containerRect.top + (containerRect.height / 2);
                
                dropdown.classList.remove('drop-down', 'drop-up');
                if (rect.top < middleY) {
                    dropdown.classList.add('drop-down');
                } else {
                    dropdown.classList.add('drop-up');
                }

                dropdown.classList.add('show');
                if (row) {
                    row.classList.add('menu-open');
                }
            }
            event.stopPropagation();
        }

        function promptRename(oldName, actionPath) {
            const newName = prompt("<?php echo addslashes($t['prompt_rename']); ?>", oldName);
            if (newName && newName !== oldName) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '?path=' + encodeURIComponent('<?php echo $current_path; ?>') + '<?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'rename';
                form.appendChild(actionInput);

                const oldInput = document.createElement('input');
                oldInput.type = 'hidden';
                oldInput.name = 'old_name';
                oldInput.value = oldName;
                form.appendChild(oldInput);

                const newInput = document.createElement('input');
                newInput.type = 'hidden';
                newInput.name = 'new_name';
                newInput.value = newName;
                form.appendChild(newInput);

                const pathInput = document.createElement('input');
                pathInput.type = 'hidden';
                pathInput.name='action_path';
                pathInput.value = actionPath;
                form.appendChild(pathInput);

                document.body.appendChild(form);
                form.submit();
            }
        }

        function promptChmod(itemName, actionPath) {
            const perms = prompt("<?php echo addslashes($t['prompt_chmod']); ?>", "0644");
            if (perms !== null) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '?path=' + encodeURIComponent('<?php echo $current_path; ?>') + '<?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'chmod';
                form.appendChild(actionInput);

                const itemInput = document.createElement('input');
                itemInput.type = 'hidden';
                itemInput.name = 'item_name';
                itemInput.value = itemName;
                form.appendChild(itemInput);

                const pathInput = document.createElement('input');
                pathInput.type = 'hidden';
                pathInput.name = 'action_path';
                pathInput.value = actionPath;
                form.appendChild(pathInput);

                const permsInput = document.createElement('input');
                permsInput.type = 'hidden';
                permsInput.name = 'permissions';
                permsInput.value = perms;
                form.appendChild(permsInput);

                document.body.appendChild(form);
                form.submit();
            }
        }

        function confirmDelete(itemName, actionPath) {
            if (confirm("<?php echo addslashes($t['confirm_delete']); ?> '" + itemName + "'?")) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '?path=' + encodeURIComponent('<?php echo $current_path; ?>') + '<?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>';
                
                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'delete';
                form.appendChild(actionInput);

                const itemInput = document.createElement('input');
                itemInput.type = 'hidden';
                itemInput.name = 'item_name';
                itemInput.value = itemName;
                form.appendChild(itemInput);

                const pathInput = document.createElement('input');
                pathInput.type = 'hidden';
                pathInput.name = 'action_path';
                pathInput.value = actionPath;
                form.appendChild(pathInput);

                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>

<?php
function renderActionDropdown($item, $dir_path, $is_dir, $config, $t, $svg_flags) {
    $current_path = isset($_GET['path']) ? $_GET['path'] : '';
    $search_query = isset($_GET['q']) ? $_GET['q'] : '';
    $ext = strtolower(pathinfo($item, PATHINFO_EXTENSION));
    $is_runnable = in_array($ext, ['php', 'htm', 'html', 'pl']);
    ?>
    <div class="dropdown">
        <span onclick="toggleDropdown(this)" style="cursor: pointer; display: inline-flex; vertical-align: middle;">
            <?php if ($is_dir): ?>
                <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: <?php echo htmlspecialchars($config['folder_color']); ?>; margin: 0;"><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 else: ?>
                <svg class="item-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="color: <?php echo htmlspecialchars($config['file_color']); ?>; margin: 0;"><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 endif; ?>
        </span>
        
        <div class="dropdown-content">
            <?php if (!$is_dir && $config['view']): ?>
                <a href="?path=<?php echo urlencode($dir_path); ?>&view=<?php echo urlencode($item); ?>&v_path=<?php echo urlencode($dir_path); ?>" target="_blank"><?php echo htmlspecialchars($t['action_view']); ?></a>
            <?php endif; ?>

            <?php if (!$is_dir && $config['edit']): ?>
                <a href="?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>&edit=<?php echo urlencode($item); ?>&e_path=<?php echo urlencode($dir_path); ?>"><?php echo htmlspecialchars($t['action_edit']); ?></a>
            <?php endif; ?>

            <?php if (!$is_dir && $config['run_web'] && $is_runnable): ?>
                <a href="/<?php echo htmlspecialchars(ltrim($dir_path . '/' . $item, '/')); ?>" target="_blank" style="color: #27ae60; font-weight: bold;"><?php echo htmlspecialchars($t['action_run_web']); ?></a>
            <?php endif; ?>

            <?php if ($config['download_file'] && (!$is_dir || ($is_dir && $config['download_folder']))): ?>
                <a href="?path=<?php echo urlencode($current_path); ?><?php echo $search_query !== '' ? '&q=' . urlencode($search_query) : ''; ?>&download=<?php echo urlencode($item); ?>&dl_path=<?php echo urlencode($dir_path); ?>">
                    <?php echo $is_dir ? htmlspecialchars($t['action_download_zip']) : htmlspecialchars($t['action_download']); ?>
                </a>
            <?php endif; ?>

            <?php if ($config['copy'] && $item !== basename(__FILE__)): ?>
                <form method="POST" style="margin:0;">
                    <input type="hidden" name="action" value="copy">
                    <input type="hidden" name="item_name" value="<?php echo htmlspecialchars($item); ?>">
                    <input type="hidden" name="action_path" value="<?php echo htmlspecialchars($dir_path); ?>">
                    <button type="submit"><?php echo htmlspecialchars($t['action_copy']); ?></button>
                </form>
            <?php endif; ?>

            <?php if ($config['copy'] && isset($_SESSION['clipboard'])): ?>
                <form method="POST" style="margin:0;">
                    <input type="hidden" name="action" value="paste">
                    <input type="hidden" name="action_path" value="<?php echo htmlspecialchars($dir_path); ?>">
                    <?php if ($is_dir): ?>
                        <input type="hidden" name="target_folder" value="<?php echo htmlspecialchars($item); ?>">
                    <?php endif; ?>
                    <button type="submit" style="color: #d35400; font-weight: bold;">
                        <?php echo htmlspecialchars($t['action_paste']); ?> (<?php echo htmlspecialchars($_SESSION['clipboard']['name']); ?>)
                    </button>
                </form>
            <?php endif; ?>

            <?php if ($config['rename'] && $item !== basename(__FILE__)): ?>
                <button type="button" onclick="promptRename('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dir_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_rename']); ?></button>
            <?php endif; ?>

            <?php if ($config['chmod'] && $item !== basename(__FILE__)): ?>
                <button type="button" onclick="promptChmod('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dir_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_chmod']); ?></button>
            <?php endif; ?>

            <?php if ($config['delete'] && $item !== basename(__FILE__)): ?>
                <button type="button" class="menu-delete" onclick="confirmDelete('<?php echo htmlspecialchars($item, ENT_QUOTES); ?>', '<?php echo htmlspecialchars($dir_path, ENT_QUOTES); ?>')"><?php echo htmlspecialchars($t['action_delete']); ?></button>
            <?php endif; ?>
        </div>
    </div>
    <?php
}