<?php
declare(strict_types=1);

/**
 * seller/ilan-duzenle.php
 * - ✅ DB: ilanlar + ilan_gorseller (SQL dump ile uyumlu)
 * - ✅ Satıcı giriş kontrolü (require_role('seller'))
 * - ✅ Sadece kendi ilanını düzenler (id + seller_id check)
 * - ✅ Görsel ekleme (URL), kapak seçme, görsel silme
 * - ✅ Önizleme: açıklama var + gereksiz uzama yok (fix)
 */

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

require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/auth.php';

start_app_session();
$u = require_role('seller');
$sellerId = (int)$u['id'];

$base   = $base   ?? (function_exists('app_base') ? app_base('seller/') : '/seller/');
$active = 'ilanlar';

/* Sidebar */
include __DIR__ . '/../app/sidebar.php';

/* =========================
   Helpers
========================= */
function normalize_status(string $s): string {
  $x = mb_strtolower(trim($s));
  if ($x === '') return 'pasif';
  return match(true){
    in_array($x, ['aktif','active','published','1','on'], true) => 'aktif',
    in_array($x, ['pasif','inactive','draft','0','off'], true)  => 'pasif',
    in_array($x, ['taslak','draft'], true) => 'taslak',
    default => $x
  };
}

function durum_pill(string $durum): array {
  $d = normalize_status($durum);
  return match($d){
    'aktif'  => ['Aktif',  'bg-emerald-100 text-emerald-800 border border-emerald-200'],
    'pasif'  => ['Pasif',  'bg-slate-100 text-slate-700 border border-slate-200'],
    'taslak' => ['Taslak', 'bg-amber-100 text-amber-800 border border-amber-200'],
    default  => [ucfirst($durum ?: '—'), 'bg-gray-100 text-gray-700 border border-gray-200'],
  };
}

function parse_money(string $s): float {
  $s = trim($s);
  if ($s === '') return 0.0;
  $s = str_replace(['₺','TRY','try','TL','tl',' '], '', $s);
  // TR format: 52.000,00 -> 52000.00
  $s = str_replace('.', '', $s);
  $s = str_replace(',', '.', $s);
  return (float)$s;
}

function to_int_or_null(string $s): ?int {
  $s = trim($s);
  if ($s === '') return null;
  return (int)$s;
}

function to_float_or_null(string $s): ?float {
  $s = trim($s);
  if ($s === '') return null;
  $s = str_replace(',', '.', $s);
  return (float)$s;
}

/* =========================
   Input
========================= */
$ilanId = (int)($_GET['id'] ?? 0);
if ($ilanId <= 0) {
  http_response_code(400);
  echo '<div style="padding:24px;font-family:system-ui">Geçersiz ilan id.</div>';
  exit;
}

$flash = '';
$errors = [];

/* =========================
   Fetch ilan + images
========================= */
function fetch_ilan(int $ilanId, int $sellerId): ?array {
  $st = db()->prepare("SELECT * FROM ilanlar WHERE id=? AND seller_id=? LIMIT 1");
  $st->execute([$ilanId, $sellerId]);
  $row = $st->fetch();
  return $row ?: null;
}

function fetch_images(int $ilanId): array {
  $st = db()->prepare("SELECT id, ilan_id, url, is_cover, sort_order, created_at
                       FROM ilan_gorseller
                       WHERE ilan_id=?
                       ORDER BY is_cover DESC, sort_order ASC, id ASC");
  $st->execute([$ilanId]);
  return $st->fetchAll() ?: [];
}

$ilan = fetch_ilan($ilanId, $sellerId);
if (!$ilan) {
  http_response_code(404);
  echo '<div style="padding:24px;font-family:system-ui">Bu ilan bulunamadı veya size ait değil.</div>';
  exit;
}
$images = fetch_images($ilanId);

$coverUrl = '';
if (!empty($images)) {
  foreach ($images as $im) {
    if ((int)$im['is_cover'] === 1) { $coverUrl = (string)$im['url']; break; }
  }
  if ($coverUrl === '') $coverUrl = (string)$images[0]['url'];
}
if ($coverUrl === '') $coverUrl = 'https://picsum.photos/seed/ilan-'.$ilanId.'/800/600';

/* =========================
   POST actions
========================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = (string)($_POST['action'] ?? 'save');

  /* İlanı sil */
  if ($action === 'delete_ilan') {
    try {
      db()->prepare("DELETE FROM ilan_gorseller WHERE ilan_id=?")->execute([$ilanId]);
      db()->prepare("DELETE FROM ilanlar WHERE id=? AND seller_id=? LIMIT 1")->execute([$ilanId, $sellerId]);
      header('Location: ilanlar.php?deleted=1');
      exit;
    } catch (Throwable $e) {
      $flash = 'Silme sırasında hata oluştu.';
    }
  }

  /* Kapak seç */
  if ($action === 'set_cover') {
    $imgId = (int)($_POST['image_id'] ?? 0);
    if ($imgId > 0) {
      try {
        // güvenlik: image bu ilana ait mi?
        $chk = db()->prepare("SELECT id FROM ilan_gorseller WHERE id=? AND ilan_id=? LIMIT 1");
        $chk->execute([$imgId, $ilanId]);
        if ($chk->fetch()) {
          db()->prepare("UPDATE ilan_gorseller SET is_cover=0 WHERE ilan_id=?")->execute([$ilanId]);
          db()->prepare("UPDATE ilan_gorseller SET is_cover=1 WHERE id=? AND ilan_id=?")->execute([$imgId, $ilanId]);
          $flash = 'Kapak görseli güncellendi.';
        }
      } catch (Throwable $e) {
        $flash = 'Kapak seçme sırasında hata oluştu.';
      }
    }
  }

  /* Görsel sil */
  if ($action === 'delete_image') {
    $imgId = (int)($_POST['image_id'] ?? 0);
    if ($imgId > 0) {
      try {
        // silinecek kapak mı?
        $st = db()->prepare("SELECT is_cover FROM ilan_gorseller WHERE id=? AND ilan_id=? LIMIT 1");
        $st->execute([$imgId, $ilanId]);
        $row = $st->fetch();

        db()->prepare("DELETE FROM ilan_gorseller WHERE id=? AND ilan_id=?")->execute([$imgId, $ilanId]);

        // eğer kapak silindiyse, ilk görseli kapak yap
        if ($row && (int)$row['is_cover'] === 1) {
          $first = db()->prepare("SELECT id FROM ilan_gorseller WHERE ilan_id=? ORDER BY sort_order ASC, id ASC LIMIT 1");
          $first->execute([$ilanId]);
          $f = $first->fetch();
          if ($f) db()->prepare("UPDATE ilan_gorseller SET is_cover=1 WHERE id=? AND ilan_id=?")->execute([(int)$f['id'], $ilanId]);
        }

        $flash = 'Görsel silindi.';
      } catch (Throwable $e) {
        $flash = 'Görsel silme sırasında hata oluştu.';
      }
    }
  }

  /* Yeni görsel URL ekle */
  if ($action === 'add_images') {
    $raw = (string)($_POST['new_urls'] ?? '');
    $lines = preg_split('/\r\n|\r|\n/', $raw) ?: [];
    $urls = [];
    foreach ($lines as $ln) {
      $u1 = trim($ln);
      if ($u1 === '') continue;
      if (mb_strlen($u1) > 255) continue;
      $urls[] = $u1;
    }

    if (!empty($urls)) {
      try {
        $mx = db()->prepare("SELECT COALESCE(MAX(sort_order),0) AS mx FROM ilan_gorseller WHERE ilan_id=?");
        $mx->execute([$ilanId]);
        $maxSort = (int)(($mx->fetch()['mx'] ?? 0));

        $ins = db()->prepare("INSERT INTO ilan_gorseller (ilan_id, url, is_cover, sort_order, created_at)
                              VALUES (?,?,?,?,NOW())");

        foreach ($urls as $i => $u2) {
          $sort = $maxSort + $i + 1;
          $ins->execute([$ilanId, $u2, 0, $sort]);
        }

        // hiç kapak yoksa ilk ekleneni kapak yap
        $chk = db()->prepare("SELECT COUNT(*) c FROM ilan_gorseller WHERE ilan_id=? AND is_cover=1");
        $chk->execute([$ilanId]);
        $hasCover = (int)($chk->fetch()['c'] ?? 0);
        if ($hasCover === 0) {
          $first = db()->prepare("SELECT id FROM ilan_gorseller WHERE ilan_id=? ORDER BY sort_order ASC, id ASC LIMIT 1");
          $first->execute([$ilanId]);
          $f = $first->fetch();
          if ($f) db()->prepare("UPDATE ilan_gorseller SET is_cover=1 WHERE id=? AND ilan_id=?")->execute([(int)$f['id'], $ilanId]);
        }

        $flash = 'Yeni görseller eklendi.';
      } catch (Throwable $e) {
        $flash = 'Görsel eklerken hata oluştu.';
      }
    } else {
      $flash = 'Eklemek için en az 1 URL girin.';
    }
  }

  /* Kaydet (ilan güncelle) */
  if ($action === 'save') {
    $baslik   = trim((string)($_POST['baslik'] ?? ''));
    $kategori = trim((string)($_POST['kategori'] ?? 'Genel'));
    $durum    = normalize_status((string)($_POST['durum'] ?? 'pasif'));
    $fiyat    = parse_money((string)($_POST['fiyat'] ?? '0'));
    $stok     = (int)($_POST['stok'] ?? 0);
    $aciklama = trim((string)($_POST['aciklama'] ?? ''));

    $kondisyon = trim((string)($_POST['kondisyon'] ?? ''));
    $kondisyon = ($kondisyon === '') ? null : $kondisyon;

    $yil = to_int_or_null((string)($_POST['yil'] ?? ''));
    $genislik = to_float_or_null((string)($_POST['genislik_cm'] ?? ''));
    $yukseklik = to_float_or_null((string)($_POST['yukseklik_cm'] ?? ''));
    $derinlik = to_float_or_null((string)($_POST['derinlik_cm'] ?? ''));

    $materyaller = trim((string)($_POST['materyaller'] ?? ''));
    $materyaller = ($materyaller === '') ? null : $materyaller;

    $kargoUcretiRaw = trim((string)($_POST['kargo_ucreti'] ?? ''));
    $kargo_ucreti = ($kargoUcretiRaw === '') ? null : parse_money($kargoUcretiRaw);

    $teslim_suresi = trim((string)($_POST['teslim_suresi'] ?? ''));
    $teslim_suresi = ($teslim_suresi === '') ? null : mb_substr($teslim_suresi, 0, 60);

    $delivery = $_POST['teslimat'] ?? [];
    $delivery = is_array($delivery) ? array_values(array_filter(array_map('trim', $delivery), fn($v)=>$v!=='')) : [];
    $teslimat_json = empty($delivery) ? null : json_encode($delivery, JSON_UNESCAPED_UNICODE);

    if ($baslik === '') $errors[] = 'Başlık zorunlu.';
    if ($stok < 0) $stok = 0;

    $allowedDurum = ['aktif','pasif','taslak'];
    if (!in_array($durum, $allowedDurum, true)) $durum = 'pasif';

    if (empty($errors)) {
      try {
        $sql = "UPDATE ilanlar SET
                  baslik=?,
                  kategori=?,
                  fiyat=?,
                  stok=?,
                  durum=?,
                  aciklama=?,
                  kondisyon=?,
                  yil=?,
                  genislik_cm=?,
                  yukseklik_cm=?,
                  derinlik_cm=?,
                  materyaller=?,
                  kargo_ucreti=?,
                  teslim_suresi=?,
                  teslimat_yontemleri_json=?,
                  updated_at=NOW()
                WHERE id=? AND seller_id=?
                LIMIT 1";
        $st = db()->prepare($sql);
        $st->execute([
          $baslik,
          ($kategori !== '' ? $kategori : 'Genel'),
          number_format($fiyat, 2, '.', ''),
          $stok,
          $durum,
          $aciklama,
          $kondisyon,
          $yil,
          $genislik,
          $yukseklik,
          $derinlik,
          $materyaller,
          ($kargo_ucreti === null ? null : number_format((float)$kargo_ucreti, 2, '.', '')),
          $teslim_suresi,
          $teslimat_json,
          $ilanId,
          $sellerId
        ]);

        $flash = 'İlan kaydedildi.';
      } catch (Throwable $e) {
        $flash = 'Kaydetme sırasında hata oluştu.';
      }
    }
  }

  // güncel verileri tekrar çek
  $ilan = fetch_ilan($ilanId, $sellerId) ?: $ilan;
  $images = fetch_images($ilanId);

  $coverUrl = '';
  if (!empty($images)) {
    foreach ($images as $im) {
      if ((int)$im['is_cover'] === 1) { $coverUrl = (string)$im['url']; break; }
    }
    if ($coverUrl === '') $coverUrl = (string)$images[0]['url'];
  }
  if ($coverUrl === '') $coverUrl = 'https://picsum.photos/seed/ilan-'.$ilanId.'/800/600';
}

/* =========================
   Derived
========================= */
$durum = normalize_status((string)($ilan['durum'] ?? 'pasif'));
[$dLabel, $dClass] = durum_pill($durum);

$baslik   = (string)($ilan['baslik'] ?? '');
$kategori = (string)($ilan['kategori'] ?? 'Genel');
$fiyat    = (float)($ilan['fiyat'] ?? 0);
$stok     = (int)($ilan['stok'] ?? 0);
$aciklama = (string)($ilan['aciklama'] ?? '');

$goruntulenme = (int)($ilan['goruntulenme'] ?? 0);
$favori = (int)($ilan['favori_sayisi'] ?? 0);

$createdAt = (string)($ilan['created_at'] ?? '');
$updatedAt = (string)($ilan['updated_at'] ?? '');

$kondisyon = (string)($ilan['kondisyon'] ?? '');
$yil = (string)($ilan['yil'] ?? '');
$genislik_cm = (string)($ilan['genislik_cm'] ?? '');
$yukseklik_cm = (string)($ilan['yukseklik_cm'] ?? '');
$derinlik_cm = (string)($ilan['derinlik_cm'] ?? '');
$materyaller = (string)($ilan['materyaller'] ?? '');
$kargo_ucreti = (string)($ilan['kargo_ucreti'] ?? '');
$teslim_suresi = (string)($ilan['teslim_suresi'] ?? '');

$teslimat_json = (string)($ilan['teslimat_yontemleri_json'] ?? '');
$teslimat_arr = [];
if ($teslimat_json !== '') {
  $decoded = json_decode($teslimat_json, true);
  if (is_array($decoded)) $teslimat_arr = $decoded;
}
$allDelivery = ['Kargo', 'Elden Teslim', 'Kurye', 'Dijital Teslim'];
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8" />
  <title>Satıcı Paneli — İlan Düzenle</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <script defer src="https://unpkg.com/lucide@latest"></script>

  <style>
    :root{
      --primary: #000000;
      --primary-gradient: linear-gradient(135deg, #000000 0%, #2D2D2D 100%);
      --card-gradient: linear-gradient(180deg, #FFFFFF 0%, #FCFCFC 100%);
      --accent: #7C3AED;

      --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.04);
      --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.08);
      --shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.12);
      --shadow-xl: 0 16px 48px rgba(0, 0, 0, 0.16);

      --radius-sm: 6px;
      --radius-md: 10px;
      --radius-lg: 14px;
      --radius-xl: 18px;
      --radius-full: 9999px;

      --transition: all 0.25s cubic-bezier(0.4,0,0.2,1);
    }

    * { font-family: 'Inter', system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
    html, body {
      height: 100%;
      background: linear-gradient(135deg, #F8FAFC 0%, #F1F5F9 100%);
      color: #0F172A;
      overflow-x: hidden;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }
    .no-x { overflow-x: hidden; max-width: 100vw; }

    .main-container{
      width:100%;
      min-height:100dvh;
      margin-left: var(--sidebar-width, 0);
      transition: margin-left .3s ease;
      display:flex;
      flex-direction:column;
    }
    @media(min-width:1024px){
      .main-container{
        margin-left: var(--sidebar-width, 280px);
        width: calc(100% - var(--sidebar-width, 280px));
      }
    }

    .page-content{
      flex:1;
      max-width:100%;
      margin:0;
      padding: 1.25rem 1rem;
    }
    @media(min-width:768px){ .page-content{ padding: 1.5rem 1.25rem; } }
    @media(min-width:1024px){ .page-content{ padding: 2rem; } }

    /* ✅ FIX: kolonu uzatmayı engelle */
    .editor-grid{
      display:flex;
      flex-direction:column;
      gap: 1.25rem;
      align-items: stretch;
    }
    @media(min-width:1024px){
      .editor-grid{
        flex-direction:row;
        gap: 1.5rem;
        align-items:flex-start; /* ✅ önemli */
      }
    }

    .preview-col{ width:100%; }
    @media(min-width:1024px){
      .preview-col{
        width: 320px;
        flex: 0 0 320px;
        position: sticky;
        top: 1.25rem;
        align-self:flex-start;
      }
    }

    .form-col{ width:100%; flex:1; min-width:0; }
    .right-col{ width:100%; }
    @media(min-width:1024px){
      .right-col{ width: 320px; flex: 0 0 320px; }
    }

    .card{
      background: var(--card-gradient);
      border-radius: var(--radius-xl);
      border:1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
    }
    .card-pad{ padding: 1.25rem; }
    @media(min-width:768px){ .card-pad{ padding: 1.5rem; } }

    .page-header{
      display:flex;
      flex-direction:column;
      gap: .75rem;
      margin-bottom: 1rem;
    }
    @media(min-width:768px){
      .page-header{
        flex-direction:row;
        align-items:center;
        justify-content:space-between;
      }
    }
    .page-title{ font-size:1.35rem; font-weight:900; letter-spacing:-.02em; }
    .page-subtitle{ font-size:.85rem; color:#64748B; font-weight:600; }

    .btn{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap:.5rem;
      padding:.55rem 1rem;
      border-radius: var(--radius-md);
      font-weight:700;
      font-size:.8125rem;
      transition: var(--transition);
      border: none;
      cursor:pointer;
      text-decoration:none;
      white-space:nowrap;
    }
    .btn-primary{
      background: var(--primary-gradient);
      color:#fff;
      box-shadow: 0 4px 12px rgba(0,0,0,.12);
    }
    .btn-primary:hover{ transform: translateY(-1px); box-shadow: 0 6px 18px rgba(0,0,0,.18); }
    .btn-secondary{
      background:#fff;
      color:#334155;
      border:1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
    }
    .btn-secondary:hover{ background:#F8FAFC; border-color:#CBD5E1; transform: translateY(-1px); box-shadow: var(--shadow-md); }
    .btn-danger{
      background: rgba(239,68,68,.10);
      color:#B91C1C;
      border:1px solid rgba(239,68,68,.25);
    }
    .btn-danger:hover{ background: rgba(239,68,68,.14); transform: translateY(-1px); box-shadow: var(--shadow-md); }

    .flash{
      border-radius: var(--radius-lg);
      padding: .875rem 1rem;
      margin-bottom: 1rem;
      display:flex;
      gap:.625rem;
      align-items:flex-start;
      border: 1px solid rgba(16,185,129,.2);
      background: linear-gradient(135deg, rgba(16,185,129,.10), rgba(16,185,129,.05));
    }
    .err{
      border-radius: var(--radius-lg);
      padding: .875rem 1rem;
      margin-bottom: 1rem;
      display:flex;
      gap:.625rem;
      align-items:flex-start;
      border: 1px solid rgba(239,68,68,.22);
      background: linear-gradient(135deg, rgba(239,68,68,.10), rgba(239,68,68,.05));
    }

    /* Preview card */
    .preview-card{
      background:#fff;
      border-radius: var(--radius-xl);
      border:1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
      overflow:hidden;
      height: fit-content; /* ✅ FIX */
    }
    .preview-img{
      width:100%;
      height: 180px;
      object-fit: cover;
      display:block;
      background: linear-gradient(135deg, #F1F5F9 0%, #E2E8F0 100%);
    }
    .preview-body{ padding: 1rem; display:flex; flex-direction:column; gap:.5rem; }
    .pill{
      display:inline-flex;
      align-items:center;
      gap:.375rem;
      font-size:.68rem;
      font-weight:800;
      padding:.22rem .5rem;
      border-radius: 999px;
      width: fit-content;
    }
    .preview-title{ font-weight:900; font-size:.95rem; line-height:1.25; }
    .preview-price{ font-weight:900; font-size:1.1rem; }
    .preview-desc{
      font-size:.8rem;
      color:#64748B;
      font-weight:600;
      line-height:1.45;
      display:-webkit-box;
      -webkit-line-clamp: 3;         /* ✅ boş uzamasın */
      -webkit-box-orient: vertical;
      overflow:hidden;
      min-height: 3.4em;             /* ✅ açıklama alanı sabit hissiyat */
    }
    .preview-stats{
      display:grid;
      grid-template-columns: repeat(3, 1fr);
      gap:.5rem;
      border-top:1px solid #F1F5F9;
      padding-top:.75rem;
      margin-top:.25rem;
    }
    .pv-stat{ text-align:center; }
    .pv-stat b{ display:block; font-size:.85rem; font-weight:900; }
    .pv-stat span{ font-size:.62rem; color:#64748B; font-weight:700; }

    /* Form */
    .section-title{
      display:flex;
      align-items:center;
      gap:.5rem;
      font-size:.95rem;
      font-weight:900;
      margin-bottom:.75rem;
    }
    .grid-2{ display:grid; grid-template-columns: 1fr; gap:.75rem; }
    @media(min-width:768px){ .grid-2{ grid-template-columns: 1fr 1fr; } }

    label.small{ font-size:.72rem; font-weight:800; color:#334155; display:block; margin-bottom:.25rem; }
    .input, .select, .textarea{
      width:100%;
      border:1px solid #E2E8F0;
      border-radius: var(--radius-md);
      padding:.65rem .75rem;
      background:#fff;
      font-size:.85rem;
      font-weight:600;
      transition: var(--transition);
      outline:none;
    }
    .textarea{ min-height: 110px; resize: vertical; }
    .input:focus, .select:focus, .textarea:focus{
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(124,58,237,.10);
    }
    .hint{ font-size:.72rem; color:#94A3B8; font-weight:600; margin-top:.35rem; }

    /* Images grid */
    .img-grid{ display:grid; grid-template-columns: repeat(2, 1fr); gap:.75rem; }
    @media(min-width:768px){ .img-grid{ grid-template-columns: repeat(3, 1fr); } }
    .img-item{
      border:1px solid #E2E8F0;
      border-radius: var(--radius-lg);
      overflow:hidden;
      background:#fff;
      box-shadow: var(--shadow-sm);
    }
    .img-item img{ width:100%; height: 110px; object-fit:cover; display:block; background:#F1F5F9; }
    .img-actions{
      display:flex;
      gap:.4rem;
      padding:.5rem;
      border-top:1px solid #F1F5F9;
      background:#F8FAFC;
    }
    .mini-btn{
      flex:1;
      font-size:.72rem;
      font-weight:800;
      border-radius: var(--radius-md);
      padding:.45rem .5rem;
      border:1px solid #E2E8F0;
      background:#fff;
      cursor:pointer;
      transition: var(--transition);
    }
    .mini-btn:hover{ transform: translateY(-1px); box-shadow: var(--shadow-md); }
    .mini-danger{
      background: rgba(239,68,68,.10);
      border-color: rgba(239,68,68,.25);
      color:#B91C1C;
    }

    /* Right sidebar */
    .side-title{
      font-size:.9rem;
      font-weight:900;
      margin-bottom:.75rem;
      display:flex;
      align-items:center;
      gap:.5rem;
    }
    .side-stack{ display:flex; flex-direction:column; gap:.75rem; }
    .side-btn{ width:100%; justify-content:center; }
    .status-pills{ display:flex; gap:.5rem; flex-wrap:wrap; }
    .status-pick{
      flex:1;
      min-width: 90px;
      border-radius: 999px;
      border:1px solid #E2E8F0;
      background:#fff;
      padding:.45rem .7rem;
      font-weight:900;
      font-size:.72rem;
      cursor:pointer;
      transition: var(--transition);
      text-align:center;
    }
    .status-pick.active{ background:#000; color:#fff; border-color:#000; }
    .kv{
      display:grid;
      grid-template-columns: 1fr auto;
      gap:.5rem .75rem;
      font-size:.78rem;
      font-weight:700;
      color:#334155;
    }
    .kv small{ color:#64748B; font-weight:800; }
    .kv b{ font-weight:900; color:#0F172A; }
  </style>
</head>

<body class="min-h-screen no-x">
<main class="main-container no-x" id="mainContainer">
  <div class="page-content">

    <?php if (!empty($flash)): ?>
      <div class="flash">
        <i data-lucide="check-circle" class="w-4 h-4" style="margin-top:2px"></i>
        <div style="font-weight:800;color:#065F46"><?= h($flash) ?></div>
      </div>
    <?php endif; ?>

    <?php if (!empty($errors)): ?>
      <div class="err">
        <i data-lucide="alert-triangle" class="w-4 h-4" style="margin-top:2px"></i>
        <div>
          <div style="font-weight:900;color:#991B1B;margin-bottom:4px">Kaydetmeden önce düzelt:</div>
          <ul style="margin:0;padding-left:18px;color:#7F1D1D;font-weight:800">
            <?php foreach ($errors as $e): ?><li><?= h($e) ?></li><?php endforeach; ?>
          </ul>
        </div>
      </div>
    <?php endif; ?>

    <div class="editor-grid">

      <!-- LEFT: Preview -->
      <section class="preview-col">
        <div class="preview-card">
          <img src="<?= h($coverUrl) ?>" alt="Kapak" class="preview-img" loading="lazy">
          <div class="preview-body">
            <div class="pill <?= h($dClass) ?>" id="pvStatusPill"><?= h($dLabel) ?></div>

            <div class="preview-title" id="pvTitle"><?= h($baslik ?: 'İlan Başlığı') ?></div>

            <div class="flex items-end justify-between gap-3">
              <div class="preview-price" id="pvPrice"><?= number_format($fiyat, 2, ',', '.') ?> ₺</div>
              <div class="text-xs font-extrabold text-slate-400">#<?= (int)$ilanId ?></div>
            </div>

            <!-- ✅ FIX: Açıklama burada -->
            <div class="preview-desc" id="pvDesc">
              <?= h($aciklama !== '' ? $aciklama : 'Açıklama ekleyin…') ?>
            </div>

            <div class="preview-stats">
              <div class="pv-stat">
                <b id="pvStock"><?= (int)$stok ?></b>
                <span>Stok</span>
              </div>
              <div class="pv-stat">
                <b><?= (int)$favori ?></b>
                <span>Favori</span>
              </div>
              <div class="pv-stat">
                <b><?= (int)$goruntulenme ?></b>
                <span>Görüntülenme</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- CENTER: Form -->
      <section class="form-col">
        <header class="page-header">
          <div>
            <div class="page-title">İlan Düzenle</div>
            <div class="page-subtitle">İlan bilgilerini güncelle</div>
          </div>

          <div class="flex gap-2 flex-wrap">
            <a href="ilanlar.php" class="btn btn-secondary">
              <i data-lucide="arrow-left" class="w-4 h-4"></i>
              İlanlarıma Dön
            </a>
            <button type="submit" form="editForm" class="btn btn-primary">
              <i data-lucide="save" class="w-4 h-4"></i>
              Kaydet
            </button>
          </div>
        </header>

        <form id="editForm" method="post" class="card card-pad" autocomplete="off">
          <input type="hidden" name="action" value="save">

          <div class="section-title">
            <i data-lucide="clipboard-list" class="w-5 h-5"></i>
            Temel Bilgiler
          </div>

          <div class="grid-2">
            <div>
              <label class="small">Başlık</label>
              <input class="input" name="baslik" id="inTitle" value="<?= h($baslik) ?>" placeholder="Örn: Vandavli Tablo">
              <div class="hint">Başlığı kısa ve net tutun.</div>
            </div>

            <div>
              <label class="small">Durum</label>
              <select class="select" name="durum" id="inDurum">
                <?php
                  $opts = ['aktif'=>'Aktif','pasif'=>'Pasif','taslak'=>'Taslak'];
                  foreach ($opts as $k=>$v):
                    $sel = (normalize_status($durum) === $k) ? 'selected' : '';
                ?>
                  <option value="<?= h($k) ?>" <?= $sel ?>><?= h($v) ?></option>
                <?php endforeach; ?>
              </select>
              <div class="hint">Aktif ilanlar mağazada görünür.</div>
            </div>

            <div>
              <label class="small">Kategori</label>
              <input class="input" name="kategori" value="<?= h($kategori) ?>" placeholder="Örn: Tablo">
            </div>

            <div>
              <label class="small">Stok</label>
              <input class="input" name="stok" id="inStock" type="number" min="0" value="<?= (int)$stok ?>" />
            </div>

            <div>
              <label class="small">Fiyat (₺)</label>
              <input class="input" name="fiyat" id="inPrice" value="<?= h(number_format((float)$fiyat, 2, ',', '.')) ?>" placeholder="52.000,00">
            </div>

            <div>
              <label class="small">Kondisyon (opsiyonel)</label>
              <input class="input" name="kondisyon" value="<?= h($kondisyon) ?>" placeholder="Örn: Yeni / İkinci El">
            </div>
          </div>

          <div style="height:14px"></div>

          <div>
            <label class="small">Açıklama</label>
            <textarea class="textarea" name="aciklama" id="inDesc" placeholder="Eser hakkında kısa açıklama..."><?= h($aciklama) ?></textarea>
          </div>

          <div style="height:18px"></div>

          <div class="section-title">
            <i data-lucide="image" class="w-5 h-5"></i>
            Görseller
          </div>

          <?php if (empty($images)): ?>
            <div class="card" style="padding:1rem;border-style:dashed">
              <div class="flex items-center gap-2 text-slate-500 font-extrabold text-sm">
                <i data-lucide="image-off" class="w-4 h-4"></i>
                Henüz görsel yok. Aşağıdan URL ekleyebilirsin.
              </div>
            </div>
          <?php else: ?>
            <div class="img-grid">
              <?php foreach ($images as $im): ?>
                <?php
                  $imId = (int)$im['id'];
                  $url  = (string)$im['url'];
                  $isCover = ((int)$im['is_cover'] === 1);
                ?>
                <div class="img-item">
                  <img src="<?= h($url) ?>" alt="Görsel" loading="lazy">
                  <div class="img-actions">
                    <form method="post" style="flex:1">
                      <input type="hidden" name="action" value="set_cover">
                      <input type="hidden" name="image_id" value="<?= $imId ?>">
                      <button class="mini-btn" type="submit" <?= $isCover ? 'disabled style="opacity:.6;cursor:not-allowed"' : '' ?>>
                        <?= $isCover ? 'Kapak' : 'Kapak Yap' ?>
                      </button>
                    </form>

                    <form method="post" onsubmit="return confirm('Bu görseli silmek istediğinize emin misiniz?');" style="flex:1">
                      <input type="hidden" name="action" value="delete_image">
                      <input type="hidden" name="image_id" value="<?= $imId ?>">
                      <button class="mini-btn mini-danger" type="submit">Sil</button>
                    </form>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>

          <div style="height:12px"></div>

          <div>
            <label class="small">Yeni Görsel URL’leri (her satır 1 URL)</label>
            <textarea class="textarea" name="new_urls" form="addImagesForm" placeholder="https://...&#10;https://..."></textarea>
            <div class="hint">İlk eklenen görsel yoksa otomatik kapak olur.</div>
          </div>

          <div class="flex gap-2 flex-wrap" style="margin-top:.75rem">
            <button type="submit" form="addImagesForm" class="btn btn-secondary">
              <i data-lucide="plus" class="w-4 h-4"></i>
              Görsel Ekle
            </button>

            <button type="submit" class="btn btn-primary">
              <i data-lucide="save" class="w-4 h-4"></i>
              Kaydet
            </button>

            <button type="submit" form="deleteIlanForm" class="btn btn-danger">
              <i data-lucide="trash-2" class="w-4 h-4"></i>
              İlanı Sil
            </button>
          </div>

          <div style="height:18px"></div>

          <details class="card" style="padding:1rem">
            <summary class="section-title" style="margin:0;cursor:pointer;list-style:none">
              <i data-lucide="sliders" class="w-5 h-5"></i>
              Detaylar (opsiyonel)
            </summary>

            <div style="height:12px"></div>

            <div class="grid-2">
              <div>
                <label class="small">Yıl</label>
                <input class="input" name="yil" value="<?= h($yil) ?>" placeholder="2024">
              </div>

              <div>
                <label class="small">Materyaller</label>
                <input class="input" name="materyaller" value="<?= h($materyaller) ?>" placeholder="Örn: Tuval, Yağlı boya">
              </div>

              <div>
                <label class="small">Genişlik (cm)</label>
                <input class="input" name="genislik_cm" value="<?= h($genislik_cm) ?>" placeholder="50">
              </div>

              <div>
                <label class="small">Yükseklik (cm)</label>
                <input class="input" name="yukseklik_cm" value="<?= h($yukseklik_cm) ?>" placeholder="70">
              </div>

              <div>
                <label class="small">Derinlik (cm)</label>
                <input class="input" name="derinlik_cm" value="<?= h($derinlik_cm) ?>" placeholder="2">
              </div>

              <div>
                <label class="small">Kargo Ücreti (₺)</label>
                <input class="input" name="kargo_ucreti" value="<?= h($kargo_ucreti) ?>" placeholder="Örn: 250">
              </div>

              <div>
                <label class="small">Teslim Süresi</label>
                <input class="input" name="teslim_suresi" value="<?= h($teslim_suresi) ?>" placeholder="Örn: 3-5 iş günü">
              </div>

              <div>
                <label class="small">Teslimat Yöntemleri</label>
                <div class="card" style="padding:.75rem;border-radius:14px">
                  <div class="grid" style="display:grid;grid-template-columns:repeat(2,1fr);gap:.5rem">
                    <?php foreach ($allDelivery as $m): ?>
                      <?php $ck = in_array($m, $teslimat_arr, true) ? 'checked' : ''; ?>
                      <label style="display:flex;align-items:center;gap:.5rem;font-weight:900;font-size:.78rem;color:#334155">
                        <input type="checkbox" name="teslimat[]" value="<?= h($m) ?>" <?= $ck ?> style="width:16px;height:16px;accent-color:#000">
                        <?= h($m) ?>
                      </label>
                    <?php endforeach; ?>
                  </div>
                </div>
                <div class="hint">Boş bırakırsan kayıt edilmez.</div>
              </div>
            </div>
          </details>
        </form>

        <!-- forms for image add & delete ilan -->
        <form id="addImagesForm" method="post">
          <input type="hidden" name="action" value="add_images">
        </form>

        <form id="deleteIlanForm" method="post" onsubmit="return confirm('Bu ilanı kalıcı olarak silmek istiyor musunuz?');">
          <input type="hidden" name="action" value="delete_ilan">
        </form>

      </section>

      <!-- RIGHT: Sidebar actions/info -->
      <aside class="right-col">
        <div class="side-stack">

          <div class="card card-pad">
            <div class="side-title">
              <i data-lucide="zap" class="w-5 h-5"></i>
              Hızlı İşlemler
            </div>

            <div class="side-stack" style="gap:.5rem">
              <button type="button" class="btn btn-secondary side-btn" onclick="window.open('ilan-detay.php?id=<?= (int)$ilanId ?>','_blank')">
                <i data-lucide="eye" class="w-4 h-4"></i>
                İlanı Görüntüle
              </button>

              <a class="btn btn-secondary side-btn" href="ilanlar.php">
                <i data-lucide="list" class="w-4 h-4"></i>
                İlanlarım
              </a>

              <button type="submit" form="editForm" class="btn btn-primary side-btn">
                <i data-lucide="save" class="w-4 h-4"></i>
                Kaydet
              </button>
            </div>
          </div>

          <div class="card card-pad">
            <div class="side-title">
              <i data-lucide="toggle-left" class="w-5 h-5"></i>
              Durum
            </div>

            <div class="status-pills">
              <button type="button" class="status-pick <?= ($durum==='aktif'?'active':'') ?>" data-set-status="aktif">Aktif</button>
              <button type="button" class="status-pick <?= ($durum==='pasif'?'active':'') ?>" data-set-status="pasif">Pasif</button>
              <button type="button" class="status-pick <?= ($durum==='taslak'?'active':'') ?>" data-set-status="taslak">Taslak</button>
            </div>

            <div class="hint">Durum butonları formdaki seçimi değiştirir.</div>
          </div>

          <div class="card card-pad">
            <div class="side-title">
              <i data-lucide="info" class="w-5 h-5"></i>
              Bilgiler
            </div>

            <div class="kv">
              <small>İlan ID</small><b>#<?= (int)$ilanId ?></b>
              <small>Oluşturma</small><b><?= h($createdAt ?: '—') ?></b>
              <small>Güncellenme</small><b><?= h($updatedAt ?: '—') ?></b>
              <small>Görüntülenme</small><b><?= (int)$goruntulenme ?></b>
              <small>Favori</small><b><?= (int)$favori ?></b>
            </div>
          </div>

        </div>
      </aside>

    </div>
  </div>
</main>

<script>
  document.addEventListener('DOMContentLoaded', function(){
    if (window.lucide) window.lucide.createIcons();

    // Sidebar width sync (ilanlar.php ile aynı mantık)
    function applySidebarWidth() {
      const sidebar = document.querySelector('aside, nav.sidebar, #sidebar');
      if (sidebar && window.innerWidth >= 1024) {
        const rect = sidebar.getBoundingClientRect();
        const style = getComputedStyle(sidebar);
        const isVisible = style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 100 && rect.left >= 0;
        if (isVisible) {
          document.documentElement.style.setProperty('--sidebar-width', rect.width + 'px');
          return;
        }
      }
      document.documentElement.style.setProperty('--sidebar-width', '0px');
    }
    applySidebarWidth();
    window.addEventListener('resize', applySidebarWidth);

    // Live preview bindings (açıklama + uzama fix hissiyatı)
    const inTitle = document.getElementById('inTitle');
    const inPrice = document.getElementById('inPrice');
    const inStock = document.getElementById('inStock');
    const inDesc  = document.getElementById('inDesc');
    const inDurum = document.getElementById('inDurum');

    const pvTitle = document.getElementById('pvTitle');
    const pvPrice = document.getElementById('pvPrice');
    const pvStock = document.getElementById('pvStock');
    const pvDesc  = document.getElementById('pvDesc');
    const pvStatusPill = document.getElementById('pvStatusPill');

    function formatPriceTR(val){
      const raw = (val || '').toString().replace(/[^\d,\.]/g,'').trim();
      if(!raw) return '0,00 ₺';
      // 52.000,00 -> keep, else try normalize
      let x = raw.replace(/\./g,'').replace(',', '.');
      const num = parseFloat(x);
      if (isNaN(num)) return raw + ' ₺';
      return num.toLocaleString('tr-TR', {minimumFractionDigits:2, maximumFractionDigits:2}) + ' ₺';
    }

    function updatePreview(){
      if (pvTitle) pvTitle.textContent = (inTitle?.value || '').trim() || 'İlan Başlığı';
      if (pvPrice) pvPrice.textContent = formatPriceTR(inPrice?.value || '0');
      if (pvStock) pvStock.textContent = (inStock?.value || '0').toString();
      const d = (inDesc?.value || '').trim();
      if (pvDesc) pvDesc.textContent = d || 'Açıklama ekleyin…';

      // status pill label (basit)
      const s = (inDurum?.value || 'pasif').toLowerCase();
      if (pvStatusPill){
        pvStatusPill.textContent = (s === 'aktif') ? 'Aktif' : (s === 'taslak') ? 'Taslak' : 'Pasif';
      }
    }

    ['input','change'].forEach(ev=>{
      inTitle && inTitle.addEventListener(ev, updatePreview);
      inPrice && inPrice.addEventListener(ev, updatePreview);
      inStock && inStock.addEventListener(ev, updatePreview);
      inDesc  && inDesc.addEventListener(ev, updatePreview);
      inDurum && inDurum.addEventListener(ev, updatePreview);
    });
    updatePreview();

    // Right status quick toggles
    document.querySelectorAll('[data-set-status]').forEach(btn=>{
      btn.addEventListener('click', ()=>{
        const val = btn.getAttribute('data-set-status');
        if (inDurum && val){
          inDurum.value = val;
          // active class
          document.querySelectorAll('.status-pick').forEach(x=>x.classList.remove('active'));
          btn.classList.add('active');
          updatePreview();
        }
      });
    });
  });
</script>
</body>
</html>
