<?php
ini_set('upload_max_filesize', '500M');
ini_set('post_max_size', '500M');
ini_set('max_execution_time', '300');
ini_set('max_input_time', '300');
session_start();
require_once 'includes/functions.php';
requireLogin();

$user = currentUser();
if (!$user) {
    session_destroy();
    header('Location: index.php');
    exit;
}

if (!checkActiveSession($user['id'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}
$activeTab = $_GET['tab'] ?? 'common';
$isAdmin = isUserAdmin($user);

cleanExpiredFiles();

$uploadMsg = '';
$uploadType = '';
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && $isAjax) {
    header('Content-Type: application/json');
    echo json_encode(['type' => 'error', 'msg' => 'Dosya çok büyük veya sunucu limiti aşıldı.']);
    exit;
}

function handleUpload(array $files, string $area): void {
    global $user, $isAjax;
    if (!isset($files)) {
        if ($isAjax) {
            header('Content-Type: application/json');
            echo json_encode(['type' => 'error', 'msg' => 'Dosya çok büyük veya sunucu limiti aşıldı.']);
            exit;
        }
        return;
    }
    $ok = 0; $fail = 0;
    $lastError = '';
    $farr = $files;
    if (!is_array($farr['name'])) {
        $farr = ['name' => [$farr['name']], 'tmp_name' => [$farr['tmp_name']], 'size' => [$farr['size']], 'error' => [$farr['error']], 'type' => [$farr['type']]];
    }
    foreach ($farr['name'] as $i => $name) {
        if ($farr['error'][$i] === UPLOAD_ERR_INI_SIZE || $farr['error'][$i] === UPLOAD_ERR_FORM_SIZE) { $fail++; continue; }
        if ($farr['error'][$i] !== UPLOAD_ERR_OK) { $fail++; continue; }
        $fileData = [
            'name'     => $farr['name'][$i],
            'tmp_name' => $farr['tmp_name'][$i],
            'size'     => $farr['size'][$i],
            'error'    => $farr['error'][$i],
            'type'     => $farr['type'][$i],
        ];
        $r = handleUserUpload($fileData, $user['id'], $area);
        if ($r['type'] === 'success') {
            $ok++;
        } else {
            $fail++;
            $lastError = $r['msg'];
        }
    }
    if ($ok > 0) {
        $msg = $ok . ' dosya başarıyla yüklendi.' . ($fail > 0 ? ' ' . $fail . ' dosya başarısız. Son hata: ' . $lastError : '');
        $type = 'success';
    } else {
        $msg = $lastError ?: 'Dosya yüklenemedi.';
        $type = 'error';
    }
    if ($isAjax) {
        header('Content-Type: application/json');
        echo json_encode(['type' => $type, 'msg' => $msg]);
        exit;
    }
    $GLOBALS['uploadMsg'] = $msg;
    $GLOBALS['uploadType'] = $type;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    verifyCsrfToken();
    if ($_POST['action'] === 'save_extensions') {
        $raw = $_POST['extensions'] ?? '';
        $exts = array_filter(array_map('trim', explode(',', $raw)), fn($e) => preg_match('/^[a-z0-9]+$/', $e));
        saveAllowedExtensions($exts);
        $uploadMsg = 'Uzantı ayarları kaydedildi.';
        $uploadType = 'success';
        addSystemLog('extensions_update', $user['username'] . ' dosya uzantı ayarlarını güncelledi (' . count($exts) . ' uzantı)', $user['id']);
    } elseif ($_POST['action'] === 'upload_common') {
        handleUpload($_FILES['files'] ?? null, 'common');
    } elseif ($_POST['action'] === 'upload_private') {
        handleUpload($_FILES['files'] ?? null, 'private');
    } elseif ($_POST['action'] === 'delete_file') {
        $fid = $_POST['file_id'] ?? '';
        $file = getFileById($fid);
        if ($file && (
            ($file['area'] === 'common')
            || ($file['owner_id'] ?? '') === $user['id']
            || ($file['recipient_id'] ?? '') === $user['id'])
        ) {
            deleteFile($fid);
            $uploadMsg = 'Dosya silindi.';
            $uploadType = 'success';
        }
    } elseif ($_POST['action'] === 'rename_file') {
        $fid = $_POST['file_id'] ?? '';
        $newName = trim($_POST['new_name'] ?? '');
        if ($newName) {
            renameFile($fid, $newName);
            $uploadMsg = 'Dosya adı güncellendi.';
            $uploadType = 'success';
        }
    } elseif ($_POST['action'] === 'create_share') {
        $fid = $_POST['file_id'] ?? '';
        $maxAccess = (int)($_POST['max_access'] ?? 0);
        $hoursLimit = (int)($_POST['hours_limit'] ?? 0);
        $code = createShare($fid, $user['id'], $maxAccess, $hoursLimit);
        header('Content-Type: application/json');
        echo json_encode(['code' => $code, 'max_access' => $maxAccess, 'hours_limit' => $hoursLimit]);
        exit;
    } elseif ($_POST['action'] === 'change_password') {
        $oldPw = $_POST['old_password'] ?? '';
        $newPw = $_POST['new_password'] ?? '';
        $verify = authenticateUser($user['username'], $oldPw);
        if (!$verify) {
            $uploadMsg = 'Mevcut şifre hatalı.';
            $uploadType = 'error';
        } elseif (strlen($newPw) < 4) {
            $uploadMsg = 'Yeni şifre en az 4 karakter olmalıdır.';
            $uploadType = 'error';
        } else {
            updateUserPassword($user['id'], $newPw);
            session_regenerate_id(true);
            $uploadMsg = 'Şifreniz güncellendi.';
            $uploadType = 'success';
            addSystemLog('password_change', $user['username'] . ' şifre değiştirdi', $user['id']);
        }
    } elseif ($isAdmin && $_POST['action'] === 'create_user') {
        $u = trim($_POST['username'] ?? '');
        $p = $_POST['password'] ?? '';
        $dn = trim($_POST['display_name'] ?? '');
        $sl = (int)($_POST['storage_limit'] ?? 1) * 1048576;
        if (!filter_var($u, FILTER_VALIDATE_EMAIL)) {
            $uploadMsg = 'Geçerli bir e-posta adresi girin.';
            $uploadType = 'error';
        } elseif (strlen($p) < 4) {
            $uploadMsg = 'Şifre en az 4 karakter olmalı.';
            $uploadType = 'error';
        } elseif (getUserByEmail($u)) {
            $uploadMsg = 'Bu e-posta zaten kayıtlı.';
            $uploadType = 'error';
        } else {
            $r = createUser($u, $p, $dn ?: explode('@', $u)[0], $sl);
            $uploadMsg = $r['msg'];
            $uploadType = $r['type'];
            if ($r['type'] === 'success') {
                addSystemLog('user_create', $user['username'] . ' yeni kullanıcı oluşturdu: ' . $u, $user['id']);
            }
        }
    } elseif ($isAdmin && $_POST['action'] === 'delete_user') {
        $uid = $_POST['user_id'] ?? '';
        if ($uid === $user['id']) {
            $uploadMsg = 'Kendinizi silemezsiniz.';
            $uploadType = 'error';
        } else {
            $r = deleteUser($uid);
            $uploadMsg = $r['msg'];
            $uploadType = $r['type'];
            if ($r['type'] === 'success') {
                $delUser = getUserById($uid);
                addSystemLog('user_delete', $user['username'] . ' kullanıcı sildi: ' . ($delUser['username'] ?? $uid), $user['id']);
            }
        }
    } elseif ($isAdmin && $_POST['action'] === 'reset_password') {
        $uid = $_POST['user_id'] ?? '';
        $np = $_POST['new_password'] ?? '';
        if (strlen($np) < 4) {
            $uploadMsg = 'Şifre en az 4 karakter olmalı.';
            $uploadType = 'error';
        } else {
            updateUserPassword($uid, $np);
            $uploadMsg = 'Şifre sıfırlandı.';
            $uploadType = 'success';
            $target = getUserById($uid);
            addSystemLog('password_reset', $user['username'] . ' kullanıcı şifresini sıfırladı: ' . ($target['username'] ?? $uid), $user['id']);
        }
    } elseif ($isAdmin && $_POST['action'] === 'update_storage_limit') {
        $uid = $_POST['user_id'] ?? '';
        $newLimit = (int)($_POST['storage_limit'] ?? 0) * 1048576;
        $r = updateUserStorageLimit($uid, $newLimit);
        $uploadMsg = $r['msg'];
        $uploadType = $r['type'];
        if ($r['type'] === 'success') {
            $target = getUserById($uid);
            addSystemLog('storage_change', $user['username'] . ' kullanıcı depolama limitini değiştirdi: ' . ($target['username'] ?? $uid) . ' → ' . formatBytes($newLimit), $user['id']);
        }
    } elseif ($isAdmin && $_POST['action'] === 'toggle_user_status') {
        $uid = $_POST['user_id'] ?? '';
        if ($uid === $user['id']) {
            $uploadMsg = 'Kendinizi devre dışı bırakamazsınız.';
            $uploadType = 'error';
        } else {
            $r = deactivateUser($uid);
            $uploadMsg = $r['msg'];
            $uploadType = $r['type'];
            if ($r['type'] === 'success') {
                $target = getUserById($uid);
                $status = ($target['active'] ?? true) === false ? 'devre dışı' : 'aktif';
                addSystemLog('user_toggle', $user['username'] . ' kullanıcı durumunu değiştirdi: ' . ($target['username'] ?? $uid) . ' → ' . $status, $user['id']);
            }
        }
    } elseif ($_POST['action'] === 'delete_share') {
        $scode = $_POST['share_code'] ?? '';
        if (deleteShare($scode)) {
            $uploadMsg = 'Paylaşım kaldırıldı.';
            $uploadType = 'success';
        }
    }
}

$commonFiles   = getCommonFiles();
$privateFiles  = getPrivateFiles($user['id']);
$inboxFiles    = getInboxFiles($user['id']);
$commonUsed    = getCommonUsedBytes();
$userStorageUsed = getUserStorageUsed($user['id']);
$userStorageLimit = getUserStorageLimit($user['id']);
$adminSubTab   = $_GET['sub'] ?? 'users';
$poolTotal     = getPoolTotal();
$poolAssigned  = getPoolAssigned();
$poolRemaining = getPoolRemaining();
$poolUsed      = array_sum(array_map(fn($u) => getUserStorageUsed($u['id']), getUsers()));
$allFiles      = getFiles();
$poolPrivate   = array_sum(array_map(fn($f) => (int)($f['size'] ?? 0),
    array_filter($allFiles, fn($f) => ($f['area'] ?? '') === 'private' && !empty($f['owner_id']) && empty($f['recipient_id']) && !isExpired($f))));
$poolInbox     = array_sum(array_map(fn($f) => (int)($f['size'] ?? 0),
    array_filter($allFiles, fn($f) => in_array($f['area'] ?? '', ['private','inbox']) && !empty($f['recipient_id']) && !isExpired($f))));
$notifications = getNotifications($user['id']);
$notifCount    = count($notifications);
$userLogs      = getLoginLogsByUser($user['id'], 10);
$allLogs       = $isAdmin ? getLoginLogs(100) : [];
$systemLogs    = $isAdmin ? getSystemLogs(100) : [];

if ($activeTab === 'private' || $activeTab === 'inbox') {
    $storageUsed = $userStorageUsed;
    $storageLimit = $userStorageLimit;
    $storageLabel = 'Özel Alan';
} else {
    $storageUsed = $commonUsed;
    $storageLimit = MAX_STORAGE;
    $storageLabel = 'Ortak Alan';
}
$storagePercent = $storageLimit > 0 ? round($storageUsed / $storageLimit * 100, 1) : 0;
$allowedExtsJson = json_encode(getAllowedExtensions());
?>
<script>const ALLOWED_EXTENSIONS = <?= $allowedExtsJson ?>;</script>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DataStore — Panel</title>
<style>
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');

  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

  :root {
    --bg: #f3f4f6;
    --surface: #ffffff;
    --surface2: #f9fafb;
    --surface3: #f0f2f5;
    --border: #e5e7eb;
    --border2: #d1d5db;
    --accent: #2563eb;
    --accent-hover: #1d4ed8;
    --accent-glow: rgba(37,99,235,0.08);
    --text: #111827;
    --text-muted: #6b7280;
    --text-dim: #9ca3af;
    --danger: #ef4444;
    --success: #22c55e;
    --warn: #f59e0b;
    --sidebar-w: 220px;
  }

  html, body { height: 100%; font-family: 'Inter', sans-serif; background: var(--bg); color: var(--text); }

  .app { display: flex; height: 100vh; overflow: hidden; }

  /* ── Sidebar ── */
  .sidebar {
    width: var(--sidebar-w);
    min-width: var(--sidebar-w);
    background: var(--surface);
    border-right: 1px solid var(--border);
    display: flex;
    flex-direction: column;
    overflow-y: auto;
  }

  .sidebar-brand {
    padding: 20px 16px 16px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .brand-icon-sm {
    width: 32px;
    height: 32px;
    background: var(--accent);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
  }

  .sidebar-brand-name {
    font-size: 15px;
    font-weight: 700;
    color: var(--text);
    letter-spacing: -0.3px;
  }

  .sidebar-brand-name span { color: var(--accent); }

  .sidebar-nav { padding: 10px 8px; flex: 1; }

  .nav-label {
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: var(--text-dim);
    padding: 8px 8px 4px;
    font-weight: 600;
  }

  .nav-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 9px 10px;
    border-radius: 6px;
    cursor: pointer;
    color: var(--text-muted);
    font-size: 13px;
    font-weight: 500;
    text-decoration: none;
    transition: all 0.15s;
    margin-bottom: 2px;
  }

  .nav-item:hover { background: var(--surface2); color: var(--text); }

  .nav-item.active { background: var(--accent-glow); color: var(--accent); border: 1px solid rgba(37,99,235,0.2); }

  .nav-item .badge {
    margin-left: auto;
    background: var(--accent);
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    padding: 1px 6px;
    border-radius: 10px;
    min-width: 18px;
    text-align: center;
  }

  .storage-bar-wrap { padding: 12px 16px 16px; border-top: 1px solid var(--border); margin-top: auto; }

  .storage-label {
    display: flex;
    justify-content: space-between;
    font-size: 11px;
    color: var(--text-muted);
    margin-bottom: 6px;
  }

  .storage-bar {
    width: 100%;
    height: 4px;
    background: var(--surface3);
    border-radius: 2px;
    overflow: hidden;
  }

  .storage-fill {
    height: 100%;
    background: <?= $storagePercent > 85 ? 'var(--danger)' : ($storagePercent > 60 ? 'var(--warn)' : 'var(--accent)') ?>;
    border-radius: 2px;
    transition: width 0.5s;
  }

  /* ── Main ── */
  .main { flex: 1; display: flex; flex-direction: column; overflow: hidden; }

  .topbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 14px 24px;
    border-bottom: 1px solid var(--border);
    background: var(--surface);
    flex-shrink: 0;
  }

  .topbar-title { font-size: 16px; font-weight: 700; color: var(--text); }
  .topbar-sub { font-size: 12px; color: var(--text-muted); margin-top: 1px; }

  .topbar-actions { display: flex; align-items: center; gap: 10px; }

  .bell-wrap { position: relative; }
  .bell-btn {
    width: 34px; height: 34px; border-radius: 50%; border: 2px solid var(--border);
    cursor: pointer; background: var(--surface2); display: flex; align-items: center;
    justify-content: center; font-size: 16px; transition: border-color 0.15s; position: relative;
  }
  .bell-btn:hover { border-color: var(--accent); }
  .bell-badge {
    position: absolute; top: -4px; right: -4px; background: var(--danger); color: #fff;
    font-size: 9px; font-weight: 700; min-width: 16px; height: 16px; border-radius: 8px;
    display: flex; align-items: center; justify-content: center; padding: 0 4px;
    border: 2px solid var(--surface); line-height: 1;
  }
  .bell-dropdown {
    position: absolute; top: calc(100% + 8px); right: 0; background: var(--surface);
    border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 8px 24px rgba(0,0,0,0.12);
    width: 300px; display: none; z-index: 100; overflow: hidden;
  }
  .bell-dropdown.open { display: block; }
  .bd-header { padding: 12px 16px; font-size: 13px; font-weight: 700; color: var(--text); border-bottom: 1px solid var(--border); }
  .bd-empty { padding: 24px 16px; text-align: center; font-size: 12px; color: var(--text-muted); }
  .bd-item { display: flex; gap: 10px; padding: 10px 16px; border-bottom: 1px solid var(--border); align-items: flex-start; }
  .bd-item:last-child { border-bottom: none; }
  .bd-item-icon { font-size: 14px; flex-shrink: 0; margin-top: 1px; }
  .bd-item-body { flex: 1; min-width: 0; }
  .bd-item-msg { font-size: 12px; color: var(--text); line-height: 1.4; }
  .bd-item-time { font-size: 10px; color: var(--text-dim); margin-top: 3px; }
  .bd-footer { border-top: 1px solid var(--border); padding: 10px 16px; text-align: center; }
  .bd-link { font-size: 12px; color: var(--accent); text-decoration: none; font-weight: 600; }
  .bd-link:hover { text-decoration: underline; }

  .profile-btn {
    width: 34px;
    height: 34px;
    border-radius: 50%;
    border: 2px solid var(--border);
    cursor: pointer;
    overflow: hidden;
    flex-shrink: 0;
    background: var(--accent-glow);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    font-weight: 700;
    color: var(--accent);
    transition: border-color 0.15s;
    position: relative;
  }
  .profile-btn:hover { border-color: var(--accent); }

  .profile-dropdown {
    position: absolute;
    top: calc(100% + 8px);
    right: 0;
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: 10px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
    min-width: 180px;
    display: none;
    z-index: 100;
    overflow: hidden;
  }
  .profile-dropdown.open { display: block; }

  .dropdown-header {
    padding: 14px 16px;
    border-bottom: 1px solid var(--border);
  }
  .dropdown-header .dh-name { font-size: 13px; font-weight: 600; color: var(--text); }
  .dropdown-header .dh-email { font-size: 11px; color: var(--text-muted); }

  .dropdown-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 11px 16px;
    font-size: 13px;
    color: var(--text-muted);
    cursor: pointer;
    text-decoration: none;
    transition: background 0.1s;
    border: none;
    background: none;
    width: 100%;
    font-family: inherit;
    text-align: left;
  }
  .dropdown-item:hover { background: var(--surface2); color: var(--text); }
  .dropdown-item svg { flex-shrink: 0; }
  .dropdown-divider { height: 1px; background: var(--border); margin: 4px 0; }

  .profile-wrap {
    position: relative;
  }

  .btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    padding: 8px 16px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 600;
    font-family: inherit;
    cursor: pointer;
    border: none;
    transition: all 0.15s;
    text-decoration: none;
  }

  .btn-primary { background: var(--accent); color: #fff; }
  .btn-primary:hover { background: var(--accent-hover); }
  .btn-ghost { background: transparent; color: var(--text-muted); border: 1px solid var(--border); }
  .btn-ghost:hover { background: var(--surface2); color: var(--text); }
  .btn-danger { background: transparent; color: var(--danger); border: 1px solid rgba(239,68,68,0.3); }
  .btn-danger:hover { background: rgba(239,68,68,0.1); }
  .btn-sm { padding: 5px 10px; font-size: 12px; }
  .btn-icon { padding: 7px; width: 32px; height: 32px; }

  .content { flex: 1; overflow-y: auto; padding: 24px; }

  /* Upload zone */
  .upload-area {
    border: 1.5px dashed var(--border2);
    border-radius: 10px;
    padding: 28px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    background: var(--surface2);
    margin-bottom: 24px;
  }

  .upload-area:hover, .upload-area.drag-over {
    border-color: var(--accent);
    background: var(--accent-glow);
  }

  .upload-area .ua-icon { font-size: 32px; margin-bottom: 8px; }
  .upload-area .ua-title { font-size: 14px; font-weight: 600; color: var(--text); margin-bottom: 4px; }
  .upload-area .ua-sub { font-size: 12px; color: var(--text-muted); }
  .upload-area .ua-file { font-size: 13px; color: var(--accent); margin-top: 8px; font-weight: 500; }

  /* File grid */
.files-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    gap: 14px;
}

  .files-grid.view-compact {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 10px;
  }

  .files-grid.view-compact .file-card {
    padding: 12px;
  }

  .files-grid.view-compact .file-icon {
    font-size: 28px;
    margin-bottom: 6px;
  }

  .files-grid.view-compact .file-name {
    font-size: 12px;
  }

  .files-grid.view-compact .file-meta {
    font-size: 10px;
  }

  .files-grid.view-compact .file-actions {
    margin-top: 8px;
    gap: 4px;
  }

  .files-grid.view-compact .file-actions .btn-sm {
    font-size: 10px;
    padding: 3px 6px;
  }

  .files-grid.view-list {
    grid-template-columns: 1fr;
    gap: 6px;
  }

  .files-grid.view-list .file-card {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 14px;
  }

  .files-grid.view-list .file-icon {
    font-size: 22px;
    margin-bottom: 0;
    flex-shrink: 0;
  }

  .files-grid.view-list .file-name-wrap {
    flex: 1;
    min-width: 0;
  }

  .files-grid.view-list .file-name {
    font-size: 13px;
    margin-bottom: 0;
  }

  .files-grid.view-list .file-meta {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-shrink: 0;
    font-size: 11px;
    margin: 0;
  }

  .files-grid.view-list .file-expire {
    white-space: nowrap;
  }

  .files-grid.view-list .file-actions {
    margin-top: 0;
    flex-shrink: 0;
  }

  .files-grid.view-list .file-actions .btn-sm {
    font-size: 11px;
    padding: 4px 8px;
  }

  .files-grid.view-list .file-card-wrap .file-checkbox {
    top: 50%;
    left: 4px;
    transform: translateY(-50%);
  }

  .files-grid.view-list .file-card {
    padding-left: 28px;
  }

  .file-card {
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 16px;
    transition: all 0.15s;
    cursor: pointer;
    position: relative;
  }

  .file-card:hover { border-color: var(--border2); background: var(--surface3); transform: translateY(-1px); }

  .file-icon { font-size: 36px; margin-bottom: 10px; display: block; }

  .file-name {
    font-size: 13px;
    font-weight: 600;
    color: var(--text);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 4px;
  }

  .file-meta {
    font-size: 11px;
    color: var(--text-muted);
    line-height: 1.6;
  }

  .file-expire { color: var(--warn); }

  .file-actions {
    display: flex;
    gap: 6px;
    margin-top: 12px;
    flex-wrap: wrap;
  }

  .inbox-tag {
    position: absolute;
    top: 10px;
    right: 10px;
    background: var(--accent);
    color: #fff;
    font-size: 10px;
    padding: 2px 7px;
    border-radius: 10px;
    font-weight: 600;
  }

  .remote-tag {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #8b5cf6;
    color: #fff;
    font-size: 10px;
    padding: 2px 7px;
    border-radius: 10px;
    font-weight: 600;
    white-space: nowrap;
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    color: var(--text-muted);
  }

  .empty-state .es-icon { font-size: 48px; margin-bottom: 12px; }
  .empty-state .es-title { font-size: 16px; font-weight: 600; margin-bottom: 6px; }
  .empty-state .es-sub { font-size: 13px; }

  /* Modal */
  .modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.75);
    z-index: 1000;
    display: none;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(4px);
  }

  .modal-overlay.open { display: flex; }

  .modal {
    background: var(--surface);
    border: 1px solid var(--border2);
    border-radius: 14px;
    padding: 28px;
    max-width: 520px;
    width: 90%;
    position: relative;
    max-height: 90vh;
    overflow-y: auto;
  }

  .modal-wide {
    width: 70vw;
    max-width: 1100px;
    height: 70vh;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
    padding: 0;
    overflow: hidden;
  }

  .modal-wide .modal-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20px 28px 0 28px;
    flex-shrink: 0;
  }

  .modal-wide .modal-header-text {
    flex: 1;
    min-width: 0;
  }

  .modal-wide .modal-title {
    font-size: 18px;
    font-weight: 700;
  }

  .modal-wide .modal-sub {
    font-size: 12px;
    color: var(--text-muted);
    margin-top: 2px;
  }

  .modal-wide .modal-body {
    flex: 1;
    min-height: 0;
    padding: 16px 28px 24px 28px;
    display: flex;
    flex-direction: column;
  }

  .modal-close {
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: 8px;
    color: var(--text-muted);
    cursor: pointer;
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    flex-shrink: 0;
    transition: all 0.15s;
  }

  .modal-close:hover { color: var(--text); background: var(--surface3); border-color: var(--text-dim); }

  .preview-split {
    display: flex;
    gap: 24px;
    min-height: 0;
    flex: 1;
  }

  .preview-left {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .preview-container {
    background: var(--surface2);
    border-radius: 12px;
    overflow: hidden;
    flex: 1;
    min-height: 180px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: inset 0 1px 3px rgba(0,0,0,0.06);
  }

  .preview-container img, .preview-container video, .preview-container audio {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }

  .preview-container iframe { width: 100%; height: 100%; border: none; }

  .preview-fallback {
    text-align: center;
    padding: 40px 30px;
    color: var(--text-muted);
  }

  .preview-fallback .pf-icon { font-size: 52px; margin-bottom: 12px; opacity: 0.7; }
  .preview-fallback .pf-msg { font-size: 14px; margin-bottom: 8px; font-weight: 600; color: var(--text); }
  .preview-fallback .pf-sub { font-size: 12px; line-height: 1.6; max-width: 320px; margin: 0 auto; }

  .preview-actions {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
    margin-top: 12px;
    flex-shrink: 0;
  }

  .preview-right {
    width: 300px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 0;
    min-height: 0;
  }

  .file-info-grid {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 4px 14px;
    font-size: 12px;
    background: var(--surface2);
    border-radius: 10px;
    padding: 12px 14px;
    overflow-y: auto;
    flex-shrink: 0;
    max-height: 50%;
  }

  .fi-label { color: var(--text-muted); font-weight: 500; white-space: nowrap; }
  .fi-val { color: var(--text); word-break: break-all; }

  .preview-right-bottom {
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid var(--border);
    overflow-y: auto;
    flex: 1;
  }

  .dl-section-title {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 10px;
  }

  .btn-full { width: 100%; justify-content: center; }

  .security-note {
    margin-top: 12px;
    padding: 10px 12px;
    background: var(--surface3);
    border-radius: 8px;
    font-size: 11px;
    color: var(--text-muted);
    line-height: 1.5;
  }

  .share-code-display {
    background: var(--surface3);
    border: 1px solid var(--accent);
    border-radius: 8px;
    padding: 14px;
    text-align: center;
    margin-top: 12px;
  }

  .share-code-display .scd-label { font-size: 11px; color: var(--text-muted); margin-bottom: 6px; }

  .share-code-display .scd-code {
    font-family: 'Courier New', monospace;
    font-size: 28px;
    font-weight: 800;
    color: var(--accent);
    letter-spacing: 6px;
  }

  .share-code-display .scd-expire { font-size: 11px; color: var(--text-dim); margin-top: 6px; }

  .form-group { margin-bottom: 14px; }

  .form-group label {
    display: block;
    font-size: 11px;
    color: var(--text-muted);
    margin-bottom: 5px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.8px;
  }

  .form-input {
    width: 100%;
    background: var(--surface2);
    border: 1px solid var(--border);
    border-radius: 6px;
    padding: 9px 12px;
    color: var(--text);
    font-size: 13px;
    font-family: inherit;
    outline: none;
    transition: border-color 0.2s;
  }

  .form-input:focus { border-color: var(--accent); }

  .pw-group { position: relative; }
  .pw-eye-btn {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    background: none;
    border: none;
    color: var(--text-muted);
    cursor: pointer;
    font-size: 14px;
  }

  .section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    gap: 12px;
  }

  .section-title { font-size: 15px; font-weight: 700; }
  .section-count { font-size: 12px; color: var(--text-muted); margin-left: 8px; }

  .view-toggle {
    display: flex;
    gap: 2px;
    background: var(--surface2);
    border-radius: 8px;
    padding: 2px;
    flex-shrink: 0;
  }

  .view-btn {
    width: 30px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    background: transparent;
    border-radius: 6px;
    cursor: pointer;
    font-size: 14px;
    color: var(--text-muted);
    transition: all 0.15s;
  }

  .view-btn:hover { color: var(--text); }
  .view-btn.active { background: var(--surface); color: var(--accent); box-shadow: 0 1px 3px rgba(0,0,0,0.08); }

  /* Logout */
  .logout-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 9px 10px;
    color: var(--danger);
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
    border-radius: 6px;
    margin: 0 8px 8px;
    text-decoration: none;
    transition: background 0.15s;
  }

  .logout-btn:hover { background: rgba(239,68,68,0.08); }

  /* ── Toast bildirim ── */
  .toast-container {
    position: fixed;
    bottom: 24px;
    right: 24px;
    z-index: 9999;
    display: flex;
    flex-direction: column;
    gap: 10px;
    pointer-events: none;
  }
  .toast {
    pointer-events: auto;
    padding: 8px 14px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 600;
    box-shadow: 0 4px 24px rgba(0,0,0,0.12);
    animation: toastIn 0.35s ease, toastOut 0.35s ease 3.5s forwards;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .toast-success { background: #22c55e; color: #fff; }
  .toast-error { background: #ef4444; color: #fff; }
  @keyframes toastIn {
    from { opacity: 0; transform: translateX(40px); }
    to { opacity: 1; transform: translateX(0); }
  }
  @keyframes toastOut {
    from { opacity: 1; transform: translateX(0); }
    to { opacity: 0; transform: translateX(40px); }
  }

  /* ── Yuvarlak ilerleme göstergesi ── */
  .progress-wrap {
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9999;
    display: none;
    flex-direction: column;
    align-items: center;
    background: #fff;
    padding: 12px 20px 10px;
    border-radius: 14px 14px 0 0;
    box-shadow: 0 -2px 20px rgba(0,0,0,0.1);
    cursor: pointer;
    min-width: 520px;
    user-select: none;
  }
  .progress-wrap.visible { display: flex; }
  .progress-row {
    display: flex;
    align-items: center;
    gap: 12px;
    width: 100%;
  }
  .progress-label { font-size: 12px; font-weight: 600; color: #111827; white-space: nowrap; flex: 1; }
  .progress-ring-wrap {
    position: relative;
    width: 44px;
    height: 44px;
    flex-shrink: 0;
  }
  .progress-ring {
    width: 44px;
    height: 44px;
    transform: rotate(-90deg);
  }
  .progress-ring-bg {
    fill: none;
    stroke: #e5e7eb;
    stroke-width: 3.5;
  }
  .progress-ring-fill {
    fill: none;
    stroke: #f59e0b;
    stroke-width: 3.5;
    stroke-linecap: round;
    transition: stroke-dashoffset 0.25s ease, stroke 0.4s ease;
  }
  .progress-ring-fill.done { stroke: #22c55e; }
  .progress-pct {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 10px;
    font-weight: 700;
    color: #111827;
  }
  .progress-pct.done { color: #22c55e; }
  .progress-detail {
    display: none;
    width: 100%;
    margin-top: 8px;
    border-top: 1px solid #eee;
    padding-top: 8px;
    font-size: 11px;
    color: #6b7280;
    max-height: 120px;
    overflow-y: auto;
  }
  .progress-detail.open { display: block; }
  .detail-item {
    display: flex;
    justify-content: space-between;
    padding: 3px 0;
    gap: 8px;
  }
  .detail-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; }
  .detail-size { flex-shrink: 0; color: #9ca3af; }
  .progress-cancel {
    background: none;
    border: none;
    color: #ef4444;
    font-size: 11px;
    font-weight: 600;
    cursor: pointer;
    padding: 2px 8px;
    border-radius: 4px;
    transition: background 0.15s;
    flex-shrink: 0;
  }
  .progress-cancel:hover { background: #fef2f2; }

  /* ── Hamburger / Mobile ── */
  .hamburger {
    display: none;
    width: 36px;
    height: 36px;
    border-radius: 6px;
    border: 1px solid var(--border);
    background: var(--surface2);
    cursor: pointer;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    transition: border-color 0.15s;
  }
  .hamburger:hover { border-color: var(--accent); }
  .hamburger svg { width: 20px; height: 20px; stroke: var(--text-muted); }

  .sidebar-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.5);
    z-index: 99;
  }
  .sidebar-overlay.open { display: block; }

  @media (max-width: 900px) {
    .sidebar {
      position: fixed;
      left: -100%;
      top: 0;
      bottom: 0;
      z-index: 100;
      transition: left 0.3s ease;
      box-shadow: 4px 0 24px rgba(0,0,0,0.15);
    }
    .sidebar.open { left: 0; }
    .hamburger { display: flex; }
  }

  /* ── Search bar ── */
  .search-wrap {
    position: relative;
    flex: 1;
    max-width: 320px;
    margin: 0 16px;
  }
  .search-wrap .search-icon {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    width: 15px;
    height: 15px;
    color: var(--text-dim);
    pointer-events: none;
  }
  .search-input {
    width: 100%;
    padding: 7px 10px 7px 32px;
    border: 1px solid var(--border);
    border-radius: 6px;
    background: var(--surface2);
    font-size: 12.5px;
    font-family: inherit;
    color: var(--text);
    outline: none;
    transition: border-color 0.2s;
  }
  .search-input:focus { border-color: var(--accent); background: var(--surface); }
  .search-input::placeholder { color: var(--text-dim); }

  .topbar-left { display: flex; align-items: center; flex: 1; min-width: 0; }

  /* ── Batch action bar ── */
  .batch-bar {
    display: none;
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    z-index: 9998;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    background: var(--accent);
    color: #fff;
    border-radius: 14px 14px 0 0;
    font-size: 12.5px;
    font-weight: 600;
    min-width: 520px;
    box-shadow: 0 -2px 20px rgba(0,0,0,0.1);
  }
  .batch-bar.visible { display: flex; }
  .batch-bar .batch-count { flex: 1; font-size: 12px; }
  .batch-bar .batch-btn {
    background: rgba(255,255,255,0.2);
    border: 1px solid rgba(255,255,255,0.3);
    color: #fff;
    padding: 5px 12px;
    border-radius: 5px;
    font-size: 11.5px;
    font-weight: 600;
    font-family: inherit;
    cursor: pointer;
    transition: background 0.15s;
  }
  .batch-bar .batch-btn:hover { background: rgba(255,255,255,0.35); }
  .batch-bar .batch-btn-danger { background: rgba(239,68,68,0.5); border-color: rgba(239,68,68,0.4); }
  .batch-bar .batch-btn-danger:hover { background: rgba(239,68,68,0.7); }

  .file-card-wrap { position: relative; }

  .file-checkbox {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 2;
    width: 18px;
    height: 18px;
    accent-color: var(--accent);
    cursor: pointer;
    opacity: 0;
    transition: opacity 0.15s;
  }
  .file-card-wrap:hover .file-checkbox,
  .file-checkbox:checked { opacity: 1; }
  .file-card-wrap.selected .file-card {
    border-color: var(--accent);
    background: var(--accent-glow);
  }

  /* ── Version badges ── */
  .version-badge-sm {
    display: inline-flex;
    align-items: center;
    gap: 2px;
    font-size: 9px;
    font-weight: 700;
    background: var(--accent);
    color: #fff;
    padding: 1px 5px;
    border-radius: 4px;
    margin-left: 5px;
    vertical-align: middle;
  }
  .file-name-wrap { display: flex; align-items: center; min-width: 0; }

  .version-list { margin-top: 8px; border-top: 1px solid var(--border); padding-top: 8px; max-height: 140px; overflow-y: auto; flex-shrink: 0; }
  .version-list-title { font-size: 11px; font-weight: 600; color: var(--text-muted); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }
  .version-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 6px 8px;
    border-radius: 5px;
    font-size: 12px;
    cursor: pointer;
    transition: background 0.1s;
  }
  .version-item:hover { background: var(--surface2); }
  .version-item.current { background: var(--accent-glow); font-weight: 600; }
  .version-item .v-icon { font-size: 14px; flex-shrink: 0; }
  .version-item .v-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
  .version-item .v-size { color: var(--text-dim); font-size: 11px; }
  .version-item .v-badge { font-size: 9px; font-weight: 700; background: var(--accent); color: #fff; padding: 1px 5px; border-radius: 4px; }
</style>
</head>
<body>
<div class="app">

  <!-- SİDEBAR -->
  <div class="sidebar-overlay" id="sidebar-overlay" onclick="toggleSidebar()"></div>

  <aside class="sidebar" id="sidebar">
    <div class="sidebar-brand">
      <div class="brand-icon-sm">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
          <path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/>
        </svg>
      </div>
      <div class="sidebar-brand-name">Data<span>Store</span></div>
    </div>

    <nav class="sidebar-nav" style="margin-top:12px">
      <div class="nav-label">Dosyalar</div>
      <a href="?tab=common" class="nav-item <?= $activeTab === 'common' ? 'active' : '' ?>">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/>
          <path d="M23 21v-2a4 4 0 00-3-3.87"/><path d="M16 3.13a4 4 0 010 7.75"/>
        </svg>
        Ortak Alan
        <?php if (count($commonFiles) > 0): ?>
          <span class="badge"><?= count($commonFiles) ?></span>
        <?php endif; ?>
      </a>
      <a href="?tab=inbox" class="nav-item <?= $activeTab === 'inbox' ? 'active' : '' ?>">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/>
          <path d="M5.45 5.11L2 12v6a2 2 0 002 2h16a2 2 0 002-2v-6l-3.45-6.89A2 2 0 0016.76 4H7.24a2 2 0 00-1.79 1.11z"/>
        </svg>
        Bana Gelenler
        <?php if (count($inboxFiles) > 0): ?>
          <span class="badge"><?= count($inboxFiles) ?></span>
        <?php endif; ?>
      </a>
      <a href="?tab=private" class="nav-item <?= $activeTab === 'private' ? 'active' : '' ?>">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>
        </svg>
        Özel Alan
        <?php if (count($privateFiles) > 0): ?>
          <span class="badge"><?= count($privateFiles) ?></span>
        <?php endif; ?>
      </a>
      <a href="?tab=shares" class="nav-item <?= $activeTab === 'shares' ? 'active' : '' ?>">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
          <line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
        </svg>
        Paylaşılanlar
      </a>
      <?php if ($isAdmin): ?>
      <div class="nav-label" style="margin-top:12px">Yönetim</div>
      <a href="?tab=admin" class="nav-item <?= $activeTab === 'admin' ? 'active' : '' ?>">
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/>
        </svg>
        Sistem Yönetimi
      </a>
      <?php endif; ?>
    </nav>

    <div class="storage-bar-wrap" id="sidebar-storage">
      <div class="storage-label">
        <span><?= $storageLabel ?></span>
        <span><?= formatBytes($storageUsed) ?> / <?= formatBytes($storageLimit) ?></span>
      </div>
      <div class="storage-bar">
        <div class="storage-fill" style="width: <?= min(100, $storagePercent) ?>%"></div>
      </div>
    </div>

    <a href="logout.php" class="logout-btn">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
      </svg>
      Çıkış Yap
    </a>
  </aside>

  <!-- MAIN -->
  <div class="main">
    <div class="topbar">
      <div class="topbar-left">
        <button class="hamburger" onclick="toggleSidebar()" title="Menü">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
        </button>
        <div>
          <div class="topbar-title">
            <?php
            if ($activeTab === 'common') echo '📁 Ortak Alan';
            elseif ($activeTab === 'inbox') echo '📬 Bana Gelenler';
            elseif ($activeTab === 'private') echo '🔒 Özel Alan';
            elseif ($activeTab === 'shares') echo '🔗 Paylaşılanlar';
            elseif ($activeTab === 'admin') echo '👥 Kullanıcı Yönetimi';
            else echo '⚙️ Hesap Ayarları';
            ?>
          </div>
          <div class="topbar-sub">Hoş geldiniz, <?= htmlspecialchars($user['display_name']) ?></div>
        </div>
        <?php if ($activeTab !== 'admin' && $activeTab !== 'settings' && $activeTab !== 'shares'): ?>
        <div class="search-wrap">
          <svg class="search-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
          <input type="text" class="search-input" id="file-search" placeholder="Dosya adıyla filtrele..." oninput="filterFiles(this.value)">
        </div>
        <?php endif; ?>
      </div>
      <div class="topbar-actions">
        <div class="bell-wrap">
          <div class="bell-btn" id="bell-btn" onclick="toggleBellDropdown()">
            🔔
            <?php if ($notifCount > 0): ?>
              <span class="bell-badge"><?= $notifCount ?></span>
            <?php endif; ?>
          </div>
          <div class="bell-dropdown" id="bell-dropdown">
            <div class="bd-header">🔔 Bildirimler</div>
            <?php if (empty($notifications)): ?>
              <div class="bd-empty">Bildirim bulunmuyor</div>
            <?php else: ?>
              <?php foreach ($notifications as $n): ?>
              <div class="bd-item">
                <span class="bd-item-icon"><?= $n['type'] === 'lockout' ? '🔒' : '🔴' ?></span>
                <div class="bd-item-body">
                  <div class="bd-item-msg"><?= htmlspecialchars($n['message']) ?></div>
                  <div class="bd-item-time"><?= timeAgo($n['time']) ?></div>
                </div>
              </div>
              <?php endforeach; ?>
            <?php endif; ?>
            <div class="bd-footer">
              <a href="?tab=settings" class="bd-link">⚙️ Hesap Ayarları →</a>
            </div>
          </div>
        </div>
        <div class="profile-wrap">
          <div class="profile-btn" id="profile-btn" onclick="toggleProfileDropdown()">
            <?= strtoupper(substr($user['display_name'], 0, 1)) ?>
          </div>
          <div class="profile-dropdown" id="profile-dropdown">
            <div class="dropdown-header">
              <div class="dh-name"><?= htmlspecialchars($user['display_name']) ?></div>
              <div class="dh-email"><?= htmlspecialchars($user['username']) ?></div>
            </div>
            <a href="?tab=settings" class="dropdown-item">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="12" cy="12" r="3"/>
                <path d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-4 0v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 010-4h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 012.83-2.83l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 014 0v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 010 4h-.09a1.65 1.65 0 00-1.51 1z"/>
              </svg>
              Hesap Ayarları
            </a>
            <div class="dropdown-divider"></div>
            <a href="logout.php" class="dropdown-item" style="color:var(--danger)">
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
              </svg>
              Çıkış Yap
            </a>
          </div>
        </div>
      </div>
    </div>

    <div class="content">
      <!-- ⬇ HER TAB'DE GÖRÜNEN YÜKLEME ALANI ⬇ -->
      <form method="post" enctype="multipart/form-data" id="upload-form" style="display:<?= $activeTab === 'common' ? 'block' : 'none' ?>">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="upload_common">
        <input type="file" id="file-input" name="files[]" style="display:none" multiple onchange="submitUpload()">
        <div class="upload-area" id="upload-area" onclick="document.getElementById('file-input').click()">
          <div class="ua-icon">☁️</div>
          <div class="ua-title">Dosya yüklemek için tıklayın veya sürükleyin</div>
          <div class="ua-sub">500 MB'a kadar · Otomatik 5 günde silinir</div>
          <div class="ua-file" id="ua-filename"></div>
        </div>
      </form>
      <form method="post" enctype="multipart/form-data" id="upload-form-private" style="display:<?= $activeTab === 'private' ? 'block' : 'none' ?>">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="upload_private">
        <input type="file" id="file-input-private" name="files[]" style="display:none" multiple onchange="submitPrivateUpload()">
        <div class="upload-area" id="upload-area-private" onclick="document.getElementById('file-input-private').click()">
          <div class="ua-icon">🔒</div>
          <div class="ua-title">Özel alanınıza dosya yükleyin</div>
          <div class="ua-sub">500 MB'a kadar · Otomatik 5 günde silinir</div>
          <div class="ua-file" id="ua-filename-private"></div>
        </div>
      </form>

      <!-- SEKMELER -->
      <div id="tab-common" style="display:<?= $activeTab === 'common' ? 'block' : 'none' ?>">
      <div class="section-header">
        <div>
          <span class="section-title">Ortak Dosyalar</span>
          <span class="section-count"><?= count($commonFiles) ?> dosya</span>
        </div>
        <div class="view-toggle">
          <button class="view-btn" data-view="grid" title="Kart Görünümü" onclick="setView('grid')">▦</button>
          <button class="view-btn" data-view="compact" title="Küçük Kart" onclick="setView('compact')">▤</button>
          <button class="view-btn" data-view="list" title="Liste" onclick="setView('list')">☰</button>
        </div>
      </div>

      <?php if (empty($commonFiles)): ?>
        <div class="empty-state">
          <div class="es-icon">📂</div>
          <div class="es-title">Henüz dosya yok</div>
          <div class="es-sub">İlk dosyayı yüklemek için yukarıdaki alanı kullanın.</div>
        </div>
      <?php else: ?>
        <div class="files-grid" id="files-grid">
          <?php foreach ($commonFiles as $f):
            $ver = (int)($f['version'] ?? 1);
            $uploaderName = !empty($f['owner_id']) ? (getUserById($f['owner_id'])['display_name'] ?? getUserById($f['owner_id'])['username'] ?? '') : '';
          ?>
          <div class="file-card-wrap" data-file-id="<?= $f['id'] ?>">
            <input type="checkbox" class="file-checkbox" data-file-id="<?= $f['id'] ?>" onchange="updateBatchBar()">
            <div class="file-card" onclick="openPreview('<?= $f['id'] ?>')">
              <span class="file-icon"><?= getMimeIcon($f['mime'], $f['ext']) ?></span>
              <div class="file-name-wrap">
                <div class="file-name" title="<?= htmlspecialchars($f['original_name']) ?>"><?= htmlspecialchars($f['original_name']) ?></div>
                <?php if ($ver > 1): ?>
                  <span class="version-badge-sm">v<?= $ver ?></span>
                <?php endif; ?>
              </div>
              <div class="file-meta">
                <?= formatBytes((int)$f['size']) ?><br>
                <?php if ($uploaderName): ?>
                  <span style="color:var(--text-dim)">👤 <?= htmlspecialchars($uploaderName) ?></span><br>
                <?php endif; ?>
                <span class="file-expire">⏳ <?= formatExpire($f) ?> kaldı</span>
              </div>
              <div class="file-actions" onclick="event.stopPropagation()">
                <button class="btn btn-ghost btn-sm" onclick="openPreview('<?= $f['id'] ?>')">👁 Görüntüle</button>
                <button class="btn btn-ghost btn-sm" onclick="openRename('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">✏️</button>
                <button class="btn btn-ghost btn-sm" onclick="openShare('<?= $f['id'] ?>')">🔗</button>
                <button class="btn btn-danger btn-sm" onclick="confirmDelete('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">🗑</button>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
      </div><!-- /tab-common -->

      <!-- GELEN KUTUSU -->
      <div id="tab-inbox" style="display:<?= $activeTab === 'inbox' ? 'block' : 'none' ?>">
      <div class="section-header">
        <div>
          <span class="section-title">Bana Gönderilen Dosyalar</span>
          <span class="section-count"><?= count($inboxFiles) ?> dosya</span>
        </div>
      </div>

      <?php if (empty($inboxFiles)): ?>
        <div class="empty-state">
          <div class="es-icon">📬</div>
          <div class="es-title">Gelen kutunuz boş</div>
          <div class="es-sub">
            Birileri size dosya gönderdiğinde burada görünür.<br>
            Gönderim adresi: <strong><?= htmlspecialchars($user['username']) ?></strong>
          </div>
        </div>
      <?php else: ?>
        <div class="files-grid">
          <?php foreach ($inboxFiles as $f):
            $ver = (int)($f['version'] ?? 1);
          ?>
          <div class="file-card-wrap" data-file-id="<?= $f['id'] ?>">
            <input type="checkbox" class="file-checkbox" data-file-id="<?= $f['id'] ?>" onchange="updateBatchBar()">
            <div class="file-card" onclick="openPreview('<?= $f['id'] ?>')">
              <div class="inbox-tag">Gelen</div>
              <span class="file-icon"><?= getMimeIcon($f['mime'], $f['ext']) ?></span>
              <div class="file-name-wrap">
                <div class="file-name" title="<?= htmlspecialchars($f['original_name']) ?>"><?= htmlspecialchars($f['original_name']) ?></div>
                <?php if ($ver > 1): ?>
                  <span class="version-badge-sm">v<?= $ver ?></span>
                <?php endif; ?>
              </div>
              <div class="file-meta">
                <?= formatBytes((int)$f['size']) ?><br>
                <?php if ($f['sender_email']): ?>
                  Gönderen: <?= htmlspecialchars($f['sender_email']) ?><br>
                <?php endif; ?>
                <span class="file-expire">⏳ <?= formatExpire($f) ?> kaldı</span>
              </div>
              <div class="file-actions" onclick="event.stopPropagation()">
                <button class="btn btn-ghost btn-sm" onclick="openPreview('<?= $f['id'] ?>')">👁 Görüntüle</button>
                <button class="btn btn-ghost btn-sm" onclick="openRename('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">✏️</button>
                <button class="btn btn-ghost btn-sm" onclick="openShare('<?= $f['id'] ?>')">🔗</button>
                <button class="btn btn-danger btn-sm" onclick="confirmDelete('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">🗑</button>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
      </div><!-- /tab-inbox -->

      <!-- ÖZEL ALAN -->
      <div id="tab-private" style="display:<?= $activeTab === 'private' ? 'block' : 'none' ?>">

      <?php
        $allPrivateItems = array_merge(
          array_map(fn($f) => $f + ['_is_incoming' => false], $privateFiles),
          array_map(fn($f) => $f + ['_is_incoming' => true], $inboxFiles)
        );
        usort($allPrivateItems, fn($a, $b) => strtotime($b['uploaded_at']) - strtotime($a['uploaded_at']));
      ?>
      <div class="section-header">
        <div>
          <span class="section-title">Özel Dosyalarım</span>
          <span class="section-count"><?= count($allPrivateItems) ?> dosya</span>
        </div>
        <div class="view-toggle">
          <button class="view-btn" data-view="grid" title="Kart Görünümü" onclick="setView('grid')">▦</button>
          <button class="view-btn" data-view="compact" title="Küçük Kart" onclick="setView('compact')">▤</button>
          <button class="view-btn" data-view="list" title="Liste" onclick="setView('list')">☰</button>
        </div>
      </div>

      <?php if (empty($allPrivateItems)): ?>
        <div class="empty-state">
          <div class="es-icon">🔒</div>
          <div class="es-title">Henüz özel dosyanız yok</div>
          <div class="es-sub">Yukarıdaki alanı kullanarak özel dosyalarınızı yükleyin.</div>
        </div>
      <?php else: ?>
        <div class="files-grid">
          <?php foreach ($allPrivateItems as $f):
            $ver = (int)($f['version'] ?? 1);
            $isIncoming = $f['_is_incoming'];
          ?>
          <div class="file-card-wrap" data-file-id="<?= $f['id'] ?>">
            <input type="checkbox" class="file-checkbox" data-file-id="<?= $f['id'] ?>" onchange="updateBatchBar()">
            <div class="file-card" onclick="openPreview('<?= $f['id'] ?>')">
              <?php if ($isIncoming): ?>
                <div class="remote-tag">🌐 Uzaktan Geldi</div>
              <?php endif; ?>
              <span class="file-icon"><?= getMimeIcon($f['mime'], $f['ext']) ?></span>
              <div class="file-name-wrap">
                <div class="file-name" title="<?= htmlspecialchars($f['original_name']) ?>"><?= htmlspecialchars($f['original_name']) ?></div>
                <?php if ($ver > 1): ?>
                  <span class="version-badge-sm">v<?= $ver ?></span>
                <?php endif; ?>
              </div>
              <div class="file-meta">
                <?= formatBytes((int)$f['size']) ?><br>
                <?php if ($isIncoming && $f['sender_email']): ?>
                  <span style="color:var(--text-dim)">📨 <?= htmlspecialchars($f['sender_email']) ?></span><br>
                <?php endif; ?>
                <span class="file-expire">⏳ <?= formatExpire($f) ?> kaldı</span>
              </div>
              <div class="file-actions" onclick="event.stopPropagation()">
                <button class="btn btn-ghost btn-sm" onclick="openPreview('<?= $f['id'] ?>')">👁 Görüntüle</button>
                <button class="btn btn-ghost btn-sm" onclick="openRename('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">✏️</button>
                <button class="btn btn-ghost btn-sm" onclick="openShare('<?= $f['id'] ?>')">🔗</button>
                <button class="btn btn-danger btn-sm" onclick="confirmDelete('<?= $f['id'] ?>', '<?= htmlspecialchars(addslashes($f['original_name'])) ?>')">🗑</button>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
      </div><!-- /tab-private -->

      <!-- PAYLAŞILANLAR -->
      <div id="tab-shares" style="display:<?= $activeTab === 'shares' ? 'block' : 'none' ?>">
      <?php
      $userShares = getSharesByUser($user['id']);
      ?>
      <div style="max-width: 700px;">
        <?php if (empty($userShares)): ?>
          <div class="empty-state">
            <div class="es-icon">🔗</div>
            <div class="es-title">Henüz paylaşımınız yok</div>
            <div class="es-sub">Bir dosyanın üzerindeki 🔗 butonuna tıklayarak paylaşım kodu oluşturabilirsiniz.</div>
          </div>
        <?php else: ?>
          <div style="display:flex;flex-direction:column;gap:10px;">
            <?php foreach ($userShares as $s):
              $sfile = getFileById($s['file_id']);
              $accessLogs = getShareAccessLogs($s['code'], 10);
              $isExceeded = isShareAccessExceeded($s);
            ?>
            <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:18px 20px;">
              <div style="display:flex;align-items:center;gap:12px;margin-bottom:10px;">
                <span style="font-size:24px;"><?= $sfile ? getMimeIcon($sfile['mime'], $sfile['ext']) : '❓' ?></span>
                <div style="flex:1;min-width:0;">
                  <div style="font-size:14px;font-weight:600;"><?= $sfile ? htmlspecialchars($sfile['original_name']) : 'Dosya silinmiş' ?></div>
                  <div style="font-size:11px;color:var(--text-dim);font-family:monospace;letter-spacing:2px;"><?= $s['code'] ?></div>
                </div>
                <form method="post" onsubmit="return confirm('Paylaşım kaldırılsın mı?')">
                  <?= csrfField() ?>
                  <input type="hidden" name="action" value="delete_share">
                  <input type="hidden" name="share_code" value="<?= $s['code'] ?>">
                  <button type="submit" class="btn btn-danger btn-sm">🗑 Kaldır</button>
                </form>
              </div>
              <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:8px;font-size:11px;margin-bottom:10px;padding:10px;background:var(--surface);border-radius:8px;">
                <div><span style="color:var(--text-dim);">Oluşturma:</span><br><?= date('d.m.Y H:i', strtotime($s['created_at'])) ?></div>
                <div><span style="color:var(--text-dim);">Bitiş:</span><br><span style="color:<?= isShareExpired($s) ? 'var(--danger)' : 'var(--warn)' ?>"><?= isShareExpired($s) ? 'Süresi doldu' : date('d.m.Y H:i', strtotime($s['expires_at'])) ?></span></div>
                <div><span style="color:var(--text-dim);">Erişim:</span><br><?= $s['access_count'] ?? 0 ?><?= ($s['max_access_count'] ?? 0) > 0 ? ' / ' . $s['max_access_count'] : '' ?></div>
                <div><span style="color:var(--text-dim);">Durum:</span><br>
                  <?php if (isShareExpired($s)): ?><span style="color:var(--danger);font-weight:600;">Süresi Doldu</span>
                  <?php elseif ($isExceeded): ?><span style="color:var(--warn);font-weight:600;">Limite Ulaştı</span>
                  <?php else: ?><span style="color:var(--success);font-weight:600;">Aktif</span>
                  <?php endif; ?>
                </div>
              </div>
              <?php if (!empty($accessLogs)): ?>
              <div>
                <div style="font-size:11px;color:var(--text-dim);margin-bottom:6px;font-weight:600;">📋 Son Erişimler</div>
                <div style="font-size:11px;">
                  <?php foreach ($accessLogs as $log): ?>
                  <div style="display:flex;gap:10px;padding:4px 8px;background:var(--surface);border-radius:4px;margin-bottom:3px;">
                    <span style="font-family:monospace;color:var(--text-muted);"><?= htmlspecialchars($log['ip']) ?></span>
                    <span style="color:var(--text-dim);"><?= date('d.m.Y H:i', $log['time']) ?></span>
                    <span style="color:var(--text-dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;"><?= htmlspecialchars($log['user_agent'] ?? '') ?></span>
                  </div>
                  <?php endforeach; ?>
                </div>
              </div>
              <?php endif; ?>
            </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
      </div><!-- /tab-shares -->

      <!-- ADMIN PANEL -->
      <div id="tab-admin" style="display:<?= ($activeTab === 'admin' && $isAdmin) ? 'block' : 'none' ?>">
      <div style="display:flex;gap:0;flex:1;min-height:0;">
        <!-- Admin alt panel -->
        <div style="width:200px;min-width:200px;background:var(--surface);border-right:1px solid var(--border);border-radius:10px;overflow:hidden;align-self:flex-start;">
          <div style="padding:14px 14px 8px;font-size:11px;font-weight:600;color:var(--text-dim);text-transform:uppercase;letter-spacing:0.5px;">Admin</div>
          <a href="?tab=admin&sub=users" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'users' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2"/><circle cx="9" cy="7" r="4"/></svg>
            Kullanıcı Ayarları
          </a>
          <a href="?tab=admin&sub=storage" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'storage' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="2" width="20" height="8" rx="2" ry="2"/><rect x="2" y="14" width="20" height="8" rx="2" ry="2"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>
            Sistem Depolaması
          </a>
          <a href="?tab=admin&sub=logs" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'logs' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
            Giriş Logları
          </a>
          <a href="?tab=admin&sub=system_logs" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'system_logs' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
            Sistem Logları
          </a>
          <a href="?tab=admin&sub=shares" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'shares' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
            Paylaşımlar
          </a>
          <a href="?tab=admin&sub=extensions" style="display:flex;align-items:center;gap:8px;padding:10px 14px;font-size:13px;text-decoration:none;<?= $adminSubTab === 'extensions' ? 'background:var(--accent-glow);color:var(--accent);font-weight:600;' : 'color:var(--text-muted);' ?>">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
            Dosya Uzantıları
          </a>
        </div>

        <!-- Admin içerik -->
        <div style="flex:1;padding-left:24px;overflow-y:auto;">

        <?php if ($adminSubTab === 'users'): ?>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
          <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Yeni Kullanıcı</h3>
            <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Depolama limitini belirleyin</p>
            <form method="post">
              <?= csrfField() ?>
              <input type="hidden" name="action" value="create_user">
              <div class="form-group">
                <label>E-posta</label>
                <input type="email" class="form-input" name="username" required placeholder="ornek@data.com">
              </div>
              <div class="form-group">
                <label>Şifre</label>
                <input type="password" class="form-input" name="password" required minlength="4">
              </div>
              <div class="form-group">
                <label>Görünen Ad</label>
                <input type="text" class="form-input" name="display_name" placeholder="Varsayılan: e-posta adı">
              </div>
              <div class="form-group">
                <label>Depolama Limiti</label>
                <select class="form-input" name="storage_limit">
                  <option value="100">100 MB</option>
                  <option value="250">250 MB</option>
                  <option value="500" selected>500 MB</option>
                  <option value="750">750 MB</option>
                  <option value="1024">1 GB</option>
                  <option value="1536">1.5 GB</option>
                  <option value="2048">2 GB</option>
                </select>
              </div>
              <button type="submit" class="btn btn-primary">Oluştur</button>
            </form>
            <div style="margin-top:14px;font-size:11px;color:var(--text-muted);">Havuz: <?= formatBytes($poolAssigned) ?> / <?= formatBytes($poolTotal) ?> kullanıldı · <?= formatBytes($poolRemaining) ?> boş</div>
          </div>

          <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Depolama Havuzu</h3>
            <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Kullanıcılara dağıtılan toplam alan (5 GB)</p>
            <div style="height:12px;background:var(--surface3);border-radius:6px;overflow:hidden;margin-bottom:8px;">
              <div style="height:100%;width:<?= $poolTotal > 0 ? min(100, $poolAssigned / $poolTotal * 100) : 0 ?>%;background:var(--accent);border-radius:6px;transition:width 0.3s;"></div>
            </div>
            <div style="display:flex;justify-content:space-between;font-size:12px;">
              <span style="color:var(--text-muted)">Kullanılan: <?= formatBytes($poolAssigned) ?></span>
              <span style="color:var(--text-muted)">Boş: <?= formatBytes($poolRemaining) ?></span>
            </div>
          </div>
        </div>

        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;margin-top:20px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Kullanıcılar</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Tüm kayıtlı hesaplar</p>
          <?php $allUsers = getUsers(); ?>
          <?php if (empty($allUsers)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Hiç kullanıcı yok.</div>
          <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:8px;">
              <?php foreach ($allUsers as $u):
                $uStorageUsed = getUserStorageUsed($u['id']);
                $uStorageLimit = (int)($u['storage_limit'] ?? 0);
                $uPercent = $uStorageLimit > 0 ? round($uStorageUsed / $uStorageLimit * 100, 1) : 0;
                $isActive = $u['active'] ?? true;
              ?>
              <div style="background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:12px 16px;">
                <div style="display:flex;align-items:center;gap:12px;">
                  <div style="width:34px;height:34px;border-radius:50%;background:<?= $isActive ? 'var(--accent-glow)' : 'var(--surface3)' ?>;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:<?= $isActive ? 'var(--accent)' : 'var(--text-dim)' ?>;flex-shrink:0;"><?= strtoupper(substr($u['display_name'], 0, 1)) ?></div>
                  <div style="flex:1;min-width:0;">
                    <div style="font-size:13px;font-weight:600;color:var(--text);display:flex;align-items:center;gap:6px;">
                      <?= htmlspecialchars($u['display_name']) ?>
                      <?php if (($u['role'] ?? 'user') === 'admin'): ?>
                        <span style="font-size:10px;background:var(--accent-glow);color:var(--accent);padding:1px 6px;border-radius:4px;font-weight:600;">Admin</span>
                      <?php endif; ?>
                      <?php if (!$isActive): ?>
                        <span style="font-size:10px;background:#fef2f2;color:var(--danger);padding:1px 6px;border-radius:4px;font-weight:600;">Pasif</span>
                      <?php endif; ?>
                    </div>
                    <div style="font-size:11px;color:var(--text-muted);"><?= htmlspecialchars($u['username']) ?></div>
                  </div>
                  <div style="display:flex;gap:6px;flex-wrap:wrap;">
                    <button class="btn btn-ghost btn-sm" onclick="openUserModal('detail','<?= $u['id'] ?>','<?= htmlspecialchars(addslashes($u['display_name'])) ?>','<?= $uStorageUsed ?>','<?= $uStorageLimit ?>','<?= htmlspecialchars(addslashes($u['created_at'] ?? '')) ?>','<?= htmlspecialchars(addslashes($u['last_login'] ?? '')) ?>',<?= $uPercent ?>)">Detay</button>
                    <?php if ($u['id'] !== $user['id']): ?>
                    <button class="btn btn-ghost btn-sm" onclick="openUserModal('password','<?= $u['id'] ?>')">Şifre Yenile</button>
                    <button class="btn btn-ghost btn-sm" onclick="openUserModal('limit','<?= $u['id'] ?>','','<?= $uStorageLimit ?>')">Limiti Güncelle</button>
                    <button class="btn btn-danger btn-sm" onclick="openUserModal('delete','<?= $u['id'] ?>','<?= htmlspecialchars(addslashes($u['display_name'])) ?>')">Hesabı Kaldır</button>
                    <?php endif; ?>
                  </div>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>

        <?php elseif ($adminSubTab === 'storage'): ?>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
          <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Toplam Depolama</h3>
            <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Sistemdeki toplam 10 GB alan dağılımı</p>
            <div style="height:20px;background:var(--surface3);border-radius:10px;overflow:hidden;display:flex;margin-bottom:12px;">
              <div style="height:100%;width:<?= min(100, $commonUsed / TOTAL_STORAGE * 100) ?>%;background:var(--accent);border-radius:10px 0 0 10px;transition:width 0.3s;"></div>
              <div style="height:100%;width:<?= min(100, $poolAssigned / TOTAL_STORAGE * 100) ?>%;background:var(--success);transition:width 0.3s;"></div>
            </div>
            <div style="display:flex;flex-direction:column;gap:6px;font-size:12px;">
              <div style="display:flex;justify-content:space-between;">
                <span><span style="color:var(--accent);font-weight:700;">■</span> Ortak Alan (5 GB)</span>
                <span><?= formatBytes($commonUsed) ?> / <?= formatBytes(MAX_STORAGE) ?></span>
              </div>
              <div style="display:flex;justify-content:space-between;">
                <span><span style="color:var(--success);font-weight:700;">■</span> Kullanıcı Havuzu (5 GB)</span>
                <span><?= formatBytes($poolAssigned) ?> / <?= formatBytes($poolTotal) ?></span>
              </div>
              <div style="display:flex;justify-content:space-between;font-weight:600;border-top:1px solid var(--border);padding-top:6px;">
                <span>Toplam</span>
                <span><?= formatBytes($commonUsed + $poolAssigned) ?> / <?= formatBytes(TOTAL_STORAGE) ?></span>
              </div>
            </div>
          </div>

          <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
            <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Kullanıcı Bazında Depolama</h3>
            <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Her kullanıcının limit ve kullanım durumu</p>
            <div style="display:flex;flex-direction:column;gap:10px;">
              <?php foreach (getUsers() as $u):
                $uUsed = getUserStorageUsed($u['id']);
                $uLimit = (int)($u['storage_limit'] ?? 0);
                $uPct = $uLimit > 0 ? round($uUsed / $uLimit * 100, 1) : 0;
              ?>
              <div>
                <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:3px;">
                  <span style="font-weight:600;color:var(--text)"><?= htmlspecialchars($u['display_name']) ?></span>
                  <span style="color:var(--text-muted)"><?= formatBytes($uUsed) ?> / <?= formatBytes($uLimit) ?></span>
                </div>
                <div style="height:6px;background:var(--surface3);border-radius:3px;overflow:hidden;">
                  <div style="height:100%;width:<?= min(100, $uPct) ?>%;background:<?= $uPct > 85 ? 'var(--danger)' : ($uPct > 60 ? 'var(--warn)' : 'var(--accent)') ?>;border-radius:3px;"></div>
                </div>
              </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>

        <!-- Birleşik depolama barı -->
        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;margin-top:20px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Sistem Depolama Dağılımı</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Kullanıcı havuzu ve ortak alanın gerçek kullanım oranları</p>
          <?php
            $poolTotalBytes = POOL_STORAGE;
            $poolAssignPct = $poolTotalBytes > 0 ? min(100, round($poolAssigned / $poolTotalBytes * 100, 1)) : 0;
            $poolPrivatePct = $poolTotalBytes > 0 ? min(100, round($poolPrivate / $poolTotalBytes * 100, 1)) : 0;
            $commonPct = MAX_STORAGE > 0 ? min(100, round($commonUsed / MAX_STORAGE * 100, 1)) : 0;
          ?>
          <div style="display:flex;height:44px;border-radius:10px;overflow:hidden;margin-bottom:14px;">
            <div style="flex:1;background:rgba(134,239,172,0.2);position:relative;border-right:2px solid var(--surface2);">
              <div style="position:absolute;left:0;top:0;height:100%;width:<?= $poolAssignPct ?>%;background:#22c55e;border-radius:0;transition:width 0.5s;"></div>
              <div style="position:absolute;left:0;top:0;height:100%;width:<?= $poolPrivatePct ?>%;background:#166534;border-radius:0;transition:width 0.5s;"></div>
              <div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#000;">
                Kullanıcı Havuzu
              </div>
            </div>
            <div style="flex:1;background:rgba(147,197,253,0.2);position:relative;display:flex;justify-content:flex-end;">
              <div style="height:100%;width:<?= $commonPct ?>%;background:#3b82f6;border-radius:0;transition:width 0.5s;"></div>
              <div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#000;">
                Ortak Alan
              </div>
            </div>
          </div>
          <div style="display:flex;gap:20px;font-size:12px;flex-wrap:wrap;">
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#bbf7d0;"></span>
              <span style="color:var(--text-muted);">Havuza ayrılan: <strong style="color:var(--text);"><?= formatBytes($poolTotalBytes) ?></strong></span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#22c55e;"></span>
              <span style="color:var(--text-muted);">Kullanıcılara atanan: <strong style="color:var(--text);"><?= formatBytes($poolAssigned) ?> (%<?= $poolAssignPct ?>)</strong></span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#166534;"></span>
              <span style="color:var(--text-muted);">Özel alan (kullanıcı dosyaları): <strong style="color:var(--text);"><?= formatBytes($poolPrivate) ?> (%<?= $poolPrivatePct ?>)</strong></span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#bbf7d0;"></span>
              <span style="color:var(--text-muted);">Kullanılmayan: <strong style="color:var(--text);"><?= formatBytes($poolTotalBytes - $poolAssigned) ?></strong></span>
            </div>
            <div style="display:flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#bfdbfe;"></span>
              <span style="color:var(--text-muted);">Ortak alan: <strong style="color:var(--text);"><?= formatBytes(MAX_STORAGE) ?></strong></span>
            </div>
            <div style="display:inline-flex;align-items:center;gap:8px;">
              <span style="display:inline-block;width:14px;height:14px;border-radius:3px;background:#3b82f6;"></span>
              <span style="color:var(--text-muted);">Ortak alanda kullanılan: <strong style="color:var(--text);"><?= formatBytes($commonUsed) ?> (%<?= $commonPct ?>)</strong></span>
            </div>
          </div>
        </div>

        <?php elseif ($adminSubTab === 'logs'): ?>

        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Giriş Logları</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Tüm başarılı ve başarısız giriş denemeleri</p>
          <?php if (empty($allLogs)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Henüz giriş kaydı bulunmuyor.</div>
          <?php else: ?>
            <div style="overflow-x:auto;">
              <table style="width:100%;font-size:12px;border-collapse:collapse;">
                <thead>
                  <tr style="border-bottom:2px solid var(--border);">
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Zaman</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Kullanıcı</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">IP</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Durum</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Not</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($allLogs as $l): ?>
                  <tr style="border-bottom:1px solid var(--border);">
                    <td style="padding:8px 10px;white-space:nowrap;"><?= date('d.m.Y H:i', $l['time']) ?></td>
                    <td style="padding:8px 10px;"><?= htmlspecialchars($l['username']) ?></td>
                    <td style="padding:8px 10px;font-family:monospace;font-size:11px;"><?= htmlspecialchars($l['ip']) ?></td>
                    <td style="padding:8px 10px;">
                      <?php if ($l['status'] === 'success'): ?>
                        <span style="color:var(--success);font-weight:600;">✓ Başarılı</span>
                      <?php else: ?>
                        <span style="color:var(--danger);font-weight:600;">✗ Başarısız</span>
                      <?php endif; ?>
                    </td>
                    <td style="padding:8px 10px;font-size:11px;">
                      <?php if ($l['lockout']): ?>
                        <span style="color:var(--warn);font-weight:600;">🔒 Kilitlendi (Seviye <?= $l['lockout_level'] ?>)</span>
                      <?php else: ?>
                        <span style="color:var(--text-dim);">-</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>

        <?php elseif ($adminSubTab === 'system_logs'): ?>

        <?php
        $typeLabels = [
            'login'            => ['Giriş', 'var(--success)'],
            'login_failed'     => ['Başarısız Giriş', 'var(--danger)'],
            'logout'           => ['Çıkış', 'var(--text-muted)'],
            'login_request'    => ['Onay İsteği', '#2979ff'],
            'login_approved'   => ['Onaylandı', 'var(--success)'],
            'login_rejected'   => ['Reddedildi', 'var(--danger)'],
            'ratelimit'        => ['Rate Limit', 'var(--warn)'],
            'file_upload'      => ['Dosya Yükleme', 'var(--success)'],
            'file_delete'      => ['Dosya Silme', 'var(--danger)'],
            'file_rename'      => ['Dosya Adı Değişikliği', '#ff9800'],
            'download'         => ['İndirme', '#2979ff'],
            'share_create'     => ['Paylaşım Oluşturma', 'var(--success)'],
            'share_delete'     => ['Paylaşım Kaldırma', 'var(--danger)'],
            'password_change'  => ['Şifre Değişikliği', '#ff9800'],
            'password_reset'   => ['Şifre Sıfırlama', '#ff9800'],
            'user_create'      => ['Kullanıcı Oluşturma', 'var(--success)'],
            'user_delete'      => ['Kullanıcı Silme', 'var(--danger)'],
            'user_toggle'      => ['Kullanıcı Durumu', '#ff9800'],
            'storage_change'   => ['Depolama Limit Değişikliği', '#ff9800'],
            'extensions_update'=> ['Uzantı Ayarları', '#ff9800'],
            'batch_delete'     => ['Toplu Silme', 'var(--danger)'],
        ];
        ?>

        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Sistem Logları</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Tüm sistem olay kayıtları (giriş/çıkış, dosya işlemleri, paylaşımlar, yönetici işlemleri)</p>
          <?php if (empty($systemLogs)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Henüz sistem kaydı bulunmuyor.</div>
          <?php else: ?>
            <div style="overflow-x:auto;">
              <table style="width:100%;font-size:12px;border-collapse:collapse;">
                <thead>
                  <tr style="border-bottom:2px solid var(--border);">
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Zaman</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">İşlem</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">Açıklama</th>
                    <th style="padding:8px 10px;text-align:left;font-weight:600;color:var(--text-muted);">IP</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($systemLogs as $l):
                    $label = $typeLabels[$l['type']] ?? [htmlspecialchars($l['type']), 'var(--text-dim)'];
                  ?>
                  <tr style="border-bottom:1px solid var(--border);">
                    <td style="padding:8px 10px;white-space:nowrap;"><?= date('d.m.Y H:i', $l['time']) ?></td>
                    <td style="padding:8px 10px;">
                      <span style="color:<?= $label[1] ?>;font-weight:600;"><?= $label[0] ?></span>
                    </td>
                    <td style="padding:8px 10px;max-width:400px;word-break:break-word;"><?= htmlspecialchars($l['message']) ?></td>
                    <td style="padding:8px 10px;font-family:monospace;font-size:11px;"><?= htmlspecialchars($l['ip']) ?></td>
                  </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>

        <?php elseif ($adminSubTab === 'shares'): ?>

        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:6px;">Tüm Paylaşımlar</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Kullanıcıların oluşturduğu paylaşım kodları</p>
          <?php
          $allShares = getAllSharesWithCreator();
          ?>
          <?php if (empty($allShares)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Henüz paylaşım yok.</div>
          <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:8px;">
              <?php foreach ($allShares as $s):
                $sfile = getFileById($s['file_id']);
              ?>
              <div style="display:flex;align-items:center;gap:12px;background:var(--surface);border:1px solid var(--border);border-radius:8px;padding:10px 14px;font-size:12px;">
                <span style="font-size:18px;"><?= $sfile ? getMimeIcon($sfile['mime'], $sfile['ext']) : '❓' ?></span>
                <div style="flex:1;min-width:0;">
                  <div style="font-weight:600;"><?= $sfile ? htmlspecialchars($sfile['original_name']) : 'Dosya silinmiş' ?></div>
                  <div style="color:var(--text-dim);font-size:11px;">
                    Oluşturan: <?= htmlspecialchars($s['creator_name']) ?> ·
                    Kod: <span style="font-family:monospace;letter-spacing:1px;"><?= $s['code'] ?></span> ·
                    <?= date('d.m.Y H:i', strtotime($s['created_at'])) ?>
                  </div>
                </div>
                <span style="font-size:11px;color:var(--text-dim);">
                  <?= $s['access_count'] ?? 0 ?> erişim
                  <?= ($s['max_access_count'] ?? 0) > 0 ? '/ ' . $s['max_access_count'] : '' ?>
                </span>
                <span>
                  <?php if (isShareExpired($s)): ?>
                    <span style="color:var(--danger);font-weight:600;">Süresi Doldu</span>
                  <?php else: ?>
                    <span style="color:var(--success);font-weight:600;">Aktif</span>
                  <?php endif; ?>
                </span>
              </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>

        <?php elseif ($adminSubTab === 'extensions'): ?>

        <?php
        $allowedExts = getAllowedExtensions();
        $allDefaultExts = getDefaultExtensions();
        $allCodeExts = getDefaultCodeExtensions();
        $codeStats = getCodeExtensionStats();

        ?>
        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;margin-bottom:20px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:4px;">İzin Verilen Dosya Uzantıları</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:6px;">
            Sadece işaretli uzantılar sisteme yüklenebilir. <span id="ext-count"><?= count($allowedExts) ?></span> uzantı aktif.
          </p>
          <div style="margin-bottom:16px;">
            <input type="text" id="ext-search" placeholder="Uzantı ara (örn: p, pd, exe) – eşleşen harfler sarı renkle vurgulanır" style="width:100%;padding:10px 14px;border-radius:8px;border:1px solid var(--border);background:var(--surface);color:var(--text);font-size:13px;outline:none;box-sizing:border-box;">
          </div>
          <form method="post" id="ext-form">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="save_extensions">
            <input type="hidden" name="extensions" id="ext-hidden" value="<?= implode(',', $allowedExts) ?>">
            <div style="font-size:13px;font-weight:600;color:var(--text-muted);margin-bottom:8px;padding:4px 0;border-bottom:1px solid var(--border);">Normal Uzantılar</div>
            <div id="ext-grid-normal" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:6px;margin-bottom:20px;">
              <?php foreach ($allDefaultExts as $ext): ?>
              <label style="display:flex;align-items:center;gap:6px;padding:5px 8px;background:var(--surface);border-radius:5px;font-size:12px;cursor:pointer;border:1px solid <?= in_array($ext, $allowedExts) ? 'var(--accent)' : 'var(--border)' ?>;transition:border-color 0.15s;" id="ext-label-<?= $ext ?>" data-ext="<?= $ext ?>">
                <input type="checkbox" class="ext-checkbox" value="<?= $ext ?>" <?= in_array($ext, $allowedExts) ? 'checked' : '' ?> onchange="toggleExt('<?= $ext ?>')" style="accent-color:var(--accent);">
                <span class="ext-text">.<?= $ext ?></span>
              </label>
              <?php endforeach; ?>
            </div>
            <div style="font-size:13px;font-weight:600;color:var(--text-muted);margin-bottom:8px;padding:4px 0;border-bottom:1px solid var(--border);">Kod Uzantıları (Zip'lenerek Kaydedilir)</div>
            <div id="ext-grid-code" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:6px;margin-bottom:20px;">
              <?php foreach ($allCodeExts as $ext): ?>
              <label style="display:flex;align-items:center;gap:6px;padding:5px 8px;background:var(--surface);border-radius:5px;font-size:12px;cursor:pointer;border:1px solid <?= in_array($ext, $allowedExts) ? 'var(--accent)' : 'var(--border)' ?>;transition:border-color 0.15s;" id="ext-label-<?= $ext ?>" data-ext="<?= $ext ?>">
                <input type="checkbox" class="ext-checkbox" value="<?= $ext ?>" <?= in_array($ext, $allowedExts) ? 'checked' : '' ?> onchange="toggleExt('<?= $ext ?>')" style="accent-color:var(--accent);">
                <span class="ext-text">.<?= $ext ?></span>
              </label>
              <?php endforeach; ?>
            </div>
            <div style="display:flex;align-items:center;gap:12px;">
              <button type="submit" class="btn btn-primary">💾 Kaydet</button>
              <button type="button" class="btn btn-ghost" onclick="selectAllExts(true)">Tümünü Seç</button>
              <button type="button" class="btn btn-ghost" onclick="selectAllExts(false)">Tümünü Kaldır</button>
            </div>
            <p style="font-size:12px;color:var(--warn);font-weight:600;margin-top:12px;display:none;" id="ext-unsaved-warning">
              ⚠ Değişiklikleri kaydetmezseniz geçersiz olur.
            </p>
          </form>
        </div>

        <div style="background:var(--surface2);border:1px solid var(--border);border-radius:12px;padding:24px;">
          <h3 style="font-size:15px;font-weight:700;margin-bottom:4px;">En Çok Kullanılan Kod Uzantıları</h3>
          <p style="font-size:12px;color:var(--text-muted);margin-bottom:18px;">Sisteme yüklenen kod dosyalarının uzantı istatistikleri</p>
          <?php if (empty($codeStats)): ?>
            <div style="font-size:13px;color:var(--text-muted);">Henüz kod dosyası yüklenmemiş.</div>
          <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:6px;max-width:500px;">
              <?php $rank = 0; ?>
              <?php foreach (array_slice($codeStats, 0, 20) as $codeExt => $count): $rank++; ?>
              <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:var(--surface);border-radius:8px;font-size:13px;">
                <span style="font-weight:700;color:var(--text-dim);min-width:24px;">#<?= $rank ?></span>
                <span style="font-weight:600;flex:1;font-family:monospace;">.<?= htmlspecialchars($codeExt) ?></span>
                <div style="height:20px;background:var(--accent-glow);border-radius:4px;flex:2;overflow:hidden;position:relative;">
                  <?php $firstCount = reset($codeStats); $pct = $firstCount > 0 ? round($count / $firstCount * 100) : 0; ?>
                  <div style="height:100%;width:<?= $pct ?>%;background:var(--accent);border-radius:4px;"></div>
                </div>
                <span style="color:var(--text-muted);font-size:12px;min-width:50px;text-align:right;"><?= $count ?> dosya</span>
              </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
        <script>
        function toggleExt(ext) {
          const cb = document.querySelector('.ext-checkbox[value="' + ext + '"]');
          const label = document.getElementById('ext-label-' + ext);
          if (cb.checked) {
            label.style.borderColor = 'var(--accent)';
          } else {
            label.style.borderColor = 'var(--border)';
          }
          updateExtHiddenInput();
          document.getElementById('ext-unsaved-warning').style.display = 'block';
        }
        function selectAllExts(select) {
          document.querySelectorAll('.ext-checkbox').forEach(cb => {
            cb.checked = select;
            const label = document.getElementById('ext-label-' + cb.value);
            if (label) label.style.borderColor = select ? 'var(--accent)' : 'var(--border)';
          });
          updateExtHiddenInput();
          document.getElementById('ext-unsaved-warning').style.display = 'block';
        }
        function updateExtHiddenInput() {
          const exts = [];
          document.querySelectorAll('.ext-checkbox:checked').forEach(cb => exts.push(cb.value));
          document.getElementById('ext-hidden').value = exts.join(',');
        }
        function highlightText(text, query) {
          if (!query) return text;
          const idx = text.toLowerCase().indexOf(query.toLowerCase());
          if (idx === -1) return text;
          return text.slice(0, idx) +
            '<mark style="background:transparent;color:#facc15;font-weight:700;padding:0;">' +
            text.slice(idx, idx + query.length) +
            '</mark>' +
            text.slice(idx + query.length);
        }
        function filterExtensions() {
          const q = document.getElementById('ext-search').value.trim();
          const labels = document.querySelectorAll('[data-ext]');
          let visibleCount = 0;
          labels.forEach(label => {
            const ext = label.getAttribute('data-ext');
            const textSpan = label.querySelector('.ext-text');
            if (!q) {
              label.style.display = '';
              textSpan.innerHTML = '.' + ext;
              visibleCount++;
            } else if (ext.toLowerCase().includes(q.toLowerCase())) {
              label.style.display = '';
              textSpan.innerHTML = highlightText('.' + ext, q);
              visibleCount++;
            } else {
              label.style.display = 'none';
            }
          });
          document.getElementById('ext-count').textContent = document.querySelectorAll('.ext-checkbox:checked').length;
        }
        document.addEventListener('DOMContentLoaded', function() {
          const searchInput = document.getElementById('ext-search');
          if (searchInput) {
            searchInput.addEventListener('input', filterExtensions);
          }
        });
        </script>

        <?php endif; ?>
        </div>
      </div>
      </div><!-- /tab-admin -->

      <!-- AYARLAR -->
      <div id="tab-settings" style="display:<?= $activeTab === 'settings' ? 'block' : 'none' ?>">
      <div style="max-width: 440px;">
        <div style="background: var(--surface2); border: 1px solid var(--border); border-radius: 12px; padding: 24px; margin-bottom: 20px;">
          <h3 style="font-size: 15px; font-weight: 700; margin-bottom: 6px;">Hesap Bilgileri</h3>
          <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 18px;">Mevcut hesap bilgileriniz</p>
          <div style="font-size: 13px; color: var(--text-muted); margin-bottom: 6px;">E-posta</div>
          <div style="font-size: 14px; font-weight: 600; color: var(--accent); margin-bottom: 4px;"><?= htmlspecialchars($user['username']) ?></div>
          <div style="font-size: 12px; color: var(--text-muted);">Özel Alan: <?= formatBytes($userStorageUsed) ?> / <?= formatBytes($userStorageLimit) ?></div>
        </div>

        <div style="background: var(--surface2); border: 1px solid var(--border); border-radius: 12px; padding: 24px;">
          <h3 style="font-size: 15px; font-weight: 700; margin-bottom: 6px;">Şifre Değiştir</h3>
          <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 18px;">Hesabınızın şifresini güncelleyin</p>
          <form method="post">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="change_password">
            <div class="form-group">
              <label>Mevcut Şifre</label>
              <div class="pw-group">
                <input type="password" class="form-input" name="old_password" id="old-pw" required>
                <button type="button" class="pw-eye-btn" onclick="toggleField('old-pw')">👁</button>
              </div>
            </div>
            <div class="form-group">
              <label>Yeni Şifre</label>
              <div class="pw-group">
                <input type="password" class="form-input" name="new_password" id="new-pw" required minlength="4">
                <button type="button" class="pw-eye-btn" onclick="toggleField('new-pw')">👁</button>
              </div>
            </div>
            <button type="submit" class="btn btn-primary">Şifreyi Güncelle</button>
          </form>
        </div>

        <div style="background: var(--surface2); border: 1px solid var(--border); border-radius: 12px; padding: 24px; margin-top: 20px;">
          <h3 style="font-size: 15px; font-weight: 700; margin-bottom: 6px;">Giriş Geçmişi</h3>
          <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 18px;">Son 10 giriş denemeniz</p>
          <?php if (empty($userLogs)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Henüz giriş kaydı bulunmuyor.</div>
          <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:6px;">
              <?php foreach ($userLogs as $l): ?>
              <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:var(--surface);border-radius:8px;font-size:12px;">
                <span><?= $l['status'] === 'success' ? '✅' : '❌' ?></span>
                <span style="flex:1;color:var(--text-muted);">
                  <?= $l['status'] === 'success' ? 'Başarılı giriş' : 'Başarısız giriş' ?>
                  <?php if ($l['lockout']): ?>
                    <span style="color:var(--warn);font-weight:600;"> (Kilitlendi)</span>
                  <?php endif; ?>
                </span>
                <span style="color:var(--text-dim);font-size:11px;"><?= date('d.m.Y H:i', $l['time']) ?></span>
              </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>

        <div style="background: var(--surface2); border: 1px solid var(--border); border-radius: 12px; padding: 24px; margin-top: 20px;">
          <h3 style="font-size: 15px; font-weight: 700; margin-bottom: 6px;">Yüklediğiniz Dosyalar</h3>
          <p style="font-size: 12px; color: var(--text-muted); margin-bottom: 18px;">Özel alanınıza yüklediğiniz dosyalar</p>
          <?php
          $myFiles = array_merge(getPrivateFiles($user['id']), getInboxFiles($user['id']));
          usort($myFiles, fn($a, $b) => strtotime($b['uploaded_at']) - strtotime($a['uploaded_at']));
          ?>
          <?php if (empty($myFiles)): ?>
            <div style="font-size:13px;color:var(--text-muted)">Henüz dosya yüklenmemiş.</div>
          <?php else: ?>
            <div style="display:flex;flex-direction:column;gap:6px;">
              <?php foreach (array_slice($myFiles, 0, 20) as $f): ?>
              <div style="display:flex;align-items:center;gap:10px;padding:8px 12px;background:var(--surface);border-radius:8px;font-size:12px;">
                <span><?= getMimeIcon($f['mime'], $f['ext']) ?></span>
                <span style="flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;"><?= htmlspecialchars($f['original_name']) ?></span>
                <span style="color:var(--text-dim);font-size:11px;"><?= formatBytes((int)$f['size']) ?></span>
                <span style="color:var(--text-dim);font-size:11px;"><?= date('d.m.Y H:i', strtotime($f['uploaded_at'])) ?></span>
              </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
      </div><!-- /tab-settings -->
    </div>
  </div>
</div>

<!-- Batch action bar -->
<div class="batch-bar" id="batch-bar">
  <span class="batch-count" id="batch-count">0 dosya seçildi</span>
  <button class="batch-btn" onclick="selectAllFiles()">Tümünü Seç</button>
  <button class="batch-btn" onclick="batchDownload()">ZIP Olarak İndir</button>
  <button class="batch-btn batch-btn-danger" onclick="batchDelete()">Seçilenleri Sil</button>
  <button class="batch-btn" style="background:transparent;border-color:transparent;" onclick="clearSelection()">İptal</button>
</div>

<!-- Toast bildirim -->
<div class="toast-container" id="toast-container"></div>

<!-- Yuvarlak ilerleme göstergesi -->
<div class="progress-wrap" id="progress-wrap" onclick="toggleDetail()">
  <div class="progress-row">
    <div class="progress-ring-wrap">
      <svg class="progress-ring" viewBox="0 0 44 44">
        <circle class="progress-ring-bg" cx="22" cy="22" r="19.5"/>
        <circle class="progress-ring-fill" id="progress-fill" cx="22" cy="22" r="19.5"
          stroke-dasharray="122.52" stroke-dashoffset="122.52"/>
      </svg>
      <span class="progress-pct" id="progress-pct">0%</span>
    </div>
    <span class="progress-label" id="progress-label">Dosya indiriliyor...</span>
  </div>
  <div class="progress-detail" id="progress-detail"></div>
</div>

<!-- PREVIEW MODAL -->
<div class="modal-overlay" id="preview-modal">
  <div class="modal modal-wide">
    <div class="modal-header">
      <div class="modal-header-text">
        <div class="modal-title" id="pm-title">Dosya Önizleme</div>
        <div class="modal-sub" id="pm-sub"></div>
      </div>
      <button class="modal-close" onclick="closeModal('preview-modal')">×</button>
    </div>
    <div class="modal-body">
      <div class="preview-split">
        <div class="preview-left">
          <div class="preview-container" id="pm-preview"></div>

          <div class="preview-actions" id="pm-actions">
            <button class="btn btn-ghost btn-sm" id="pm-share-btn" onclick="openShareFromModal()">🔗 Paylaş</button>
            <button class="btn btn-ghost btn-sm" id="pm-rename-btn" onclick="openRenameFromModal()">✏️ Yeniden Adlandır</button>
            <button class="btn btn-danger btn-sm" id="pm-delete-btn" onclick="deleteFromModal()">🗑 Sil</button>
          </div>

          <div class="version-list" id="pm-versions" style="display:none"></div>
        </div>

        <div class="preview-right">
          <div class="file-info-grid" id="pm-info"></div>

          <div class="preview-right-bottom">
            <div id="pm-dl-section">
              <div class="dl-section-title">İndirme</div>
              <a id="pm-download" href="#" class="btn btn-primary btn-sm btn-full">⬇ İndir</a>
              <div id="code-dl-options" style="display:none">
                <a id="pm-dl-zip" href="#" class="btn btn-primary btn-sm btn-full">📦 ZIP Olarak İndir</a>
                <a id="pm-dl-orig" href="#" class="btn btn-ghost btn-sm btn-full" style="margin-top:6px;">📄 Orijinal İndir</a>
              </div>
              <div id="pm-security-note" style="display:none" class="security-note">
                🔒 Güvenlik nedeniyle .zip olarak saklanmaktadır.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- RENAME MODAL -->
<div class="modal-overlay" id="rename-modal">
  <div class="modal" style="max-width: 380px;">
    <button class="modal-close" onclick="closeModal('rename-modal')">×</button>
    <div class="modal-title">Dosyayı Yeniden Adlandır</div>
    <div class="modal-sub">Yeni bir isim girin</div>
    <form method="post" id="rename-form">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="rename_file">
      <input type="hidden" name="file_id" id="rename-file-id">
      <div class="form-group">
        <label>Yeni Ad</label>
        <input type="text" class="form-input" name="new_name" id="rename-input" required>
      </div>
      <div style="display:flex; gap:8px;">
        <button type="submit" class="btn btn-primary btn-sm">Kaydet</button>
        <button type="button" class="btn btn-ghost btn-sm" onclick="closeModal('rename-modal')">İptal</button>
      </div>
    </form>
  </div>
</div>

<!-- DELETE MODAL -->
<div class="modal-overlay" id="delete-modal">
  <div class="modal" style="max-width: 360px;">
    <button class="modal-close" onclick="closeModal('delete-modal')">×</button>
    <div class="modal-title">Dosyayı Sil</div>
    <div class="modal-sub" id="delete-sub"></div>
    <form method="post" id="delete-form">
      <?= csrfField() ?>
      <input type="hidden" name="action" value="delete_file">
      <input type="hidden" name="file_id" id="delete-file-id">
      <div style="display:flex; gap:8px;">
        <button type="submit" class="btn btn-danger btn-sm">Evet, Sil</button>
        <button type="button" class="btn btn-ghost btn-sm" onclick="closeModal('delete-modal')">İptal</button>
      </div>
    </form>
  </div>
</div>

<!-- SHARE MODAL -->
<div class="modal-overlay" id="share-modal">
  <div class="modal" style="max-width: 380px;">
    <button class="modal-close" onclick="closeModal('share-modal')">×</button>
    <div class="modal-title">🔗 Paylaşım Kodu</div>
    <div class="modal-sub">Bu kodu paylaştığınız kişiler dosyaya erişebilir.</div>
    <div id="share-options" style="padding: 8px 0 12px;">
      <div class="form-group">
        <label>Maksimum Erişim (0 = sınırsız)</label>
        <input type="number" class="form-input" id="share-max-access" value="0" min="0" max="9999" style="font-size:13px;">
      </div>
      <div class="form-group">
        <label>Süre Limiti</label>
        <select class="form-input" id="share-hours-limit" style="font-size:13px;">
          <option value="0">Dosya silinene kadar</option>
          <option value="1">1 saat</option>
          <option value="3">3 saat</option>
          <option value="6">6 saat</option>
          <option value="12">12 saat</option>
          <option value="24">24 saat</option>
          <option value="48">48 saat</option>
          <option value="72">72 saat</option>
        </select>
      </div>
    </div>
    <div id="share-loading" style="text-align:center; padding: 20px; color: var(--text-muted);">Kod oluşturuluyor...</div>
    <div id="share-result" style="display:none">
      <div class="share-code-display">
        <div class="scd-label">Paylaşım Kodu</div>
        <div class="scd-code" id="share-code-text"></div>
        <div class="scd-expire" id="share-expire-text">Dosya süresine kadar geçerli</div>
      </div>
      <div style="margin-top: 12px; display: flex; gap: 8px;">
        <button class="btn btn-primary btn-sm" onclick="copyCode()">📋 Kodu Kopyala</button>
        <span id="copy-confirm" style="font-size:12px; color: var(--success); align-self:center; display:none">✓ Kopyalandı!</span>
      </div>
      <p style="font-size: 12px; color: var(--text-muted); margin-top: 12px; line-height: 1.6;">
        Alıcı giriş sayfasının sol panelinden "Kod ile Aç" sekmesine geçip bu kodu girebilir.
      </p>
    </div>
  </div>
</div>

<!-- KULLANICI MODAL -->
<div class="modal-overlay" id="user-modal">
  <div class="modal" style="max-width:420px;" id="user-modal-content">
    <button class="modal-close" onclick="closeModal('user-modal')">×</button>
    <div class="modal-title" id="um-title">Kullanıcı İşlemi</div>
    <div class="modal-sub" id="um-sub"></div>
    <div id="um-body"></div>
  </div>
</div>

<script>
function isExtAllowed(file) {
  const ext = file.name.split('.').pop().toLowerCase();
  if (!ext) return true;
  return ALLOWED_EXTENSIONS.includes(ext);
}

function showRejectedToast(filename) {
  showToast('🔒 "' + filename + '" dosya yolu güvenlik nedeniyle reddediliyor.', 'error');
}

// Upload sürükle bırak
function setupUpload(areaId, inputId, labelId, fn) {
  const area = document.getElementById(areaId);
  if (!area) return;
  area.addEventListener('dragover', e => { e.preventDefault(); area.classList.add('drag-over'); });
  area.addEventListener('dragleave', () => area.classList.remove('drag-over'));
  area.addEventListener('drop', e => {
    e.preventDefault();
    area.classList.remove('drag-over');
    const fi = document.getElementById(inputId);
    const files = e.dataTransfer.files;
    let blocked = false;
    for (const f of files) {
      if (!isExtAllowed(f)) {
        showRejectedToast(f.name);
        blocked = true;
      }
    }
    if (blocked) return;
    fi.files = files;
    if (fi.files.length > 0) {
      const el = document.getElementById(labelId);
      if (fi.files.length === 1) {
        el.textContent = '📎 ' + fi.files[0].name;
      } else {
        el.textContent = '📎 ' + fi.files.length + ' dosya seçildi';
      }
      fn();
    }
  });
}

setupUpload('upload-area', 'file-input', 'ua-filename', submitUpload);
setupUpload('upload-area-private', 'file-input-private', 'ua-filename-private', function() { submitUpload('private'); });

let currentXHR = null;
let isUploading = false;
var uploadQueue = [];
var uploadDone = 0;
var uploadFailed = 0;
var queueTotal = 0;
var C = 122.52;

function cancelFileFromQueue(qid) {
  if (!isUploading) return;
  for (var k = 1; k < uploadQueue.length; k++) {
    if (uploadQueue[k].id === qid) {
      uploadQueue.splice(k, 1);
      queueTotal--;
      var el = document.getElementById('dq-' + qid);
      if (el) el.remove();
      showToast('Dosya sıradan kaldırıldı.', 'info');
      return;
    }
  }
}

function submitUpload(area) {
  area = area || 'common';
  var fiId = area === 'private' ? 'file-input-private' : 'file-input';
  var fnId = area === 'private' ? 'ua-filename-private' : 'ua-filename';
  var formId = area === 'private' ? 'upload-form-private' : 'upload-form';
  var action = area === 'private' ? 'upload_private' : 'upload_common';
  const fi = document.getElementById(fiId);
  if (!fi || fi.files.length === 0) return;
  for (const f of fi.files) {
    if (!isExtAllowed(f)) {
      showRejectedToast(f.name);
      return;
    }
  }
  var newFiles = Array.from(fi.files);
  var pd = document.getElementById('progress-detail');
  for (var i = 0; i < newFiles.length; i++) {
    var qid = 'q' + Date.now() + i + Math.random().toString(36).slice(2,7);
    queueTotal++;
    uploadQueue.push({ file: newFiles[i], id: qid, action: action, formId: formId });
    if (isUploading) {
      pd.innerHTML += '<div class="detail-item" id="dq-' + qid + '"><span class="detail-name">📄 ' + escHtml(newFiles[i].name) + '</span><span class="detail-size" style="color:#f59e0b;font-weight:600;">Yükleme bekleniyor</span><span class="detail-cancel" style="color:#ef4444;font-size:11px;font-weight:600;cursor:pointer;flex-shrink:0;margin-left:8px;" onclick="event.stopPropagation();cancelFileFromQueue(\'' + qid + '\')">İptal</span></div>';
      showToast('📎 "' + newFiles[i].name + '" sıraya eklendi (' + uploadQueue.length + ' dosya bekliyor).', 'info');
      var pl = document.getElementById('progress-label');
      if (pl) pl.textContent = uploadDone + ' / ' + queueTotal + ' dosya';
    }
  }
  document.getElementById(fiId).value = '';
  if (isUploading) return;

  isUploading = true;
  document.getElementById(fnId).textContent = '';
  uploadDone = 0;
  uploadFailed = 0;
  queueTotal = uploadQueue.length;
  var pw = document.getElementById('progress-wrap');
  var pf = document.getElementById('progress-fill');
  var pp = document.getElementById('progress-pct');
  var pl = document.getElementById('progress-label');
  pw.classList.add('visible');
  pf.classList.remove('done');
  pp.classList.remove('done');
  pp.textContent = '0%';
  pl.textContent = '0 / ' + uploadQueue.length + ' dosya';
  pd.classList.remove('open');
  pd.innerHTML = '';
  for (var j = 0; j < uploadQueue.length; j++) {
    var st = j === 0 ? '' : '<span class="detail-size" style="color:#f59e0b;font-weight:600;">Yükleme bekleniyor</span><span class="detail-cancel" style="color:#ef4444;font-size:11px;font-weight:600;cursor:pointer;flex-shrink:0;margin-left:8px;" onclick="event.stopPropagation();cancelFileFromQueue(\'' + uploadQueue[j].id + '\')">İptal</span>';
    pd.innerHTML += '<div class="detail-item" id="dq-' + uploadQueue[j].id + '"><span class="detail-name">📄 ' + escHtml(uploadQueue[j].file.name) + '</span>' + st + '</div>';
  }
  processQueue();
}

function processQueue() {
  var total = uploadQueue.length;
  if (total === 0 || !isUploading) { finishAllUploads(); return; }
  var item = uploadQueue[0];
  var file = item.file;
  var qid = item.id;
  var action = item.action || 'upload_common';
  var formId = item.formId || 'upload-form';
  var detailRow = document.getElementById('dq-' + qid);
  if (detailRow) detailRow.innerHTML = '<span class="detail-name">📄 ' + escHtml(file.name) + '</span><span class="detail-size" style="font-weight:600;color:#3b82f6;">İndiriliyor %0</span><span class="detail-cancel" style="color:#ef4444;font-size:11px;font-weight:600;cursor:pointer;flex-shrink:0;margin-left:8px;" onclick="event.stopPropagation();cancelUpload()">İptal</span>';

  const form = new FormData();
  form.append('action', action);
  form.append('csrf_token', (document.querySelector('#' + formId + ' [name="csrf_token"]') || {}).value || '');
  form.append('files[]', file);

  const xhr = new XMLHttpRequest();
  currentXHR = xhr;
  var pl = document.getElementById('progress-label');
  pl.textContent = uploadDone + ' / ' + queueTotal + ' dosya (' + escHtml(file.name) + ')';

  xhr.upload.addEventListener('progress', function(e) {
    if (e.lengthComputable && detailRow) {
      var fpct = Math.round((e.loaded / e.total) * 100);
      detailRow.innerHTML = '<span class="detail-name">📄 ' + escHtml(file.name) + '</span><span class="detail-size" style="font-weight:600;color:#3b82f6;">İndiriliyor %' + fpct + '</span><span class="detail-cancel" style="color:#ef4444;font-size:11px;font-weight:600;cursor:pointer;flex-shrink:0;margin-left:8px;" onclick="event.stopPropagation();cancelUpload()">İptal</span>';
      var pf = document.getElementById('progress-fill');
      var pp = document.getElementById('progress-pct');
      var overall = Math.round(((uploadDone + uploadFailed + (e.loaded / e.total)) / queueTotal) * 100);
      pf.setAttribute('stroke-dashoffset', C - (overall / 100) * C);
      pp.textContent = Math.min(overall, 99) + '%';
    }
  });

  xhr.addEventListener('load', function() {
    if (!currentXHR) return;
    uploadQueue.shift();
    try {
      var res = JSON.parse(xhr.responseText);
      if (res.type !== 'success') { uploadFailed++; if (detailRow) detailRow.innerHTML = '<span class="detail-name">📄 ' + escHtml(file.name) + '</span><span class="detail-size" style="color:#ef4444;font-weight:600;">' + (res.msg || 'Hata') + '</span><span class="detail-cancel" style="color:#9ca3af;font-size:11px;font-weight:600;flex-shrink:0;margin-left:8px;">İptal</span>'; processQueue(); return; }
    } catch(e) { uploadFailed++; processQueue(); return; }
    uploadDone++;
      if (detailRow) {
        detailRow.innerHTML = '<span class="detail-name">📄 ' + escHtml(file.name) + '</span><span class="detail-size" style="color:#22c55e;font-weight:600;">İndirildi</span><span class="detail-cancel" style="color:#9ca3af;font-size:11px;font-weight:600;flex-shrink:0;margin-left:8px;">İptal</span>';
      }
    var pp = document.getElementById('progress-pct');
    var pf = document.getElementById('progress-fill');
    var overall = Math.round(((uploadDone + uploadFailed) / queueTotal) * 100);
    pf.setAttribute('stroke-dashoffset', C - (overall / 100) * C);
    pp.textContent = overall + '%';
    var pl = document.getElementById('progress-label');
    pl.textContent = uploadDone + ' / ' + queueTotal + ' dosya';
    processQueue();
  });

  xhr.addEventListener('error', function() {
    if (!currentXHR) return;
    uploadQueue.shift();
    uploadFailed++;
    if (detailRow) {
      detailRow.innerHTML = '<span class="detail-name">📄 ' + escHtml(file.name) + '</span><span class="detail-size" style="color:#ef4444;font-weight:600;">Hata</span><span class="detail-cancel" style="color:#9ca3af;font-size:11px;font-weight:600;flex-shrink:0;margin-left:8px;">İptal</span>';
    }
    processQueue();
  });
  xhr.addEventListener('abort', function() { currentXHR = null; });
  xhr.open('POST', 'dashboard.php', true);
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  xhr.send(form);
}

function finishAllUploads() {
  currentXHR = null;
  var pw = document.getElementById('progress-wrap');
  var pf = document.getElementById('progress-fill');
  var pp = document.getElementById('progress-pct');
  var pl = document.getElementById('progress-label');
  pf.setAttribute('stroke-dashoffset', '0');
  pf.classList.add('done');
  pp.classList.add('done');
  pp.textContent = '✓';
  pl.textContent = uploadDone + ' / ' + queueTotal + ' dosya tamam';
  if (uploadDone > 0) {
    showToast('✓ ' + uploadDone + ' dosya başarıyla yüklendi.' + (uploadFailed > 0 ? ' ' + uploadFailed + ' dosya başarısız.' : ''), 'success');
  }
  isUploading = false;
  setTimeout(function() {
    pw.classList.remove('visible');
    location.reload();
  }, 1500);
}

function submitPrivateUpload() {
  submitUpload('private');
}

function cancelUpload() {
  if (currentXHR) {
    currentXHR.abort();
    currentXHR = null;
  }
  isUploading = false;
  uploadQueue = [];
  uploadDone = 0;
  uploadFailed = 0;
  queueTotal = 0;
  const pw = document.getElementById('progress-wrap');
  pw.classList.remove('visible');
  document.getElementById('progress-detail').classList.remove('open');
  document.getElementById('file-input').value = '';
  document.getElementById('file-input-private').value = '';
  document.getElementById('ua-filename').textContent = '';
  document.getElementById('ua-filename-private').textContent = '';
  showToast('Yükleme iptal edildi.', 'error');
}

function toggleDetail() {
  const pd = document.getElementById('progress-detail');
  pd.classList.toggle('open');
}

// Kullanıcı yönetim modalı
function openUserModal(action, userId, displayName, storageUsed, storageLimit, createdAt, lastLogin, percent) {
  const modal = document.getElementById('user-modal');
  const title = document.getElementById('um-title');
  const sub = document.getElementById('um-sub');
  const body = document.getElementById('um-body');

  if (action === 'delete') {
    title.textContent = 'Hesabı Kaldır';
    sub.textContent = displayName + ' hesabı silinecek.';
    body.innerHTML =
      '<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;padding:14px;font-size:12px;color:#dc2626;margin-bottom:16px;">' +
      '<strong>⚠ Bu işlem geri alınamaz.</strong><br>' +
      'Kullanıcının özel alanındaki tüm dosyalar kalıcı olarak silinecektir.' +
      '</div>' +
      '<form method="post">' +
      '<input type="hidden" name="csrf_token" value="' + CSRF_TOKEN + '">' +
      '<input type="hidden" name="action" value="delete_user">' +
      '<input type="hidden" name="user_id" value="' + userId + '">' +
      '<div style="display:flex;gap:8px;">' +
      '<button type="submit" class="btn btn-danger">Evet, Sil</button>' +
      '<button type="button" class="btn btn-ghost" onclick="closeModal(\'user-modal\')">İptal</button>' +
      '</div></form>';
  } else if (action === 'limit') {
    const currentMB = Math.round(parseInt(storageLimit) / 1048576);
    title.textContent = 'Depolama Limitini Güncelle';
    sub.textContent = displayName + ' için yeni limiti seçin.';
    const opts = [100, 250, 500, 750, 1024, 1536, 2048];
    let sel = '<select name="storage_limit" class="form-input" style="margin-bottom:16px;">';
    for (const o of opts) {
      sel += '<option value="' + o + '" ' + (currentMB === o ? 'selected' : '') + '>' +
        (o >= 1024 ? (o/1024).toFixed(o%1024===0?0:1) + ' GB' : o + ' MB') + '</option>';
    }
    sel += '</select>';
    body.innerHTML =
      '<form method="post">' +
      '<input type="hidden" name="csrf_token" value="' + CSRF_TOKEN + '">' +
      '<input type="hidden" name="action" value="update_storage_limit">' +
      '<input type="hidden" name="user_id" value="' + userId + '">' +
      '<div class="form-group"><label>Yeni Depolama Limiti</label>' + sel + '</div>' +
      '<button type="submit" class="btn btn-primary">Güncelle</button>' +
      '</form>';
  } else if (action === 'password') {
    title.textContent = 'Şifre Yenileme';
    sub.textContent = displayName + ' için yeni şifre belirleyin.';
    body.innerHTML =
      '<form method="post">' +
      '<input type="hidden" name="csrf_token" value="' + CSRF_TOKEN + '">' +
      '<input type="hidden" name="action" value="reset_password">' +
      '<input type="hidden" name="user_id" value="' + userId + '">' +
      '<div class="form-group"><label>Yeni Şifre</label>' +
      '<input type="password" class="form-input" name="new_password" required minlength="4" placeholder="En az 4 karakter"></div>' +
      '<button type="submit" class="btn btn-primary">Şifreyi Sıfırla</button>' +
      '</form>';
  } else if (action === 'detail') {
    const usedFmt = formatBytes(parseInt(storageUsed));
    const limitFmt = formatBytes(parseInt(storageLimit));
    title.textContent = displayName;
    sub.textContent = 'Hesap detayları';
    const pct = parseFloat(percent) || 0;
    const barColor = pct > 85 ? 'var(--danger)' : (pct > 60 ? 'var(--warn)' : 'var(--accent)');
    body.innerHTML =
      '<div style="display:flex;flex-direction:column;gap:12px;">' +
      '<div><div style="font-size:11px;color:var(--text-muted);margin-bottom:4px;">Depolama Kullanımı</div>' +
      '<div style="height:10px;background:var(--surface3);border-radius:5px;overflow:hidden;margin-bottom:4px;">' +
      '<div style="height:100%;width:' + Math.min(100, pct) + '%;background:' + barColor + ';border-radius:5px;"></div></div>' +
      '<div style="font-size:12px;color:var(--text-muted);">' + usedFmt + ' / ' + limitFmt + ' (' + pct + '%)</div></div>' +
      '<div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;font-size:12px;">' +
      '<div style="background:var(--surface2);padding:10px;border-radius:6px;"><div style="color:var(--text-muted);font-size:11px;">Açılma Tarihi</div><div style="font-weight:600;">' + (createdAt || '?') + '</div></div>' +
      '<div style="background:var(--surface2);padding:10px;border-radius:6px;"><div style="color:var(--text-muted);font-size:11px;">Son Giriş</div><div style="font-weight:600;">' + (lastLogin || 'Henüz giriş yapmadı') + '</div></div>' +
      '</div>' +
      '<div style="background:var(--surface2);padding:10px;border-radius:6px;font-size:12px;display:flex;justify-content:space-between;">' +
      '<span style="color:var(--text-muted);">Kullanılan Alan</span><span style="font-weight:600;">' + usedFmt + '</span></div>' +
      '<div style="background:var(--surface2);padding:10px;border-radius:6px;font-size:12px;display:flex;justify-content:space-between;">' +
      '<span style="color:var(--text-muted);">Depolama Limiti</span><span style="font-weight:600;">' + limitFmt + '</span></div>' +
      '</div>' +
      '<div style="margin-top:12px;"><button type="button" class="btn btn-ghost" onclick="closeModal(\'user-modal\')">Kapat</button></div>';
  }
  modal.classList.add('open');
}

// Şifre toggle
function toggleField(id) {
  const f = document.getElementById(id);
  f.type = f.type === 'password' ? 'text' : 'password';
}

// Profil dropdown
function toggleProfileDropdown() {
  document.getElementById('profile-dropdown').classList.toggle('open');
  document.getElementById('bell-dropdown').classList.remove('open');
}

// Bildirim dropdown
function toggleBellDropdown() {
  document.getElementById('bell-dropdown').classList.toggle('open');
  document.getElementById('profile-dropdown').classList.remove('open');
}

document.addEventListener('click', function(e) {
  const pw = document.querySelector('.profile-wrap');
  if (pw && !pw.contains(e.target)) {
    document.getElementById('profile-dropdown').classList.remove('open');
  }
  const bw = document.querySelector('.bell-wrap');
  if (bw && !bw.contains(e.target)) {
    document.getElementById('bell-dropdown').classList.remove('open');
  }
});

// Modal
function closeModal(id) {
  document.getElementById(id).classList.remove('open');
  if (id === 'share-modal') {
    document.getElementById('share-options').style.display = 'block';
  }
}

let currentFileId = null;
let currentFileName = null;
const CSRF_TOKEN = '<?= generateCsrfToken() ?>';
const MAX_STORAGE = <?= MAX_STORAGE ?>;
const COMMON_USED = <?= $commonUsed ?>;
const USER_STORAGE_LIMIT = <?= $userStorageLimit ?>;
const USER_STORAGE_USED = <?= $userStorageUsed ?>;

// Önizleme
function openPreview(fileId) {
  currentFileId = fileId;

  fetch('api.php?action=file_info&id=' + fileId)
    .then(r => r.json())
    .then(data => {
      if (!data.success) return;
      const f = data.file;
      currentFileName = f.original_name;

      document.getElementById('pm-title').textContent = f.original_name;
      document.getElementById('pm-sub').textContent = formatBytes(f.size) + ' · ' + f.mime;

      // Sağ taraf: indirme seçenekleri
      const codeOpts = document.getElementById('code-dl-options');
      const securityNote = document.getElementById('pm-security-note');
      const dlBtn = document.getElementById('pm-download');
      if (f.code_zipped) {
        dlBtn.style.display = 'none';
        codeOpts.style.display = 'block';
        securityNote.style.display = 'block';
        document.getElementById('pm-dl-zip').href = 'download.php?id=' + fileId + '&format=zip';
        document.getElementById('pm-dl-orig').href = 'download.php?id=' + fileId + '&format=original';
      } else {
        dlBtn.style.display = 'flex';
        codeOpts.style.display = 'none';
        securityNote.style.display = 'none';
        dlBtn.href = 'download.php?id=' + fileId;
      }

      // Preview
      const pc = document.getElementById('pm-preview');
      pc.innerHTML = '';

      if (f.previewable) {
        if (f.mime.startsWith('image/')) {
          pc.innerHTML = '<img src="download.php?id=' + fileId + '&preview=1" alt="Önizleme">';
        } else if (f.mime.startsWith('video/')) {
          pc.innerHTML = '<video controls><source src="download.php?id=' + fileId + '&preview=1"></video>';
        } else if (f.mime.startsWith('audio/')) {
          pc.innerHTML = '<audio controls style="width:100%;padding:20px"><source src="download.php?id=' + fileId + '&preview=1"></audio>';
        } else if (f.mime === 'application/pdf') {
          pc.innerHTML = '<iframe src="download.php?id=' + fileId + '&preview=1"></iframe>';
        } else if (f.mime.startsWith('text/')) {
          fetch('download.php?id=' + fileId + '&preview=1')
            .then(r => r.text())
            .then(txt => {
              pc.innerHTML = '<pre style="color:#111827;padding:16px;font-size:12px;overflow:auto;max-height:300px;text-align:left">' + escHtml(txt.substring(0, 5000)) + '</pre>';
            });
        }
      } else {
        let fbHtml = '<div class="preview-fallback">' +
          '<div class="pf-icon">' + f.icon + '</div>';
        if (f.code_zipped) {
          fbHtml += '<div class="pf-msg">📦 Kod dosyası zip olarak kaydedildi</div>' +
            '<div class="pf-sub">Bu dosya (.' + (f.original_ext || '') + ') bir kod dosyası olduğu için otomatik zip\'lendi.<br>Sağ taraftan zip veya orijinal seçeneğini seçebilirsiniz.</div>';
        } else {
          fbHtml += '<div class="pf-msg">Bu dosya biçimi önizlenemiyor</div>' +
            '<div class="pf-sub">Desteklenen önizleme biçimleri: Görüntüler, PDF, Video, Ses, Metin dosyaları</div>';
        }
        fbHtml += '</div>';
        pc.innerHTML = fbHtml;
      }

      // Dosya bilgileri (sağ panel)
      let ownerLabel = '';
      if (f.owner_name) {
        ownerLabel = '<span class="fi-label">Yükleyen</span><span class="fi-val">👤 ' + escHtml(f.owner_name) + '</span>';
      }
      let codeLabel = '';
      if (f.code_zipped) {
        codeLabel = '<span class="fi-label">Durum</span><span class="fi-val"><span style="color:var(--warn);font-weight:600;">📦 Zip\'li Kod Dosyası</span></span>';
        if (f.original_ext) {
          codeLabel += '<span class="fi-label">Orijinal Uzantı</span><span class="fi-val">.' + escHtml(f.original_ext) + '</span>';
        }
      }
      document.getElementById('pm-info').innerHTML =
        '<span class="fi-label">Dosya Adı</span><span class="fi-val">' + escHtml(f.original_name) + '</span>' +
        '<span class="fi-label">Boyut</span><span class="fi-val">' + formatBytes(f.size) + '</span>' +
        '<span class="fi-label">Tür</span><span class="fi-val">' + escHtml(f.mime) + '</span>' +
        ownerLabel +
        '<span class="fi-label">Yükleme Tarihi</span><span class="fi-val">' + escHtml(f.uploaded_at) + '</span>' +
        '<span class="fi-label">Silinme</span><span class="fi-val" style="color:var(--warn)">' + escHtml(f.expire_label) + ' kaldı</span>' +
        codeLabel;

      document.getElementById('preview-modal').classList.add('open');
    });
}

function openShareFromModal() {
  closeModal('preview-modal');
  openShare(currentFileId);
}

function openRenameFromModal() {
  closeModal('preview-modal');
  openRename(currentFileId, currentFileName);
}

function deleteFromModal() {
  closeModal('preview-modal');
  confirmDelete(currentFileId, currentFileName);
}

function openRename(fileId, fileName) {
  document.getElementById('rename-file-id').value = fileId;
  document.getElementById('rename-input').value = fileName;
  document.getElementById('rename-modal').classList.add('open');
}

function confirmDelete(fileId, fileName) {
  document.getElementById('delete-file-id').value = fileId;
  document.getElementById('delete-sub').textContent = '"' + fileName + '" silinecek. Emin misiniz?';
  document.getElementById('delete-modal').classList.add('open');
}

function openShare(fileId) {
  document.getElementById('share-loading').style.display = 'block';
  document.getElementById('share-result').style.display = 'none';
  document.getElementById('share-options').style.display = 'none';
  document.getElementById('share-modal').classList.add('open');

  const maxAccess = document.getElementById('share-max-access').value || 0;
  const hoursLimit = document.getElementById('share-hours-limit').value || 0;

  const form = new FormData();
  form.append('action', 'create_share');
  form.append('file_id', fileId);
  form.append('max_access', maxAccess);
  form.append('hours_limit', hoursLimit);
  form.append('csrf_token', CSRF_TOKEN);

  fetch('dashboard.php', { method: 'POST', body: form })
    .then(r => r.json())
    .then(data => {
      document.getElementById('share-loading').style.display = 'none';
      document.getElementById('share-code-text').textContent = data.code;
      let expireText = '';
      if (parseInt(hoursLimit) > 0) {
        expireText = parseInt(hoursLimit) + ' saat sonra sona erecek';
      } else {
        expireText = 'Dosya silinene kadar geçerli';
      }
      if (parseInt(maxAccess) > 0) {
        expireText += ' · En fazla ' + maxAccess + ' erişim';
      }
      document.getElementById('share-result').style.display = 'block';
    })
    .catch(() => {
      document.getElementById('share-loading').style.display = 'none';
      document.getElementById('share-options').style.display = 'block';
      showToast('Paylaşım kodu oluşturulamadı.', 'error');
    });
}

function resetShareModal() {
  document.getElementById('share-options').style.display = 'block';
  document.getElementById('share-loading').style.display = 'none';
  document.getElementById('share-result').style.display = 'none';
}

function copyCode() {
  const code = document.getElementById('share-code-text').textContent;
  navigator.clipboard.writeText(code).then(() => {
    const el = document.getElementById('copy-confirm');
    el.style.display = 'inline';
    setTimeout(() => el.style.display = 'none', 2000);
  });
}

function formatBytes(b) {
  if (b >= 1073741824) return (b/1073741824).toFixed(2) + ' GB';
  if (b >= 1048576) return (b/1048576).toFixed(1) + ' MB';
  if (b >= 1024) return (b/1024).toFixed(1) + ' KB';
  return b + ' B';
}

function escHtml(str) {
  const d = document.createElement('div');
  d.appendChild(document.createTextNode(str));
  return d.innerHTML;
}

// Modal dışına tıklayınca kapat
document.querySelectorAll('.modal-overlay').forEach(o => {
  o.addEventListener('click', e => { if (e.target === o) o.classList.remove('open'); });
});

// Toast bildirim
function showToast(msg, type) {
  const c = document.getElementById('toast-container');
  const t = document.createElement('div');
  t.className = 'toast toast-' + type;
  t.textContent = msg;
  c.appendChild(t);
  setTimeout(() => { if (t.parentNode) t.remove(); }, 4000);
}

<?php if ($uploadMsg): ?>
showToast('<?= htmlspecialchars(addslashes($uploadMsg)) ?>', '<?= $uploadType === 'success' ? 'success' : 'error' ?>');
<?php endif; ?>


// ── Sidebar toggle (mobile) ──
// ── View mode ──
function setView(mode) {
  document.querySelectorAll('.files-grid').forEach(g => {
    g.className = 'files-grid view-' + mode;
  });
  document.querySelectorAll('.view-btn').forEach(b => {
    b.classList.toggle('active', b.dataset.view === mode);
  });
  localStorage.setItem('datastore_view', mode);
}

(function initView() {
  const saved = localStorage.getItem('datastore_view') || 'grid';
  setView(saved);
})();

// Sekme geçişlerini AJAX ile yap (sayfa yeniden yüklenmez, upload kesilmez)
document.querySelector('.sidebar').addEventListener('click', function(e) {
  var link = e.target.closest('.nav-item');
  if (!link || link.getAttribute('href').indexOf('logout') !== -1) return;
  e.preventDefault();
  var url = link.getAttribute('href');
  history.pushState(null, '', url);
  fetch(url)
    .then(function(r) { return r.text(); })
    .then(function(html) {
      var p = new DOMParser();
      var doc = p.parseFromString(html, 'text/html');
      var newContent = doc.querySelector('.content');
      var oldContent = document.querySelector('.content');
      if (newContent && oldContent) {
        oldContent.innerHTML = newContent.innerHTML;
      }
      var newTitle = doc.querySelector('.topbar-title');
      var oldTitle = document.querySelector('.topbar-title');
      if (newTitle && oldTitle) {
        oldTitle.innerHTML = newTitle.innerHTML;
      }
      var newStorage = doc.querySelector('#sidebar-storage');
      var oldStorage = document.querySelector('#sidebar-storage');
      if (newStorage && oldStorage) {
        oldStorage.outerHTML = newStorage.outerHTML;
      }
      document.querySelectorAll('.sidebar .nav-item').forEach(function(l) {
        l.classList.toggle('active', l.getAttribute('href') === url);
      });
      var tabMatch = url.match(/[?&]tab=(\w+)/);
      var tabName = tabMatch ? tabMatch[1] : 'common';
      var batchBar = document.getElementById('batch-bar');
      if (batchBar && (tabName === 'admin' || tabName === 'settings' || tabName === 'shares')) {
        batchBar.classList.remove('visible');
      }
      var saved = localStorage.getItem('datastore_view') || 'grid';
      setView(saved);
    });
});

// Tarayıcı geri/ileri butonları
window.addEventListener('popstate', function() {
  location.reload();
});

function toggleSidebar() {
  document.getElementById('sidebar').classList.toggle('open');
  document.getElementById('sidebar-overlay').classList.toggle('open');
}

// ── File search ──
function filterFiles(query) {
  const q = query.toLowerCase().trim();
  document.querySelectorAll('.file-card-wrap').forEach(w => {
    const name = w.querySelector('.file-name');
    if (!name) return;
    const match = !q || name.textContent.toLowerCase().includes(q);
    w.style.display = match ? '' : 'none';
  });
}

// ── Batch operations ──
function getSelectedIds() {
  const ids = [];
  document.querySelectorAll('.file-checkbox:checked').forEach(cb => {
    ids.push(cb.dataset.fileId);
  });
  return ids;
}

function updateBatchBar() {
  const bar = document.getElementById('batch-bar');
  if (!bar) return;
  const ids = getSelectedIds();
  document.querySelectorAll('.file-card-wrap').forEach(w => {
    const cb = w.querySelector('.file-checkbox');
    if (cb && cb.checked) {
      w.classList.add('selected');
    } else {
      w.classList.remove('selected');
    }
  });
  if (ids.length === 0) {
    bar.classList.remove('visible');
    return;
  }
  bar.classList.add('visible');
  document.getElementById('batch-count').textContent = ids.length + ' dosya seçildi';
}

function selectAllFiles() {
  document.querySelectorAll('.file-checkbox').forEach(cb => cb.checked = true);
  updateBatchBar();
}

function clearSelection() {
  document.querySelectorAll('.file-checkbox:checked').forEach(cb => cb.checked = false);
  updateBatchBar();
}

function batchDownload() {
  const ids = getSelectedIds();
  if (ids.length === 0) return;
  window.location.href = 'download.php?batch=zip&ids=' + ids.join(',');
  clearSelection();
}

function batchDelete() {
  const ids = getSelectedIds();
  if (ids.length === 0) return;

  const form = new FormData();
  form.append('ids', ids.join(','));
  form.append('csrf_token', CSRF_TOKEN);

  fetch('api.php?action=batch_delete', { method: 'POST', body: form })
    .then(r => r.json())
    .then(data => {
      showToast(data.msg || 'Silindi.', data.deleted > 0 ? 'success' : 'error');
      if (data.deleted > 0) setTimeout(() => location.reload(), 800);
    })
    .catch(() => showToast('Silme hatası.', 'error'));
}

// ── Override openPreview to add version list ──
openPreview = function(fileId) {
  currentFileId = fileId;

  fetch('api.php?action=file_info&id=' + fileId)
    .then(r => r.json())
    .then(data => {
      if (!data.success) return;
      const f = data.file;
      currentFileName = f.original_name;

      document.getElementById('pm-title').textContent = f.original_name;
      document.getElementById('pm-sub').textContent = formatBytes(f.size) + ' · ' + f.mime;

      // Sağ taraf: indirme seçenekleri
      const codeOpts = document.getElementById('code-dl-options');
      const securityNote = document.getElementById('pm-security-note');
      const dlBtn = document.getElementById('pm-download');
      if (f.code_zipped) {
        dlBtn.style.display = 'none';
        codeOpts.style.display = 'block';
        securityNote.style.display = 'block';
        document.getElementById('pm-dl-zip').href = 'download.php?id=' + fileId + '&format=zip';
        document.getElementById('pm-dl-orig').href = 'download.php?id=' + fileId + '&format=original';
      } else {
        dlBtn.style.display = 'flex';
        codeOpts.style.display = 'none';
        securityNote.style.display = 'none';
        dlBtn.href = 'download.php?id=' + fileId;
      }

      // Preview
      const pc = document.getElementById('pm-preview');
      pc.innerHTML = '';

      if (f.previewable) {
        if (f.mime.startsWith('image/')) {
          pc.innerHTML = '<img src="download.php?id=' + fileId + '&preview=1" alt="Önizleme">';
        } else if (f.mime.startsWith('video/')) {
          pc.innerHTML = '<video controls><source src="download.php?id=' + fileId + '&preview=1"></video>';
        } else if (f.mime.startsWith('audio/')) {
          pc.innerHTML = '<audio controls style="width:100%;padding:20px"><source src="download.php?id=' + fileId + '&preview=1"></audio>';
        } else if (f.mime === 'application/pdf') {
          pc.innerHTML = '<iframe src="download.php?id=' + fileId + '&preview=1"></iframe>';
        } else if (f.mime.startsWith('text/')) {
          fetch('download.php?id=' + fileId + '&preview=1')
            .then(r => r.text())
            .then(txt => {
              pc.innerHTML = '<pre style="color:#111827;padding:16px;font-size:12px;overflow:auto;max-height:300px;text-align:left">' + escHtml(txt.substring(0, 5000)) + '</pre>';
            });
        }
      } else {
        let fbHtml = '<div class="preview-fallback">' +
          '<div class="pf-icon">' + f.icon + '</div>';
        if (f.code_zipped) {
          fbHtml += '<div class="pf-msg">📦 Kod dosyası zip olarak kaydedildi</div>' +
            '<div class="pf-sub">Bu dosya (.' + (f.original_ext || '') + ') bir kod dosyası olduğu için otomatik zip\'lendi.<br>Sağ taraftan zip veya orijinal seçeneğini seçebilirsiniz.</div>';
        } else {
          fbHtml += '<div class="pf-msg">Bu dosya biçimi önizlenemiyor</div>' +
            '<div class="pf-sub">Desteklenen önizleme biçimleri: Görüntüler, PDF, Video, Ses, Metin dosyaları</div>';
        }
        fbHtml += '</div>';
        pc.innerHTML = fbHtml;
      }

      // Dosya bilgileri
      let verLabel = '';
      if (f.version > 1) verLabel = ' · <span style="color:var(--accent);font-weight:600;">v' + f.version + '</span>';
      let ownerLabel = '';
      if (f.owner_name) {
        ownerLabel = '<span class="fi-label">Yükleyen</span><span class="fi-val">👤 ' + escHtml(f.owner_name) + '</span>';
      }
      let codeLabel = '';
      if (f.code_zipped) {
        codeLabel = '<span class="fi-label">Durum</span><span class="fi-val"><span style="color:var(--warn);font-weight:600;">📦 Zip\'li Kod Dosyası</span></span>';
        if (f.original_ext) {
          codeLabel += '<span class="fi-label">Orijinal Uzantı</span><span class="fi-val">.' + escHtml(f.original_ext) + '</span>';
        }
      }
      document.getElementById('pm-info').innerHTML =
        '<span class="fi-label">Dosya Adı</span><span class="fi-val">' + escHtml(f.original_name) + verLabel + '</span>' +
        '<span class="fi-label">Boyut</span><span class="fi-val">' + formatBytes(f.size) + '</span>' +
        '<span class="fi-label">Tür</span><span class="fi-val">' + escHtml(f.mime) + '</span>' +
        ownerLabel +
        '<span class="fi-label">Yükleme Tarihi</span><span class="fi-val">' + escHtml(f.uploaded_at) + '</span>' +
        '<span class="fi-label">Silinme</span><span class="fi-val" style="color:var(--warn)">' + escHtml(f.expire_label) + ' kaldı</span>' +
        codeLabel;

      // Versiyon listesi
      const pv = document.getElementById('pm-versions');
      if (f.versions && f.versions.length > 1) {
        pv.style.display = 'block';
        let html = '<div class="version-list-title">📋 Versiyon Geçmişi (' + f.versions.length + ')</div>';
        for (const v of f.versions) {
          const isCurrent = v.id === fileId;
          html += '<div class="version-item' + (isCurrent ? ' current' : '') + '" onclick="' + (isCurrent ? '' : "openPreview('" + v.id + "')") + '">' +
            '<span class="v-icon">' + v.icon + '</span>' +
            '<span class="v-badge">v' + v.version + '</span>' +
            '<span class="v-name">' + escHtml(v.original_name) + '</span>' +
            '<span class="v-size">' + formatBytes(v.size) + '</span>' +
            '</div>';
        }
        pv.innerHTML = html;
      } else {
        pv.style.display = 'none';
      }

      document.getElementById('preview-modal').classList.add('open');
    });
};
</script>
</body>
</html>
