<?php
// seller/login.php (tek dosya: inline CSS + JS)
// SOL görsel + SAĞ login — Etsy kalite giriş
declare(strict_types=1);

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

/* Fatal error yakala */
register_shutdown_function(function () {
  $e = error_get_last();
  if ($e && in_array($e['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR], true)) {
    header('Content-Type: text/plain; charset=utf-8');
    echo "FATAL ERROR:\n";
    print_r($e);
  }
});

/**
 * Görsel URL'lerini buraya gireceksin:
 */
define('LOGIN_LEFT_IMAGE_URL', 'https://sanatcidan.wanyweb.com/img/banner22.png'); // ✅ bunu değiştir

/* =========================
   app/ klasörünü otomatik bul
========================= */
function find_app_dir(string $startDir): ?string {
  $dir = realpath($startDir) ?: $startDir;
  for ($i = 0; $i < 10; $i++) {
    $candidate = $dir . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'auth.php';
    if (is_file($candidate)) return $dir . DIRECTORY_SEPARATOR . 'app';
    $parent = dirname($dir);
    if ($parent === $dir) break;
    $dir = $parent;
  }
  return null;
}

$appDir = find_app_dir(__DIR__);
if ($appDir === null) {
  http_response_code(500);
  header('Content-Type: text/plain; charset=utf-8');
  echo "app/ klasoru bulunamadi.\n";
  echo "Beklenen: (ust dizinlerden birinde) app/auth.php\n";
  echo "Suan: " . __DIR__ . "\n";
  exit;
}

/* Çekirdek */
require_once $appDir . '/db.php';
require_once $appDir . '/helpers.php';
require_once $appDir . '/auth.php';
require_once $appDir . '/csrf.php';

start_app_session();

/* PDO yakala (db.php farklı yapılarda olabilir) */
function app_pdo() {
  if (function_exists('pdo')) return pdo();
  if (function_exists('db'))  return db();
  if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO) return $GLOBALS['pdo'];
  throw new RuntimeException('PDO bulunamadı. app/db.php içinde pdo() veya db() olmalı ya da $pdo global olmalı.');
}

/* App name */
$appName = (function_exists('cfg') ? (string)(cfg()['app']['name'] ?? 'Sanatçı') : 'Sanatçı');

/* Zaten girişliyse (✅ seller kontrol) */
$u = function_exists('current_user') ? current_user() : null;
if ($u && (($u['role'] ?? '') === 'seller')) {
  // seller_id yoksa burada da tamamla
  if (empty($_SESSION['seller_id'])) {
    try {
      $pdo = app_pdo();
      $email = (string)($u['email'] ?? '');
      if ($email !== '') {
        $st = $pdo->prepare("SELECT id, firma_adi FROM sellers WHERE email = ? LIMIT 1");
        $st->execute([$email]);
        $row = $st->fetch(PDO::FETCH_ASSOC);
        if ($row) {
          $_SESSION['seller_id'] = (int)$row['id'];
          if (!empty($row['firma_adi'])) $_SESSION['firma_adi'] = (string)$row['firma_adi'];
        }
      }
    } catch (\Throwable $e) {
      // sessiz geç
    }
  }

  header('Location: ' . (function_exists('app_base') ? app_base('seller/dashboard.php') : 'dashboard.php'));
  exit;
}

/* Login */
$error = '';
$emailVal = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_verify($_POST['_csrf'] ?? null);

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

  if ($email === '' || $pass === '') {
    $error = 'E-posta ve şifre zorunlu.';
  } else {
    $res = login_attempt($email, $pass);

    if (empty($res['ok'])) {
      $error = (string)($res['err'] ?? 'Giriş başarısız. Bilgileri kontrol edin.');
    } else {
      // ✅ role uyuşmazsa: seller paneline alma
      $cu = current_user();
      if (!$cu || (($cu['role'] ?? '') !== 'seller')) {
        logout();
        $error = 'Bu hesap satıcı paneline yetkili değil.';
      } else {

        // ✅ KRİTİK FIX: seller_id oturuma yaz (sellers tablosundan)
        try {
          $pdo = app_pdo();
          $cuEmail = (string)($cu['email'] ?? $email);
          $st = $pdo->prepare("SELECT id, firma_adi FROM sellers WHERE email = ? LIMIT 1");
          $st->execute([$cuEmail]);
          $row = $st->fetch(PDO::FETCH_ASSOC);

          if ($row && !empty($row['id'])) {
            $_SESSION['seller_id'] = (int)$row['id'];
            if (!empty($row['firma_adi'])) $_SESSION['firma_adi'] = (string)$row['firma_adi'];
          } else {
            // sellers kaydı yoksa en azından fallback (bazı sayfalar seller_id arıyor)
            $_SESSION['seller_id'] = (int)($cu['id'] ?? 0);
          }
        } catch (\Throwable $e) {
          $_SESSION['seller_id'] = (int)($cu['id'] ?? 0);
        }

        // dashboard’da isim gözüksün
        $_SESSION['firma_adi'] = (string)($_SESSION['firma_adi'] ?? ($cu['name'] ?? 'Satıcı'));

        header('Location: ' . (function_exists('app_base') ? app_base('seller/dashboard.php') : 'dashboard.php'));
        exit;
      }
    }
  }
}

$csrf = csrf_token();
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <title>Giriş • <?= htmlspecialchars($appName, ENT_QUOTES, 'UTF-8') ?></title>

  <style>
    /* Nexa */
    @font-face{
      font-family:"Nexa";
      src:url("../assets/fonts/Nexa-Regular.woff2") format("woff2"),
          url("../assets/fonts/Nexa-Regular.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;
    }

    :root{
      --bg:#ffffff;
      --text:#0b0c0f;
      --muted:#5c6470;
      --line:#e6e8ee;
      --font:"Nexa", ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
    }

    *{box-sizing:border-box}
    html,body{height:100%}
    body{
      margin:0;
      font-family:var(--font);
      background:var(--bg);
      color:var(--text);
    }

    /* Layout */
    .layout{
      min-height:100vh;
      display:grid;
      grid-template-columns: 1.2fr 1fr;
    }

    .left{
      position:relative;
      overflow:hidden;
      background:#f3f4f7;
    }
    .left::before{
      content:"";
      position:absolute;
      inset:0;
      background-image: var(--left-image);
      background-size:cover;
      background-position:center;
      background-repeat:no-repeat;
      transform: scale(1.02);
    }
    .left::after{
      content:"";
      position:absolute;
      inset:0;
      background: linear-gradient(90deg, rgba(255,255,255,.04), rgba(255,255,255,.22));
    }

    .right{
      display:flex;
      justify-content:flex-start;
      align-items:center;
      padding: clamp(18px, 3vw, 48px);
      background:#fff;
    }

    /* Box yok: sadece genişlik + hizalama */
    .right-inner{
      width: min(720px, 100%);
      margin-left:auto; /* sağda dursun */
    }

    .title{
      margin:0;
      font-size: 46px;
      font-weight:800;
      letter-spacing:.2px;
      line-height:1.05;
    }
    .subtitle{
      margin:10px 0 0;
      color:var(--muted);
      font-size: 20px;
      line-height:1.35;
    }

    .alert{
      margin-top: 18px;
      padding: 16px 16px;
      border:1px solid #f1c7c7;
      border-radius: 18px;
      background:#fff5f5;
      color:#8b1d1d;
      font-weight:800;
      font-size: 18px;
    }

    form{
      margin-top: 26px;
      display:flex;
      flex-direction:column;
      gap: 18px;
    }

    label span{
      display:block;
      font-size: 18px;
      color: var(--muted);
      margin: 0 0 10px;
      font-weight:800;
      letter-spacing:.2px;
    }

    .field{position:relative;}

    input{
      width:100%;
      padding: 22px 22px 22px 64px;
      border-radius: 22px;
      border:1px solid var(--line);
      background:#fff;
      color:var(--text);
      outline:none;
      font-family:var(--font);
      font-size: 22px;
      font-weight:700;
    }
    input:focus{border-color:#111;}

    .icon{
      position:absolute;
      left: 22px;
      top: 50%;
      transform: translateY(-50%);
      width: 28px;
      height: 28px;
      color:#111;
      opacity:.9;
      pointer-events:none;
    }

    .btn{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap: 14px;
      padding: 22px 22px;
      border-radius: 26px;
      border:1px solid #111;
      background:#111;
      color:#fff;
      cursor:pointer;
      font-weight:800;
      font-family:var(--font);
      font-size: 22px;
      width: 100%;
    }
    .btn svg{width:28px; height:28px; color:#fff;}

    /* Mobil */
    @media (max-width: 980px){
      .layout{grid-template-columns: 1fr;}
      .left{min-height: 32vh;}
      .right{justify-content:center;}
      .right-inner{margin-left:0;}
      .title{font-size: 38px;}
      .subtitle{font-size: 18px;}
      input{font-size: 20px;}
      .btn{font-size: 20px;}
    }
  </style>

  <script defer src="https://unpkg.com/lucide@latest"></script>
  <script>
    window.addEventListener('DOMContentLoaded', () => {
      if (window.lucide) window.lucide.createIcons();

      const left = document.querySelector('.left');
      if (left) {
        const url = left.dataset.image || '';
        left.style.setProperty('--left-image', url ? `url("${url}")` : 'none');
      }

      const u = document.querySelector('input[name="email"]');
      const p = document.querySelector('input[name="password"]');
      if (u && !u.value) u.focus();
      else if (p) p.focus();
    });
  </script>
</head>

<body>
  <div class="layout">
    <!-- Sol görsel alanı -->
    <section class="left" data-image="<?= htmlspecialchars(LOGIN_LEFT_IMAGE_URL, ENT_QUOTES, 'UTF-8') ?>" aria-label="Görsel Alanı"></section>

    <!-- Sağ login alanı -->
    <section class="right">
      <div class="right-inner">

        <h1 class="title">Sanatçı Giriş</h1>
        <p class="subtitle">Satıcı Paneline Giriş Yapın.</p>

        <?php if ($error): ?>
          <div class="alert"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
        <?php endif; ?>

        <form method="post" autocomplete="on">
          <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf, ENT_QUOTES, 'UTF-8') ?>" />

          <label>
            <span>E-posta</span>
            <div class="field">
              <i class="icon" data-lucide="mail"></i>
              <input
                name="email"
                type="email"
                autocomplete="username"
                placeholder="E-posta adresinizi girin"
                value="<?= htmlspecialchars($emailVal, ENT_QUOTES, 'UTF-8') ?>"
                required
              />
            </div>
          </label>

          <label>
            <span>Şifre</span>
            <div class="field">
              <i class="icon" data-lucide="lock"></i>
              <input
                type="password"
                name="password"
                autocomplete="current-password"
                placeholder="Şifrenizi girin"
                required
              />
            </div>
          </label>

          <button class="btn" type="submit">
            <i data-lucide="log-in"></i>
            <span>Giriş Yap</span>
          </button>
        </form>

      </div>
    </section>
  </div>
</body>
</html>
