<?php
declare(strict_types=1);

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

require_once __DIR__ . '/../lib/db.php';

// helpers yoksa e() fallback
if (!function_exists('e')) {
  function e(string $s): string { return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

$db = db();

// kullanıcı sayısı
$exists = 0;
$r = $db->query("SELECT COUNT(*) c FROM users");
if ($r && ($row = $r->fetch_assoc())) $exists = (int)$row['c'];

$err = '';
$ok  = '';

// POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim((string)($_POST['username'] ?? ''));
  $pass  = (string)($_POST['pass'] ?? '');

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $err = 'Geçerli e-posta gir.';
  } else if (strlen($pass) < 6) {
    $err = 'Şifre en az 6 karakter.';
  } else {
    // aynı e-posta var mı?
    $stmt = $db->prepare("SELECT id FROM users WHERE username = ? LIMIT 1");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();
    $already = ($stmt->num_rows > 0);
    $stmt->close();

    if ($already) {
      $err = 'Bu e-posta zaten kayıtlı.';
    } else {
      $hash = password_hash($pass, PASSWORD_DEFAULT);
      $now  = function_exists('now_ts') ? now_ts() : date('Y-m-d H:i:s');

      $stmt = $db->prepare("INSERT INTO users (username, password_hash, created_at) VALUES (?,?,?)");
      $stmt->bind_param('sss', $email, $hash, $now);
      if ($stmt->execute()) {
        $ok = 'Kullanıcı oluşturuldu. Şimdi login.php ile giriş yap.';
        $exists++;
      } else {
        $err = 'DB hata: kullanıcı eklenemedi.';
      }
      $stmt->close();
    }
  }
}

// son kullanıcılar (opsiyonel)
$users = [];
$qr = $db->query("SELECT username, created_at FROM users ORDER BY id DESC LIMIT 25");
if ($qr) {
  while ($row = $qr->fetch_assoc()) $users[] = $row;
}
?>
<!doctype html>
<html lang="tr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Kullanıcı Oluştur</title>
<style>
  body{margin:0;font-family:system-ui;background:#0b1220;color:#fff;min-height:100vh;display:grid;place-items:center;padding:18px}
  .card{width:min(520px,94vw);background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.12);border-radius:18px;padding:16px}
  .h{font-weight:900;letter-spacing:.08em}
  input{width:100%;padding:12px 12px;border-radius:14px;border:1px solid rgba(255,255,255,.14);background:rgba(0,0,0,.25);color:#fff;outline:none}
  button{width:100%;margin-top:10px;padding:12px;border-radius:14px;border:0;background:linear-gradient(135deg,#1d4ed8,#60a5fa);color:#fff;font-weight:900;letter-spacing:.06em;cursor:pointer}
  .msg{margin-top:10px;font-size:13px;opacity:.92;line-height:1.35}
  .muted{opacity:.75}
  hr{border:0;border-top:1px solid rgba(255,255,255,.12);margin:14px 0}
  .list{margin-top:8px}
  .item{display:flex;justify-content:space-between;gap:10px;padding:8px 10px;border-radius:12px;border:1px solid rgba(255,255,255,.10);background:rgba(0,0,0,.16);margin-top:8px}
  .item b{font-size:13px}
  .item span{font-size:12px;opacity:.7;white-space:nowrap}
  .pill{display:inline-block;margin-top:10px;font-size:12px;padding:6px 10px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(0,0,0,.18);opacity:.95}
</style>
</head>
<body>
  <div class="card">
    <div class="h">KULLANICI OLUŞTUR</div>
    <div class="msg muted">Giriş gerekmeden yeni kullanıcı ekleyebilirsin.</div>

    <?php if($err): ?><div class="msg" style="color:#fca5a5"><?= e($err) ?></div><?php endif; ?>
    <?php if($ok): ?><div class="msg" style="color:#86efac"><?= e($ok) ?></div><?php endif; ?>

    <form method="post" autocomplete="off">
      <div style="margin-top:10px"><input name="username" placeholder="E-posta"></div>
      <div style="margin-top:10px"><input name="pass" type="password" placeholder="Şifre (en az 6 karakter)"></div>
      <button type="submit">KULLANICI OLUŞTUR</button>
    </form>

    <div class="pill">Toplam kullanıcı: <b><?= (int)$exists ?></b></div>

    <?php if (!empty($users)): ?>
      <hr>
      <div class="msg muted">Son kayıtlı kullanıcılar (en fazla 25):</div>
      <div class="list">
        <?php foreach ($users as $u): ?>
          <div class="item">
            <b><?= e((string)$u['username']) ?></b>
            <span><?= e((string)$u['created_at']) ?></span>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</body>
</html>
