<?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();
if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit;
}

require_once 'includes/functions.php';

$left_action = $_GET['action'] ?? 'send';
$msg = '';
$msg_type = '';
$lockout = checkLoginLockout();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    verifyCsrfToken();
    if ($_POST['action'] === 'send_file') {
        // Çoklu dosya desteği
        $results = [];
        $files = $_FILES['files'] ?? [];
        $recipientEmail = trim($_POST['recipient_email'] ?? '');
        $senderEmail    = trim($_POST['sender_email'] ?? '');
        $message        = trim($_POST['message'] ?? '');

        if (empty($files['tmp_name'][0])) {
            $msg = 'Lütfen en az bir dosya seçin.';
            $msg_type = 'error';
        } elseif (!filter_var($recipientEmail, FILTER_VALIDATE_EMAIL)) {
            $msg = 'Geçersiz alıcı e-posta adresi.';
            $msg_type = 'error';
        } else {
            $recipient = getUserByEmail($recipientEmail);
            if (!$recipient) {
                $msg = 'Bu e-posta adresinde kayıtlı kullanıcı bulunamadı.';
                $msg_type = 'error';
            } else {
                $ok = 0; $fail = 0;
                foreach ($files['tmp_name'] as $i => $tmp) {
                    if ($files['error'][$i] !== UPLOAD_ERR_OK) { $fail++; continue; }
                    $single = [
                        'name'     => $files['name'][$i],
                        'tmp_name' => $tmp,
                        'size'     => $files['size'][$i],
                        'error'    => $files['error'][$i],
                        'type'     => $files['type'][$i],
                    ];
                    $r = uploadFile($single, 'private', null, $recipient['id'], $senderEmail, $message);
                    $r['type'] === 'success' ? $ok++ : $fail++;
                }
                if ($ok > 0 && $fail === 0) {
                    $msg = $ok . ' dosya başarıyla gönderildi!';
                    $msg_type = 'success';
                } elseif ($ok > 0) {
                    $msg = $ok . ' dosya gönderildi, ' . $fail . ' dosya başarısız.';
                    $msg_type = 'success';
                } else {
                    $msg = 'Dosya yükleme başarısız.';
                    $msg_type = 'error';
                }
            }
        }
    } elseif ($_POST['action'] === 'check_code') {
        require_once 'includes/functions.php';
        $shareLockout = checkShareLockout();
        if ($shareLockout) {
            $msg = 'Çok fazla hatalı deneme. Lütfen ' . formatLockoutTime($shareLockout['remaining']) . ' bekleyin.';
            $msg_type = 'error';
        } else {
            $code = trim($_POST['share_code'] ?? '');
            $share = getShareByCode($code);
            if ($share) {
                header('Location: shared.php?code=' . urlencode($code));
                exit;
            } else {
                recordShareAttempt();
                $msg = 'Geçersiz veya süresi dolmuş paylaşım kodu.';
                $msg_type = 'error';
                $left_action = 'code';
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    if ($lockout) {
        $login_error = 'Çok fazla hatalı giriş denemesi. Lütfen ' . formatLockoutTime($lockout['remaining']) . ' bekleyin.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $user = authenticateUser($username, $password);
        if ($user) {
            addLoginLog($username, $user['id'], 'success');
            addSystemLog('login', $user['username'] . ' giriş yaptı (IP: ' . getClientIP() . ')', $user['id']);
            resetLoginAttempts();
            session_regenerate_id(true);
            setActiveSession($user['id']);
            $_SESSION['user_id']      = $user['id'];
            $_SESSION['username']     = $user['username'];
            $_SESSION['display_name'] = $user['display_name'];
            header('Location: dashboard.php');
            exit;
        } else {
            $loginResult = recordFailedAttempt();
            $login_error = 'Kullanıcı adı veya şifre hatalı.';
            $targetUser = getUserByEmail($username);
            addSystemLog('login_failed', 'Başarısız giriş denemesi: ' . $username . ' (IP: ' . getClientIP() . ')', $targetUser ? $targetUser['id'] : null);
            addLoginLog($username, $targetUser ? $targetUser['id'] : null, 'failed',
                $loginResult ? true : false, $loginResult ? 1 : 0);
            if ($targetUser) {
                $notifMsg = 'Hesabınıza başarısız giriş denemesi yapıldı (IP: ' . getClientIP() . ')';
                if ($loginResult) {
                    $notifMsg .= ' Hesap 10 dakika süreyle kilitlendi.';
                }
                addNotification($targetUser['id'], $loginResult ? 'lockout' : 'failed_login', $notifMsg);
            }
            if ($loginResult) {
                $lockout = $loginResult;
            }
        }
    }
}

$slider_images = [];
$assets_dir = __DIR__ . '/assets/';
if (is_dir($assets_dir)) {
    $files_sl = glob($assets_dir . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
    sort($files_sl);
    foreach ($files_sl as $f) {
        $slider_images[] = 'assets/' . basename($f);
    }
}
if (empty($slider_images)) {
    // assets/slides/ klasörünü de dene
    $fallback_dir = __DIR__ . '/assets/slides/';
    if (is_dir($fallback_dir)) {
        $files_sl = glob($fallback_dir . '*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
        sort($files_sl);
        foreach ($files_sl as $f) {
            $slider_images[] = 'assets/slides/' . basename($f);
        }
    }
}
if (empty($slider_images)) {
    $slider_images = ['assets/default_bg.svg'];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DataStore — Dosya Paylaşım Sistemi</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 {
    --accent: #2979ff;
    --accent-hover: #1565c0;
    --text-dark: #222;
    --text-mid: #555;
    --text-light: #999;
    --border: #e0e4ea;
    --bg-input: #f5f7fa;
    --right-w: 400px;
    --panel-w: 340px;
  }
  html, body { height: 100%; font-family: 'Inter', sans-serif; background: #0a0a0a; color: #f0f0f0; overflow: hidden; }
  .layout { display: flex; height: 100vh; width: 100vw; position: relative; background: #0a0a0a; }

  /* ── SOL PANEL (cam kart) ── */
  .left-panel {
    width: var(--panel-w);
    min-width: var(--panel-w);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2;
    padding: 24px 20px;
    position: relative;
    background: transparent;
    margin-right: auto;
  }

  .left-card {
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 8px 40px rgba(0,0,0,0.35);
    padding: 22px 20px 18px;
    width: 100%;
    max-height: calc(100vh - 48px);
    overflow-y: auto;
    scrollbar-width: none;
  }
  .left-card::-webkit-scrollbar { display: none; }

  /* Tab row */
  .tab-row {
    display: flex;
    border-bottom: 1.5px solid var(--border);
    margin-bottom: 16px;
  }
  .tab-btn {
    flex: 1;
    padding: 8px 4px;
    background: none;
    border: none;
    border-bottom: 2.5px solid transparent;
    margin-bottom: -1.5px;
    font-size: 12px;
    font-weight: 600;
    font-family: inherit;
    color: var(--text-light);
    cursor: pointer;
    transition: all 0.2s;
  }
  .tab-btn.active { color: var(--accent); border-bottom-color: var(--accent); }
  .tab-btn:hover:not(.active) { color: var(--text-mid); }

  .panel-section { display: none; min-height: 380px; }
  .panel-section.active { display: block; }

  /* Upload zone — büyük, ikon merkezde */
  .upload-zone {
    border: 1.5px dashed #c5cfe0;
    border-radius: 10px;
    padding: 18px 14px 14px;
    text-align: center;
    cursor: pointer;
    transition: all 0.2s;
    background: #f8faff;
    margin-bottom: 12px;
    position: relative;
  }
  .upload-zone:hover, .upload-zone.drag-over {
    border-color: var(--accent);
    background: #eef3ff;
  }
  .upload-zone .uz-cloud {
    width: 38px;
    height: 38px;
    color: var(--accent);
    margin: 0 auto 8px;
    display: block;
  }
  .upload-zone .uz-title {
    font-size: 13px;
    font-weight: 600;
    color: var(--text-dark);
    margin-bottom: 3px;
  }
  .upload-zone .uz-sub {
    font-size: 11px;
    color: var(--text-light);
    line-height: 1.5;
  }
  .uz-sub strong { color: var(--accent); }

  /* Seçilen dosyalar listesi */
  .file-list {
    margin-bottom: 10px;
    display: flex;
    flex-direction: column;
    gap: 5px;
    max-height: 110px;
    overflow-y: auto;
  }
  .file-item {
    display: flex;
    align-items: center;
    gap: 7px;
    background: #f0f4ff;
    border: 1px solid #d0daf8;
    border-radius: 7px;
    padding: 5px 8px;
    font-size: 11px;
    color: var(--text-dark);
  }
  .file-item-icon { font-size: 14px; flex-shrink: 0; }
  .file-item-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500; }
  .file-item-size { color: var(--text-light); flex-shrink: 0; font-size: 10px; }
  .file-item-del {
    background: none; border: none; color: #bbb; cursor: pointer; font-size: 14px; line-height: 1; padding: 0 2px;
    flex-shrink: 0;
  }
  .file-item-del:hover { color: #e53935; }

  /* Form alanları */
  .form-field {
    width: 100%;
    background: var(--bg-input);
    border: 1px solid var(--border);
    border-radius: 8px;
    padding: 9px 12px;
    font-size: 12.5px;
    font-family: inherit;
    color: var(--text-dark);
    outline: none;
    transition: border-color 0.2s;
    margin-bottom: 8px;
    display: block;
  }
  .form-field:focus { border-color: var(--accent); background: #fff; }
  .form-field::placeholder { color: var(--text-light); }
  textarea.form-field { resize: none; height: 62px; }

  /* Alt buton satırı */
  .send-row {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-top: 4px;
  }
  .icon-btn {
    width: 38px;
    height: 38px;
    border: 1.5px solid var(--border);
    border-radius: 8px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    flex-shrink: 0;
    transition: border-color 0.2s;
  }
  .icon-btn:hover { border-color: var(--accent); }
  .send-btn {
    flex: 1;
    background: var(--accent);
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 9px 16px;
    font-size: 13px;
    font-weight: 700;
    font-family: inherit;
    cursor: pointer;
    transition: background 0.15s;
  }
  .send-btn:hover { background: var(--accent-hover); }

  /* Alert */
  .alert {
    padding: 9px 12px;
    border-radius: 8px;
    font-size: 11.5px;
    margin-bottom: 12px;
    line-height: 1.5;
    font-weight: 500;
  }
  .alert-success { background: #e8f5e9; border: 1px solid #a5d6a7; color: #2e7d32; }
  .alert-error { background: #ffebee; border: 1px solid #ef9a9a; color: #c62828; }

  /* Kod girişi */
  .code-input {
    font-family: 'Courier New', monospace;
    font-size: 20px;
    text-align: center;
    letter-spacing: 5px;
    font-weight: 800;
    color: var(--accent);
    text-transform: uppercase;
    background: #f0f4ff;
    border: 1.5px solid #c5cfe0;
  }
  .code-input:focus { border-color: var(--accent); background: #e8efff; }

  .code-btn {
    width: 100%;
    background: var(--accent);
    color: #fff;
    border: none;
    border-radius: 8px;
    padding: 10px;
    font-size: 13px;
    font-weight: 700;
    font-family: inherit;
    cursor: pointer;
    margin-top: 4px;
    transition: background 0.15s;
  }
  .code-btn:hover { background: var(--accent-hover); }
  .code-hint { font-size: 11px; color: var(--text-light); margin-top: 14px; line-height: 1.6; border-top: 1px solid var(--border); padding-top: 12px; }

  /* ── ORTA SLIDER (tam arka plan) ── */
  .center-area { position: absolute; inset: 0; z-index: 0; overflow: hidden; }
  .slider-wrap { width: 100%; height: 100%; position: relative; }
  .slide { position: absolute; inset: 0; opacity: 0; transition: opacity 1.2s ease; background-size: cover; background-position: center; }
  .slide.active { opacity: 1; }
  .slide-overlay { position: absolute; inset: 0; background: linear-gradient(135deg, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0.2) 100%); }

  /* Sadece indikatörler — sol altta */
  .slide-indicators-wrap {
    position: absolute;
    bottom: 32px;
    left: 36px;
    display: flex;
    gap: 7px;
  }
  .indicator {
    width: 22px;
    height: 3px;
    border-radius: 2px;
    background: rgba(255,255,255,0.35);
    cursor: pointer;
    transition: all 0.3s;
  }
  .indicator.active { background: #2979ff; width: 34px; }

  /* ── SAĞ PANEL ── */
  .right-panel {
    width: var(--right-w);
    min-width: var(--right-w);
    background: #fff;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    position: relative;
    z-index: 2;
  }
  .right-body {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 40px 24px;
  }

  .brand { text-align: center; margin-bottom: 32px; }
  .brand-logo { display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 5px; }
  .brand-icon { width: 38px; height: 38px; }
  .brand-name { font-size: 24px; font-weight: 800; color: #111; letter-spacing: -0.5px; }
  .brand-name span { color: #2979ff; }
  .brand-tagline { font-size: 11px; color: #9ca3af; font-weight: 500; text-transform: uppercase; letter-spacing: 1.5px; }

  .login-form { width: 100%; max-width: 300px; }
  .login-title { font-size: 19px; font-weight: 700; color: #111; text-align: center; margin-bottom: 22px; }

  .login-group { position: relative; margin-bottom: 12px; }
  .login-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); width: 15px; height: 15px; color: #9ca3af; }
  .login-input {
    width: 100%; padding: 10px 12px 10px 36px;
    border: 1px solid #d1d5db; border-radius: 8px;
    font-size: 13.5px; font-family: inherit; color: #111;
    outline: none; background: #f9fafb;
    transition: border-color 0.2s, box-shadow 0.2s;
  }
  .login-input:focus { border-color: #2979ff; box-shadow: 0 0 0 3px rgba(41,121,255,0.1); background: #fff; }
  .login-input.pw-field { padding-right: 38px; }

  .pw-eye { position: absolute; right: 11px; top: 50%; transform: translateY(-50%); cursor: pointer; background: none; border: none; color: #9ca3af; display: flex; align-items: center; }
  .pw-eye:hover { color: #111; }

  .login-error { background: #fef2f2; border: 1px solid #fecaca; color: #dc2626; border-radius: 7px; padding: 9px 12px; font-size: 12px; margin-bottom: 12px; text-align: center; }

  .lockout-container { text-align: center; padding: 10px 0; width: 100%; max-width: 300px; }
  .lockout-icon { width: 44px; height: 44px; margin: 0 auto 10px; color: #dc2626; }
  .lockout-title { font-size: 17px; font-weight: 700; color: #111; margin-bottom: 6px; }
  .lockout-text { font-size: 12px; color: #6b7280; margin-bottom: 16px; line-height: 1.5; }
  .lockout-bar-wrap { background: #e5e7eb; border-radius: 10px; height: 10px; overflow: hidden; margin-bottom: 6px; }
  .lockout-bar { height: 100%; width: 0%; background: linear-gradient(90deg, #2979ff, #42a5f5); border-radius: 10px; transition: width 1s linear; }
  .lockout-info { display: flex; justify-content: space-between; font-size: 11px; color: #9ca3af; font-weight: 600; }

  .remember-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; font-size: 12.5px; }
  .remember-row label { display: flex; align-items: center; gap: 6px; cursor: pointer; color: #374151; }
  .login-btn {
    width: 100%; padding: 11px; background: #2979ff; color: #fff; border: none;
    border-radius: 8px; font-size: 13.5px; font-weight: 700; font-family: inherit;
    cursor: pointer; transition: background 0.15s; letter-spacing: 0.3px;
  }
  .login-btn:hover { background: #1565c0; }

  .right-footer { padding: 16px 40px 28px; text-align: center; }
  .version-badge { font-size: 10.5px; color: #d1d5db; font-weight: 700; }

  @media (max-width: 860px) {
    .left-panel { display: none; }
    .center-area { display: none; }
    .right-panel { width: 100%; min-width: 100%; }
  }
  @keyframes spin { to { transform: rotate(360deg); } }

  .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;
    color: #fff;
    box-shadow: 0 4px 24px rgba(0,0,0,0.12);
    animation: toastIn 0.35s ease, toastOut 0.35s ease 3.5s forwards;
  }
  .toast-error { background: #ef4444; }
  @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); }
  }
</style>
</head>
<body>
<div class="layout">

  <!-- SOL PANEL -->
  <aside class="left-panel">
    <div class="left-card">

      <div class="tab-row">
        <button class="tab-btn <?= $left_action === 'send' ? 'active' : '' ?>" onclick="switchTab('send')">Dosya Gönder</button>
        <button class="tab-btn <?= $left_action === 'code' ? 'active' : '' ?>" onclick="switchTab('code')">Kod ile Aç</button>
      </div>

      <?php if ($msg): ?>
        <div class="alert alert-<?= $msg_type ?>"><?= htmlspecialchars($msg) ?></div>
      <?php endif; ?>

      <!-- GÖNDER SEKMESİ -->
      <div class="panel-section <?= $left_action === 'send' ? 'active' : '' ?>" id="sec-send">
        <form method="post" enctype="multipart/form-data" id="send-form">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="send_file">

          <!-- Upload Zone -->
          <div class="upload-zone" id="upload-zone" onclick="document.getElementById('file-input').click()">
            <svg class="uz-cloud" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
              <path d="M12 16.5V9.75m0 0l3 3m-3-3l-3 3M6.75 19.5a4.5 4.5 0 01-1.41-8.775 5.25 5.25 0 0110.338-2.32 5.75 5.75 0 011.52 11.095H6.75z"/>
            </svg>
            <div class="uz-title">Dosya Seçmek İçin Tıklayınız</div>
            <div class="uz-sub"><strong>500 MB</strong>'a kadar olan dosyalarınız sistemde<br><strong>5 gün</strong> boyunca saklanır.</div>
          </div>
          <input type="file" id="file-input" name="files[]" style="display:none" multiple onchange="handleFiles(this.files)">

          <!-- Seçilen dosya listesi -->
          <div class="file-list" id="file-list"></div>

          <input type="email" class="form-field" name="sender_email" placeholder="E-posta adresinizi giriniz">
          <input type="email" class="form-field" name="recipient_email" placeholder="Alıcı e-posta adresini giriniz" required>
          <textarea class="form-field" name="message" placeholder="Mesaj"></textarea>

          <div class="send-row">
            <button type="button" class="icon-btn" onclick="document.getElementById('file-input').click()" title="Dosya ekle">
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="#2979ff" stroke-width="2">
                <path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"/>
              </svg>
            </button>
            <button type="submit" class="send-btn">Yükle</button>
          </div>
        </form>
      </div>

      <!-- KOD SEKMESİ -->
      <div class="panel-section <?= $left_action === 'code' ? 'active' : '' ?>" id="sec-code">
        <form method="post">
          <?= csrfField() ?>
          <input type="hidden" name="action" value="check_code">
          <input type="text" name="share_code" class="form-field code-input" maxlength="8" placeholder="XXXXXXXX" autocomplete="off">
          <button type="submit" class="code-btn">🔍 Dosyayı Bul</button>
        </form>
        <div class="code-hint">
          Size gönderilmiş bir paylaşım kodunuz varsa buraya girerek dosyaya hesap açmadan erişebilirsiniz.
        </div>
      </div>

    </div>
  </aside>

  <!-- ORTA SLIDER -->
  <div class="center-area">
    <div class="slider-wrap" id="slider">
      <?php foreach ($slider_images as $i => $img): ?>
        <div class="slide <?= $i === 0 ? 'active' : '' ?>"
             style="background-image: url('<?= htmlspecialchars($img) ?>')"
             data-index="<?= $i ?>">
          <div class="slide-overlay"></div>
        </div>
      <?php endforeach; ?>

      <!-- Sadece indikatörler -->
      <div class="slide-indicators-wrap" id="indicators">
        <?php foreach ($slider_images as $j => $_): ?>
          <div class="indicator <?= $j === 0 ? 'active' : '' ?>" onclick="goSlide(<?= $j ?>)"></div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- SAĞ PANEL -->
  <div class="right-panel">
    <div class="right-body">
      <div class="brand">
        <div class="brand-logo">
          <svg class="brand-icon" viewBox="0 0 40 40" fill="none">
            <rect width="40" height="40" rx="10" fill="#2979ff"/>
            <path d="M10 28 L10 16 L20 10 L30 16 L30 28 Z" fill="none" stroke="white" stroke-width="1.5" stroke-linejoin="round"/>
            <path d="M16 28 L16 22 L24 22 L24 28" fill="none" stroke="white" stroke-width="1.5"/>
            <path d="M14 20 L20 17 L26 20" fill="none" stroke="white" stroke-width="1.5" stroke-linejoin="round"/>
          </svg>
          <div>
            <div class="brand-name">Data<span>Store</span></div>
          </div>
        </div>
        <div class="brand-tagline">Dosya Paylaşım Sistemi</div>
      </div>

      <?php if ($lockout): ?>
      <div class="lockout-container" data-remaining="<?= $lockout['remaining'] ?>" data-total="<?= $lockout['total'] ?>">
        <div class="lockout-icon">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="11" width="18" height="11" rx="2"/>
            <path d="M7 11V7a5 5 0 0110 0v4"/>
            <circle cx="12" cy="16" r="1.5"/>
            <line x1="12" y1="16" x2="12" y2="13"/>
          </svg>
        </div>
        <div class="lockout-title">Hesap Kilitlendi</div>
        <div class="lockout-text">Çok fazla hatalı giriş denemesi yapıldı.</div>
        <div class="lockout-bar-wrap">
          <div class="lockout-bar" id="lockout-bar"></div>
        </div>
        <div class="lockout-info">
          <span id="lockout-time"><?= formatLockoutTime($lockout['remaining']) ?></span>
          <span id="lockout-pct">%0</span>
        </div>
      </div>
      <?php else: ?>
      <form class="login-form" method="post">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="login">
        <div class="login-title">Kullanıcı Girişi</div>

        <?php if (isset($login_error)): ?>
          <div class="login-error"><?= htmlspecialchars($login_error) ?></div>
        <?php endif; ?>

        <div class="login-group">
          <svg class="login-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/>
          </svg>
          <input class="login-input" type="email" name="username" placeholder="E-posta" required>
        </div>

        <div class="login-group">
          <svg class="login-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/>
          </svg>
          <input class="login-input pw-field" type="password" name="password" id="pw-field" placeholder="Şifre" required>
          <button type="button" class="pw-eye" onclick="togglePw()">
            <svg id="eye-icon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>
            </svg>
          </button>
        </div>

        <div class="remember-row">
          <label><input type="checkbox" name="remember"> Beni Hatırla</label>
        </div>

        <button type="submit" class="login-btn">OTURUM AÇ</button>
      </form>
      <?php endif; ?>
    </div>

    <div class="right-footer">
      <div class="version-badge">v1.0.11</div>
    </div>
  </div>

</div>
<div class="toast-container" id="toast-container"></div>
<script>
const ALLOWED_EXTENSIONS = <?= json_encode(getAllowedExtensions()) ?>;
// ── Slider ──
let cur = 0;
const slides = document.querySelectorAll('.slide');
const indicators = document.querySelectorAll('.indicator');

function goSlide(n) {
  slides[cur]?.classList.remove('active');
  indicators[cur]?.classList.remove('active');
  cur = (n + slides.length) % slides.length;
  slides[cur]?.classList.add('active');
  indicators[cur]?.classList.add('active');
}
if (slides.length > 1) setInterval(() => goSlide(cur + 1), 5000);

// ── Tab ──
function switchTab(tab) {
  document.querySelectorAll('.tab-btn').forEach((b, i) => {
    b.classList.toggle('active', (i === 0 && tab === 'send') || (i === 1 && tab === 'code'));
  });
  document.querySelectorAll('.panel-section').forEach((s, i) => {
    s.classList.toggle('active', (i === 0 && tab === 'send') || (i === 1 && tab === 'code'));
  });
}

// ── Çoklu dosya yönetimi ──
let selectedFiles = new DataTransfer();

function handleFiles(newFiles) {
  for (const f of newFiles) {
    const ext = f.name.split('.').pop().toLowerCase();
    if (ext && !ALLOWED_EXTENSIONS.includes(ext)) {
      showToast('🔒 "' + f.name + '" dosya yolu güvenlik nedeniyle reddediliyor.');
      continue;
    }
    selectedFiles.items.add(f);
  }
  document.getElementById('file-input').files = selectedFiles.files;
  renderFileList();
}

function showToast(msg) {
  const c = document.getElementById('toast-container');
  if (!c) return;
  const t = document.createElement('div');
  t.className = 'toast toast-error';
  t.textContent = msg;
  c.appendChild(t);
  setTimeout(() => { if (t.parentNode) t.remove(); }, 4000);
}

function removeFile(index) {
  const dt = new DataTransfer();
  const files = selectedFiles.files;
  for (let i = 0; i < files.length; i++) {
    if (i !== index) dt.items.add(files[i]);
  }
  selectedFiles = dt;
  document.getElementById('file-input').files = selectedFiles.files;
  renderFileList();
}

function renderFileList() {
  const list = document.getElementById('file-list');
  const files = selectedFiles.files;
  list.innerHTML = '';
  if (files.length === 0) return;

  for (let i = 0; i < files.length; i++) {
    const f = files[i];
    const ext = f.name.split('.').pop().toLowerCase();
    const icons = { pdf:'📄', doc:'📝', docx:'📝', xls:'📊', xlsx:'📊', jpg:'🖼️', jpeg:'🖼️', png:'🖼️', gif:'🎞️', mp4:'🎬', mp3:'🎵', zip:'📦', rar:'📦' };
    const icon = icons[ext] || '📁';
    const size = f.size >= 1048576 ? (f.size/1048576).toFixed(1)+' MB' : (f.size/1024).toFixed(0)+' KB';

    const item = document.createElement('div');
    item.className = 'file-item';
    item.innerHTML =
      '<span class="file-item-icon">'+icon+'</span>' +
      '<span class="file-item-name" title="'+f.name+'">'+f.name+'</span>' +
      '<span class="file-item-size">'+size+'</span>' +
      '<button type="button" class="file-item-del" onclick="removeFile('+i+')" title="Kaldır">×</button>';
    list.appendChild(item);
  }
}

// Drag & drop
const zone = document.getElementById('upload-zone');
if (zone) {
  zone.addEventListener('dragover', e => { e.preventDefault(); zone.classList.add('drag-over'); });
  zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
  zone.addEventListener('drop', e => {
    e.preventDefault();
    zone.classList.remove('drag-over');
    handleFiles(e.dataTransfer.files);
  });
}

// Kod büyük harf
document.querySelector('[name="share_code"]')?.addEventListener('input', function() {
  this.value = this.value.toUpperCase();
});

// Şifre göster/gizle
function togglePw() {
  const f = document.getElementById('pw-field');
  const icon = document.getElementById('eye-icon');
  if (f.type === 'password') {
    f.type = 'text';
    icon.innerHTML = '<path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/>';
  } else {
    f.type = 'password';
    icon.innerHTML = '<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/>';
  }
}

// Lockout geri sayım
(function() {
  const c = document.querySelector('.lockout-container');
  if (!c) return;
  let r = parseInt(c.dataset.remaining), t = parseInt(c.dataset.total);
  function u() {
    if (r === 0) { location.reload(); return; }
    const p = Math.round((t - r) / t * 100);
    const b = document.getElementById('lockout-bar');
    if (b) b.style.width = p + '%';
    const pe = document.getElementById('lockout-pct');
    if (pe) pe.textContent = '%' + p;
    const te = document.getElementById('lockout-time');
    if (te) {
      const m = Math.floor(r / 60), s = r % 60;
      te.textContent = (m ? m + ' dakika ' : '') + s + ' saniye';
    }
    r--;
  }
  u(); setInterval(u, 1000);
})();
</script>
</body>
</html>
