<?php
declare(strict_types=1);

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

/**
 * admin/login.php
 * ✅ Sade UI (Nexa + kart tasarım)
 * ✅ Mobil uyumlu
 * ✅ Provider görselleri 100x100
 * ✅ Setup (ilk admin) desteği korunur
 * ✅ Emoji yerine Lucide icon
 */

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

start_app_session();

$cfg   = app_config();
$err   = '';
$info  = '';
$setup = (($_GET['setup'] ?? '') === '1');

if ($setup && empty($cfg['setup_create_first_admin'])) {
  $err = 'Kurulum kapalı (config: setup_create_first_admin=false).';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_verify();

  $email = trim((string)($_POST['email'] ?? ''));
  $pass  = (string)($_POST['password'] ?? '');

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $err = 'Geçerli bir e-posta yaz.';
  } elseif (strlen($pass) < 8) {
    $err = 'Şifre en az 8 karakter olmalı.';
  } else {
    if ($setup) {
      if ($err === '') {
        $cnt = 0;
        try {
          $row = db()->query("SELECT COUNT(*) AS c FROM users")->fetch();
          $cnt = (int)($row['c'] ?? 0);
        } catch (Throwable $e) {
          $cnt = 0;
        }

        if ($cnt > 0) {
          $err = 'Kurulum zaten yapılmış (kullanıcı mevcut).';
        } else {
          $hash = password_hash($pass, PASSWORD_DEFAULT);
          $st = db()->prepare("INSERT INTO users(email,password_hash,role,is_active) VALUES(?,?, 'admin', 1)");
          $st->execute([$email, $hash]);
          $info = 'İlk admin oluşturuldu. Artık normal giriş yapabilirsin.';
        }
      }
    } else {
      $st = db()->prepare("SELECT id, password_hash, is_active FROM users WHERE email=? LIMIT 1");
      $st->execute([$email]);
      $u = $st->fetch();

      if (!$u || (int)$u['is_active'] !== 1 || !password_verify($pass, (string)$u['password_hash'])) {
        $err = 'E-posta veya şifre hatalı.';
      } else {
        $_SESSION['user_id'] = (int)$u['id'];
        header('Location: dashboard.php');
        exit;
      }
    }
  }
}

/** ✅ URL'leri sen gir */
$logoUrl   = 'https://ivr.wanyweb.com/assets/logo/wany22.png';
$provider1 = 'https://ivr.wanyweb.com/assets/logo/netbg.png';
$provider2 = 'https://ivr.wanyweb.com/assets/logo/wany21.png';
$provider3 = 'https://ivr.wanyweb.com/assets/logo/ercbg.png';
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <link rel="manifest" href="manifest.json" />
  <title>NETGSM Santral • Admin</title>

  <!-- Lucide -->
  <script src="https://unpkg.com/lucide@latest"></script>

  <style>
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/NexaRegular.woff2') format('woff2'),
           url('/assets/fonts/NexaRegular.woff') format('woff');
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/Nexa Bold.woff2') format('woff2'),
           url('/assets/fonts/Nexa Bold.woff') format('woff');
      font-weight: 700;
      font-style: normal;
      font-display: swap;
    }
    @font-face {
      font-family: 'Nexa';
      src: url('/assets/fonts/Nexa-Heavy.woff2') format('woff2'),
           url('/assets/fonts/Nexa-Heavy.woff') format('woff');
      font-weight: 800;
      font-style: normal;
      font-display: swap;
    }

    * { margin:0; padding:0; box-sizing:border-box; -webkit-tap-highlight-color: transparent; }
    body{
      font-family:'Nexa', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
      background:#ffffff;
      color:#000;
      min-height:100vh;
      padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);
    }
    input, button { font-size:16px; }

    .wrap{
      min-height:100vh;
      display:flex;
      align-items:center;
      justify-content:center;
      padding: 14px 10px;
    }
    .container{
      width:100%;
      max-width: 520px;
    }

    .topbar{
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:10px;
      margin-bottom: 10px;
      flex-wrap:wrap;
    }

    .pill{
      background:#f0f0f0;
      border:none;
      padding:8px 12px;
      border-radius:999px;
      font-size:13px;
      font-family:'Nexa', sans-serif;
      cursor:default;
      text-decoration:none;
      color:#000;
      font-weight:800;
      display:inline-flex;
      align-items:center;
      gap:8px;
      white-space:nowrap;
    }
    .pill.online{ background:#e8f5e9; color:#2e7d32; }
    .dot{ width:9px; height:9px; border-radius:999px; background:#2e7d32; display:inline-block; }

    .ico{ width:16px; height:16px; display:inline-block; }

    .card{
      background:#f8f8f8;
      border-radius:14px;
      padding:14px;
    }

    .brand{
      display:flex;
      align-items:center;
      justify-content:center;
      padding: 6px 0 10px 0;
    }
    .brand img{
      height:64px;
      width:auto;
      object-fit:contain;
      border-radius:12px;
    }
    .title{
      text-align:center;
      font-size:18px;
      font-weight:900;
      letter-spacing:-0.2px;
      margin-top:6px;
    }
    .subtitle{
      text-align:center;
      font-size:12px;
      font-weight:800;
      color:#666;
      margin-top:4px;
      line-height:1.35;
    }

    .alert{
      margin-top:12px;
      border-radius:12px;
      padding:12px;
      font-weight:800;
      font-size:13px;
      line-height:1.35;
      background:#eeeeee;
      color:#333;
      display:flex;
      gap:10px;
      align-items:flex-start;
    }
    .alert .ai{ width:18px; height:18px; flex:0 0 auto; margin-top:1px; }
    .alert.err{ background:#ffebee; color:#c62828; }
    .alert.ok{ background:#e8f5e9; color:#2e7d32; }

    .form{
      margin-top:12px;
    }
    .field{
      margin-top:10px;
    }
    .label{
      font-size:12px;
      color:#666;
      font-weight:900;
      padding:0 2px 6px 2px;
    }
    .inrow{
      display:flex;
      align-items:center;
      gap:8px;
      background:#fff;
      border:1px solid #e0e0e0;
      border-radius:20px;
      padding:10px 12px;
    }
    .inrow:focus-within{ border-color:#d0d0d0; }
    .inrow input{
      width:100%;
      border:none;
      outline:none;
      font-family:'Nexa', sans-serif;
      background:transparent;
      font-weight:800;
      color:#111;
    }
    .inrow input::placeholder{ color:#bbb; font-weight:800; }

    .icon{
      width:30px;
      height:30px;
      border-radius:10px;
      background:#f0f0f0;
      display:flex;
      align-items:center;
      justify-content:center;
      flex:0 0 auto;
      color:#444;
    }
    .icon svg{ width:18px; height:18px; }

    .eye{
      border:none;
      background:#f0f0f0;
      border-radius:12px;
      padding:10px 12px;
      cursor:pointer;
      font-family:'Nexa', sans-serif;
      font-weight:900;
      color:#444;
      flex:0 0 auto;
      display:inline-flex;
      align-items:center;
      gap:8px;
    }
    .eye svg{ width:18px; height:18px; }

    .btn{
      width:100%;
      margin-top:14px;
      padding:12px 14px;
      border:none;
      border-radius:14px;
      font-family:'Nexa', sans-serif;
      font-weight:900;
      font-size:15px;
      cursor:pointer;
      background:#111;
      color:#fff;
      display:flex;
      align-items:center;
      justify-content:center;
      gap:10px;
    }
    .btn:active{ transform: scale(.995); }
    .btn[disabled]{ opacity:.75; cursor:not-allowed; }

    .btn svg{ width:18px; height:18px; }

    .spin{
      width:16px;
      height:16px;
      border-radius:999px;
      border:2px solid rgba(255,255,255,.35);
      border-top-color:#fff;
      animation: spin .8s linear infinite;
    }
    @keyframes spin{ to { transform: rotate(360deg); } }

    .providers{
      margin-top:14px;
      background:#f0f0f0;
      border-radius:12px;
      padding:12px;
    }
    .providers .pt{
      text-align:center;
      font-size:12px;
      color:#666;
      font-weight:900;
      margin-bottom:10px;
      display:flex;
      align-items:center;
      justify-content:center;
      gap:8px;
    }
    .prow{
      display:flex;
      align-items:center;
      justify-content:center;
      gap:14px;
      flex-wrap:wrap;
    }
    .providerImg{
      width:100px;
      height:100px;
      object-fit:contain;
      display:block;
      border-radius:14px;
      background:#fff;
      border:1px solid #e6e6e6;
      padding:10px;
    }

    .footer{
      text-align:center;
      padding:14px 0 0 0;
      color:#999;
      font-size:12px;
      margin-top:10px;
      font-weight:800;
    }

    .hintline{
      margin-top:10px;
      text-align:center;
      font-size:12px;
      color:#666;
      font-weight:900;
    }
    .hintline a{
      color:#111;
      text-decoration:none;
      background:#f0f0f0;
      padding:6px 10px;
      border-radius:999px;
      display:inline-flex;
      align-items:center;
      gap:8px;
      margin-top:6px;
    }
    .hintline a svg{ width:16px; height:16px; }

    @media (max-width:360px){
      .providerImg{ width:92px; height:92px; }
    }
  </style>
</head>

<body>
  <div class="wrap">
    <div class="container">

      <div class="topbar">
        <span class="pill online">
          <span class="dot"></span>
          <i data-lucide="activity" class="ico"></i>
          API Online
        </span>

        
      </div>

      <div class="card" id="loginCard">
        <div class="brand">
          <?php if (!empty($logoUrl)): ?>
            <img src="<?= e($logoUrl) ?>" alt="Logo">
          <?php endif; ?>
        </div>

        <div class="title"><?= $setup ? 'İlk Admini Oluştur' : 'Giriş Yap' ?></div>
        <div class="subtitle">
          <?= $setup ? 'Kurulum için ilk admin hesabını oluştur.' : 'Paneli kullanmak için giriş yap.' ?>
        </div>

        <?php if ($err): ?>
          <div class="alert err">
            <i data-lucide="alert-triangle" class="ai"></i>
            <div><?= e($err) ?></div>
          </div>
        <?php endif; ?>

        <?php if ($info): ?>
          <div class="alert ok">
            <i data-lucide="check-circle-2" class="ai"></i>
            <div><?= e($info) ?></div>
          </div>
        <?php endif; ?>

        <form class="form" method="post" autocomplete="on" id="loginForm" novalidate>
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"/>

          <div class="field">
            <div class="label">E-posta</div>
            <div class="inrow">
              <div class="icon">
                <i data-lucide="mail"></i>
              </div>
              <input
                name="email"
                type="email"
                inputmode="email"
                autocomplete="email"
                autocapitalize="none"
                spellcheck="false"
                required
                placeholder="admin@firma.com"
              />
            </div>
          </div>

          <div class="field">
            <div class="label">Şifre</div>
            <div class="inrow">
              <div class="icon">
                <i data-lucide="lock"></i>
              </div>

              <input
                id="passwordInput"
                name="password"
                type="password"
                autocomplete="current-password"
                required
                minlength="8"
                placeholder="••••••••"
              />

              <button type="button" class="eye" id="togglePass" aria-label="Şifreyi göster/gizle">
                <i id="eyeIcon" data-lucide="eye"></i>
                <span id="eyeText">Göster</span>
              </button>
            </div>
          </div>

          <button id="loginBtn" class="btn" type="submit">
            <span id="btnSpin" style="display:none;" class="spin"></span>
            <i id="btnIcon" data-lucide="<?= $setup ? 'sparkles' : 'log-in' ?>"></i>
            <span id="btnText"><?= $setup ? 'Oluştur' : 'Giriş Yap' ?></span>
          </button>
        </form>

        <div class="providers">
          <div class="pt">
            <i data-lucide="boxes" class="ico"></i>
            API Sağlayıcıları ve Yazılım
          </div>
          <div class="prow">
            <?php if (!empty($provider1)): ?><img class="providerImg" src="<?= e($provider1) ?>" alt="Provider 1"><?php endif; ?>
            <?php if (!empty($provider2)): ?><img class="providerImg" src="<?= e($provider2) ?>" alt="Provider 2"><?php endif; ?>
            <?php if (!empty($provider3)): ?><img class="providerImg" src="<?= e($provider3) ?>" alt="Provider 3"><?php endif; ?>
          </div>
        </div>

        

      <div class="footer">
        © <?= date('Y') ?> • NETGSM Santral MVP by Wany Technologies
      </div>

    </div>
  </div>

  <script>
    // lucide init
    lucide.createIcons();

    const pass = document.getElementById('passwordInput');
    const toggle = document.getElementById('togglePass');
    const eyeIcon = document.getElementById('eyeIcon');
    const eyeText = document.getElementById('eyeText');

    toggle?.addEventListener('click', () => {
      const isText = pass.type === 'text';
      pass.type = isText ? 'password' : 'text';

      if (eyeText) eyeText.textContent = isText ? 'Göster' : 'Gizle';
      if (eyeIcon) eyeIcon.setAttribute('data-lucide', isText ? 'eye' : 'eye-off');

      lucide.createIcons();

      pass.focus({ preventScroll: true });
      try { pass.setSelectionRange(pass.value.length, pass.value.length); } catch (e) {}
    });

    const form = document.getElementById('loginForm');
    const btn = document.getElementById('loginBtn');
    const btnText = document.getElementById('btnText');
    const spin = document.getElementById('btnSpin');
    const card = document.getElementById('loginCard');
    const btnIcon = document.getElementById('btnIcon');

    <?php if (!empty($err)): ?>
      // küçük bir titreşim efekti (sade)
      setTimeout(() => {
        card.style.transform = 'translateX(-4px)';
        setTimeout(() => card.style.transform = 'translateX(4px)', 70);
        setTimeout(() => card.style.transform = 'translateX(-3px)', 140);
        setTimeout(() => card.style.transform = 'translateX(3px)', 210);
        setTimeout(() => card.style.transform = 'translateX(0)', 280);
      }, 80);
    <?php endif; ?>

    form?.addEventListener('submit', () => {
      if (!btn) return;
      btn.disabled = true;
      if (spin) spin.style.display = 'inline-block';
      if (btnText) btnText.textContent = 'Gönderiliyor...';
      if (btnIcon) btnIcon.style.display = 'none';
    });
  </script>
</body>
</html>
