<?php 
// seller/urun-ekle.php
declare(strict_types=1);

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

/* =========================
   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. Beklenen: 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 */
function app_pdo(): 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ı.');
}

/* Basit escape */
function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

/* =========================
   ✅ AUTH (Loop yapmadan)
========================= */
$u = function_exists('current_user') ? current_user() : null;
$isSeller = $u && (($u['role'] ?? '') === 'seller');

if (!$isSeller) {
  $next = $_SERVER['REQUEST_URI'] ?? 'urun-ekle.php';
  $loginUrl = (function_exists('app_base') ? app_base('seller/login.php') : 'login.php') . '?next=' . rawurlencode($next);
  header('Location: ' . $loginUrl);
  exit;
}

/* seller_id yoksa tamamla (ama gate için şart koşmuyoruz -> loop olmaz) */
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ç
  }
}
$sellerId = (int)($_SESSION['seller_id'] ?? ($u['id'] ?? 0));
if ($sellerId <= 0) {
  // En kötü senaryo: user id fallback
  $sellerId = (int)($u['id'] ?? 0);
}

/* Sidebar (auth sonrası!) */
$active = 'ilanlar';
$base   = $base   ?? (function_exists('app_base') ? app_base('seller/') : '/seller/');
$userName = (string)($_SESSION['firma_adi'] ?? ($u['name'] ?? 'Hesabım'));
include __DIR__ . '/../app/sidebar.php';

/* =========================
   Demo veriler (istersen DB’den çekersin)
========================= */
$categories = [
  'Tablo' => 'Tablo',
  'Heykel' => 'Heykel',
  'Seramik' => 'Seramik',
  'Fotoğraf' => 'Fotoğraf',
  'Poster' => 'Poster',
  'İllüstrasyon' => 'İllüstrasyon',
  'Gravür' => 'Gravür',
  'Diğer' => 'Diğer'
];

$conditions = [
  'yeni' => 'Yeni',
  'cok-iyi' => 'Çok İyi',
  'iyi' => 'İyi',
  'orta' => 'Orta',
  'tadilat-gerekli' => 'Tadilat Gerekli'
];

$delivery_methods = [
  'kargo' => 'Kargo ile Gönderim',
  'teslim' => 'Elden Teslim',
  'galeriden' => 'Galeriden Alım'
];

/* =========================
   POST -> DB KAYIT
========================= */
$message = '';
$error = '';

/* old values */
$old = [
  'title' => '',
  'category' => '',
  'price' => '',
  'stock' => '1',
  'description' => '',
  'condition' => '',
  'year' => '',
  'width' => '',
  'height' => '',
  'depth' => '',
  'materials' => '',
  'delivery' => [],
  'shipping_cost' => '',
  'delivery_time' => '',
];

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

    $action = (string)($_POST['action'] ?? 'publish'); // publish | draft

    $old['title'] = trim((string)($_POST['title'] ?? ''));
    $old['category'] = (string)($_POST['category'] ?? '');
    $old['price'] = (string)($_POST['price'] ?? '');
    $old['stock'] = (string)($_POST['stock'] ?? '1');
    $old['description'] = trim((string)($_POST['description'] ?? ''));
    $old['condition'] = (string)($_POST['condition'] ?? '');
    $old['year'] = (string)($_POST['year'] ?? '');
    $old['width'] = (string)($_POST['width'] ?? '');
    $old['height'] = (string)($_POST['height'] ?? '');
    $old['depth'] = (string)($_POST['depth'] ?? '');
    $old['materials'] = trim((string)($_POST['materials'] ?? ''));
    $old['delivery'] = (array)($_POST['delivery'] ?? []);
    $old['shipping_cost'] = (string)($_POST['shipping_cost'] ?? '');
    $old['delivery_time'] = (string)($_POST['delivery_time'] ?? '');

    // Validasyon
    if ($old['title'] === '' || $old['category'] === '' || $old['price'] === '' || $old['condition'] === '') {
      throw new RuntimeException('Zorunlu alanları doldurunuz (Başlık, Kategori, Fiyat, Durum).');
    }

    $price = (float)$old['price'];
    if ($price <= 0) throw new RuntimeException('Fiyat 0’dan büyük olmalı.');

    $stock = (int)$old['stock'];
    if ($stock < 1) throw new RuntimeException('Stok en az 1 olmalı.');

    $year = $old['year'] !== '' ? (int)$old['year'] : null;
    if ($year !== null && ($year < 1900 || $year > (int)date('Y'))) {
      throw new RuntimeException('Yapım yılı geçersiz.');
    }

    $widthCm  = $old['width']  !== '' ? (float)$old['width']  : null;
    $heightCm = $old['height'] !== '' ? (float)$old['height'] : null;
    $depthCm  = $old['depth']  !== '' ? (float)$old['depth']  : null;

    $shippingCost = $old['shipping_cost'] !== '' ? (float)$old['shipping_cost'] : 0.00;

    // Teslimat json
    $deliveryArr = array_values(array_filter(array_map('strval', $old['delivery'])));
    $deliveryJson = json_encode($deliveryArr, JSON_UNESCAPED_UNICODE);

    $durum = ($action === 'draft') ? 'taslak' : 'aktif';

    $pdo = app_pdo();
    $pdo->beginTransaction();

    $now = date('Y-m-d H:i:s');

    // ✅ ilanlar tablosu kolonları (SQL dosyana göre)
    $sql = "INSERT INTO ilanlar
      (seller_id, baslik, kategori, fiyat, stok, aciklama, kondisyon, yil,
       genislik_cm, yukseklik_cm, derinlik_cm, materyaller,
       teslimat_yontemleri_json, kargo_ucreti, teslim_suresi, durum,
       created_at, updated_at)
      VALUES
      (:seller_id, :baslik, :kategori, :fiyat, :stok, :aciklama, :kondisyon, :yil,
       :genislik_cm, :yukseklik_cm, :derinlik_cm, :materyaller,
       :teslimat_json, :kargo_ucreti, :teslim_suresi, :durum,
       :created_at, :updated_at)";

    $st = $pdo->prepare($sql);
    $st->execute([
      ':seller_id'      => $sellerId,
      ':baslik'         => $old['title'],
      ':kategori'       => $old['category'],
      ':fiyat'          => $price,
      ':stok'           => $stock,
      ':aciklama'       => $old['description'],
      ':kondisyon'      => $old['condition'],
      ':yil'            => $year,
      ':genislik_cm'    => $widthCm,
      ':yukseklik_cm'   => $heightCm,
      ':derinlik_cm'    => $depthCm,
      ':materyaller'    => $old['materials'],          // ✅ sütun adı: materyaller
      ':teslimat_json'  => $deliveryJson,
      ':kargo_ucreti'   => $shippingCost,
      ':teslim_suresi'  => $old['delivery_time'],
      ':durum'          => $durum,
      ':created_at'     => $now,
      ':updated_at'     => $now,
    ]);

    $ilanId = (int)$pdo->lastInsertId();

    /* =========================
       Fotoğraflar -> uploads + ilan_gorseller
       tablo: ilan_gorseller(url, is_cover, sort_order, created_at)
    ========================= */
    $uploadDir = realpath(__DIR__ . '/../uploads') ?: (__DIR__ . '/../uploads');
    $ilanUploadDir = $uploadDir . DIRECTORY_SEPARATOR . 'ilanlar';
    if (!is_dir($ilanUploadDir)) {
      if (!mkdir($ilanUploadDir, 0775, true) && !is_dir($ilanUploadDir)) {
        throw new RuntimeException('uploads/ilanlar klasörü oluşturulamadı.');
      }
    }

    $publicPrefix = function_exists('app_base') ? app_base('uploads/ilanlar/') : '/uploads/ilanlar/';

    $files = $_FILES['images'] ?? null;
    if ($files && isset($files['name']) && is_array($files['name'])) {
      $finfo = new finfo(FILEINFO_MIME_TYPE);

      $count = count($files['name']);
      $sort = 1;

      for ($i = 0; $i < $count; $i++) {
        if (($files['error'][$i] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) continue;

        $tmp = (string)$files['tmp_name'][$i];
        $origName = (string)$files['name'][$i];
        $size = (int)($files['size'][$i] ?? 0);

        if ($size <= 0) continue;
        if ($size > 5 * 1024 * 1024) {
          throw new RuntimeException("Dosya 5MB'dan büyük: " . $origName);
        }

        $mime = $finfo->file($tmp) ?: '';
        $allowed = [
          'image/jpeg' => 'jpg',
          'image/png'  => 'png',
          'image/webp' => 'webp',
        ];
        if (!isset($allowed[$mime])) {
          throw new RuntimeException("Desteklenmeyen resim türü ($mime): " . $origName);
        }

        $ext = $allowed[$mime];
        $safeName = bin2hex(random_bytes(16)) . '.' . $ext;
        $destPath = $ilanUploadDir . DIRECTORY_SEPARATOR . $safeName;

        if (!move_uploaded_file($tmp, $destPath)) {
          throw new RuntimeException("Fotoğraf kaydedilemedi: " . $origName);
        }

        $url = $publicPrefix . $safeName;
        $isCover = ($sort === 1) ? 1 : 0;

        $igst = $pdo->prepare("INSERT INTO ilan_gorseller (ilan_id, url, is_cover, sort_order, created_at)
                               VALUES (:ilan_id, :url, :is_cover, :sort_order, :created_at)");
        $igst->execute([
          ':ilan_id'   => $ilanId,
          ':url'       => $url,
          ':is_cover'  => $isCover,
          ':sort_order'=> $sort,          // ✅ sütun adı: sort_order (sira değil)
          ':created_at'=> $now,
        ]);

        $sort++;
        if ($sort > 8) break; // max 8
      }
    }

    $pdo->commit();

    $message = ($durum === 'taslak')
      ? 'İlan taslak olarak kaydedildi!'
      : 'İlan başarıyla oluşturuldu ve yayına alındı!';

    // Formu sıfırla (başarılıysa)
    $old = [
      'title' => '',
      'category' => '',
      'price' => '',
      'stock' => '1',
      'description' => '',
      'condition' => '',
      'year' => '',
      'width' => '',
      'height' => '',
      'depth' => '',
      'materials' => '',
      'delivery' => [],
      'shipping_cost' => '',
      'delivery_time' => '',
    ];

  } catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
      $pdo->rollBack();
    }
    $error = 'Kayıt sırasında hata oluştu: ' . $e->getMessage();
  }
}

$csrf = csrf_token();
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Yeni İlan Ekle - Sanat Eseri</title>
  <script src="https://unpkg.com/lucide@latest"></script>
  
  <style>
    :root {
      --primary: #2563eb;
      --primary-dark: #1d4ed8;
      --success: #059669;
      --warning: #d97706;
      --danger: #dc2626;
      --gray-50: #f9fafb;
      --gray-100: #f3f4f6;
      --gray-200: #e5e7eb;
      --gray-300: #d1d5db;
      --gray-400: #9ca3af;
      --gray-500: #6b7280;
      --gray-600: #4b5563;
      --gray-700: #374151;
      --gray-800: #1f2937;
      --gray-900: #111827;
      --radius: 8px;
      --shadow: 0 1px 3px rgba(0,0,0,0.1);
      --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
    }
    
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
      font-size: 14px;
      line-height: 1.5;
      color: var(--gray-800);
      background-color: var(--gray-50);
      min-height: 100vh;
    }
    
    .container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 0 20px;
      width: 100%;
    }
    
    .page-header {
      padding: 24px 0;
      border-bottom: 1px solid var(--gray-200);
      background: white;
      margin-bottom: 24px;
    }
    
    .page-header h1 {
      font-size: 24px;
      font-weight: 600;
      color: var(--gray-900);
      margin-bottom: 8px;
    }
    
    .page-header p {
      color: var(--gray-600);
      font-size: 14px;
    }
    
    .main-layout {
      display: grid;
      grid-template-columns: 1fr 340px;
      gap: 24px;
      margin-bottom: 40px;
    }
    
    @media (max-width: 992px) {
      .main-layout {
        grid-template-columns: 1fr;
      }
    }
    
    /* Form Styling */
    .form-section {
      background: white;
      border-radius: var(--radius);
      padding: 24px;
      margin-bottom: 24px;
      box-shadow: var(--shadow);
      border: 1px solid var(--gray-200);
    }
    
    .section-title {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 20px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--gray-200);
    }
    
    .section-title h2 {
      font-size: 16px;
      font-weight: 600;
      color: var(--gray-900);
    }
    
    .section-title svg {
      width: 20px;
      height: 20px;
      color: var(--gray-600);
    }
    
    .form-group {
      margin-bottom: 20px;
    }
    
    .form-label {
      display: block;
      font-size: 13px;
      font-weight: 500;
      color: var(--gray-700);
      margin-bottom: 6px;
    }
    
    .form-label.required::after {
      content: " *";
      color: var(--danger);
    }
    
    .form-control {
      width: 100%;
      padding: 10px 12px;
      font-size: 14px;
      border: 1px solid var(--gray-300);
      border-radius: var(--radius);
      background: white;
      transition: border-color 0.15s;
      font-family: inherit;
    }
    
    .form-control:focus {
      outline: none;
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
    }
    
    .form-control::placeholder {
      color: var(--gray-400);
    }
    
    select.form-control {
      appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%236b7280' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 12px center;
      padding-right: 36px;
    }
    
    textarea.form-control {
      min-height: 120px;
      resize: vertical;
    }
    
    .form-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
    }
    
    @media (max-width: 768px) {
      .form-grid {
        grid-template-columns: 1fr;
      }
    }
    
    .form-grid .full-width {
      grid-column: 1 / -1;
    }
    
    /* File Upload */
    .file-upload-area {
      border: 2px dashed var(--gray-300);
      border-radius: var(--radius);
      padding: 32px 20px;
      text-align: center;
      background: var(--gray-50);
      transition: border-color 0.15s;
      cursor: pointer;
    }
    
    .file-upload-area:hover {
      border-color: var(--gray-400);
    }
    
    .file-upload-area.drag-over {
      border-color: var(--primary);
      background: rgba(37, 99, 235, 0.02);
    }
    
    .file-upload-icon {
      margin: 0 auto 12px;
      color: var(--gray-500);
    }
    
    .file-upload-title {
      font-size: 15px;
      font-weight: 500;
      color: var(--gray-800);
      margin-bottom: 4px;
    }
    
    .file-upload-desc {
      font-size: 13px;
      color: var(--gray-500);
      margin-bottom: 16px;
    }
    
    .file-preview-container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
      gap: 12px;
      margin-top: 16px;
    }
    
    .file-preview {
      position: relative;
      aspect-ratio: 1;
      border-radius: var(--radius);
      overflow: hidden;
      border: 1px solid var(--gray-200);
      background: white;
    }
    
    .file-preview img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .file-preview-remove {
      position: absolute;
      top: 6px;
      right: 6px;
      width: 24px;
      height: 24px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.7);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border: none;
      opacity: 0;
      transition: opacity 0.15s;
    }
    
    .file-preview:hover .file-preview-remove {
      opacity: 1;
    }
    
    /* Checkbox Group */
    .checkbox-group {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
    
    .checkbox-item {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 12px;
      border: 1px solid var(--gray-200);
      border-radius: var(--radius);
      background: white;
      cursor: pointer;
      transition: border-color 0.15s;
    }
    
    .checkbox-item:hover {
      border-color: var(--gray-300);
    }
    
    .checkbox-item input[type="checkbox"] {
      width: 16px;
      height: 16px;
      accent-color: var(--primary);
    }
    
    .checkbox-label {
      font-size: 14px;
      color: var(--gray-700);
    }
    
    /* Alert */
    .alert {
      padding: 12px 16px;
      border-radius: var(--radius);
      margin-bottom: 20px;
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;
    }
    
    .alert-success {
      background-color: #f0fdf4;
      border: 1px solid #bbf7d0;
      color: var(--success);
    }
    
    .alert-error {
      background-color: #fef2f2;
      border: 1px solid #fecaca;
      color: var(--danger);
    }
    
    /* Buttons */
    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 10px 20px;
      font-size: 14px;
      font-weight: 500;
      border-radius: var(--radius);
      border: 1px solid transparent;
      cursor: pointer;
      transition: all 0.15s;
      font-family: inherit;
    }
    
    .btn-primary {
      background-color: var(--primary);
      color: white;
      border-color: var(--primary);
    }
    
    .btn-primary:hover {
      background-color: var(--primary-dark);
    }
    
    .btn-secondary {
      background-color: white;
      color: var(--gray-700);
      border-color: var(--gray-300);
    }
    
    .btn-secondary:hover {
      background-color: var(--gray-50);
    }
    
    .btn-outline {
      background-color: transparent;
      color: var(--gray-700);
      border-color: var(--gray-300);
    }
    
    .btn-outline:hover {
      background-color: var(--gray-50);
    }
    
    .btn-sm {
      padding: 8px 16px;
      font-size: 13px;
    }
    
    /* Form Actions */
    .form-actions {
      display: flex;
      gap: 12px;
      padding: 20px 0;
      border-top: 1px solid var(--gray-200);
      margin-top: 20px;
    }
    
    @media (max-width: 640px) {
      .form-actions {
        flex-direction: column;
      }
      
      .form-actions .btn {
        width: 100%;
      }
    }
    
    /* Preview Sidebar */
    .preview-sidebar {
      position: sticky;
      top: 24px;
    }
    
    .preview-card {
      background: white;
      border-radius: var(--radius);
      padding: 20px;
      box-shadow: var(--shadow);
      border: 1px solid var(--gray-200);
      margin-bottom: 20px;
    }
    
    .preview-header {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid var(--gray-200);
    }
    
    .preview-header h3 {
      font-size: 15px;
      font-weight: 600;
      color: var(--gray-900);
    }
    
    .preview-image {
      aspect-ratio: 4/3;
      background: var(--gray-100);
      border-radius: var(--radius);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 16px;
      overflow: hidden;
    }
    
    .preview-image img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .preview-image-placeholder {
      color: var(--gray-400);
    }
    
    .preview-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--gray-900);
      margin-bottom: 8px;
    }
    
    .preview-category {
      display: inline-block;
      padding: 4px 12px;
      background: var(--gray-100);
      color: var(--gray-700);
      border-radius: 20px;
      font-size: 12px;
      margin-bottom: 12px;
    }
    
    .preview-description {
      font-size: 14px;
      color: var(--gray-600);
      line-height: 1.6;
      margin-bottom: 16px;
    }
    
    .preview-price {
      font-size: 20px;
      font-weight: 600;
      color: var(--gray-900);
      margin-bottom: 16px;
    }
    
    .preview-meta {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid var(--gray-200);
    }
    
    .meta-item {
      text-align: center;
    }
    
    .meta-value {
      display: block;
      font-size: 14px;
      font-weight: 600;
      color: var(--gray-900);
    }
    
    .meta-label {
      display: block;
      font-size: 12px;
      color: var(--gray-500);
      margin-top: 4px;
    }
    
    /* Tips */
    .tips {
      background: #f0f9ff;
      border: 1px solid #e0f2fe;
      border-radius: var(--radius);
      padding: 16px;
      margin-top: 20px;
    }
    
    .tips h4 {
      font-size: 14px;
      font-weight: 600;
      color: var(--gray-800);
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .tips ul {
      padding-left: 20px;
      color: var(--gray-600);
      font-size: 13px;
      line-height: 1.6;
    }
    
    .tips li {
      margin-bottom: 6px;
    }
    
    /* Character Counter */
    .char-counter {
      text-align: right;
      font-size: 12px;
      color: var(--gray-500);
      margin-top: 4px;
    }
    
    /* Required Indicator */
    .required-indicator {
      color: var(--danger);
      margin-left: 4px;
    }
    
    /* Helper Text */
    .helper-text {
      font-size: 12px;
      color: var(--gray-500);
      margin-top: 4px;
    }
    
    /* Back Link */
    .back-link {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      color: var(--gray-600);
      font-size: 14px;
      text-decoration: none;
      margin-bottom: 20px;
    }
    
    .back-link:hover {
      color: var(--gray-800);
    }
  </style>
</head>

<body>
  <div class="page-header">
    <div class="container">
      <a href="ilanlar.php" class="back-link">
        <i data-lucide="arrow-left" class="w-4 h-4"></i>
        İlanlara Dön
      </a>
      <h1>Yeni İlan Ekle</h1>
      <p>Sanat eserinizi detaylı bir şekilde tanıtın</p>
    </div>
  </div>

  <div class="container">
    <?php if ($message): ?>
      <div class="alert alert-success">
        <i data-lucide="check-circle" class="w-5 h-5"></i>
        <span><?= h($message) ?></span>
      </div>
    <?php endif; ?>

    <?php if ($error): ?>
      <div class="alert alert-error">
        <i data-lucide="alert-circle" class="w-5 h-5"></i>
        <span><?= h($error) ?></span>
      </div>
    <?php endif; ?>

    <div class="main-layout">
      <!-- Main Form -->
      <div class="form-container">
        <form method="POST" class="form" id="listingForm" enctype="multipart/form-data">
          <input type="hidden" name="_csrf" value="<?= h($csrf) ?>">
          <input type="hidden" name="action" id="formAction" value="publish">

          <!-- Temel Bilgiler -->
          <div class="form-section">
            <div class="section-title">
              <i data-lucide="info" class="w-5 h-5"></i>
              <h2>Temel Bilgiler</h2>
            </div>

            <div class="form-group">
              <label class="form-label required">İlan Başlığı</label>
              <input type="text" name="title" class="form-control" 
                     placeholder="Örn: Soyut Tablo - Renk Dalgası" 
                     maxlength="100" required value="<?= h($old['title']) ?>">
              <div class="char-counter" id="titleCounter"><?= (int)mb_strlen($old['title']) ?>/100</div>
            </div>

            <div class="form-grid">
              <div class="form-group">
                <label class="form-label required">Kategori</label>
                <select name="category" class="form-control" required>
                  <option value="">Kategori seçin</option>
                  <?php foreach ($categories as $value => $label): ?>
                    <option value="<?= h($value) ?>" <?= ($old['category'] === $value ? 'selected' : '') ?>>
                      <?= h($label) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>

              <div class="form-group">
                <label class="form-label required">Fiyat (₺)</label>
                <input type="number" name="price" class="form-control" 
                       placeholder="0.00" min="0" step="0.01" required 
                       value="<?= h($old['price']) ?>">
              </div>
            </div>

            <div class="form-grid">
              <div class="form-group">
                <label class="form-label required">Stok Adedi</label>
                <input type="number" name="stock" class="form-control" 
                       placeholder="Örn: 1" min="1" required 
                       value="<?= h($old['stock']) ?>">
              </div>
            </div>
          </div>

          <!-- Fotoğraflar -->
          <div class="form-section">
            <div class="section-title">
              <i data-lucide="image" class="w-5 h-5"></i>
              <h2>Fotoğraflar</h2>
            </div>

            <div class="file-upload-container">
              <div class="file-upload-area" id="dropZone">
                <div class="file-upload-icon">
                  <i data-lucide="upload" class="w-10 h-10"></i>
                </div>
                <h4 class="file-upload-title">Fotoğrafları sürükleyip bırakın</h4>
                <p class="file-upload-desc">veya</p>
                
                <button type="button" class="btn btn-outline btn-sm" id="fileUploadBtn">
                  <i data-lucide="folder-open" class="w-4 h-4"></i>
                  Bilgisayardan Seç
                </button>
                
                <input type="file" id="fileInput" name="images[]" multiple accept="image/*" style="display:none;">
                
                <p class="file-upload-desc" style="margin-top: 12px;">
                  JPG, PNG, WEBP • maksimum 5MB • en fazla 8 fotoğraf
                </p>
              </div>

              <div class="file-preview-container" id="filePreview"></div>
            </div>
          </div>

          <!-- Açıklama -->
          <div class="form-section">
            <div class="section-title">
              <i data-lucide="file-text" class="w-5 h-5"></i>
              <h2>Açıklama</h2>
            </div>

            <div class="form-group">
              <label class="form-label">Detaylı Açıklama</label>
              <textarea name="description" class="form-control" 
                        placeholder="Ürününüzü detaylı bir şekilde anlatın..."
                        rows="6" maxlength="2000"><?= h($old['description']) ?></textarea>
              <div class="char-counter" id="descriptionCounter"><?= (int)mb_strlen($old['description']) ?>/2000</div>
            </div>
          </div>

          <!-- Durum ve Özellikler -->
          <div class="form-section">
            <div class="section-title">
              <i data-lucide="package" class="w-5 h-5"></i>
              <h2>Durum ve Özellikler</h2>
            </div>

            <div class="form-grid">
              <div class="form-group">
                <label class="form-label required">Durum</label>
                <select name="condition" class="form-control" required>
                  <option value="">Durum seçin</option>
                  <?php foreach ($conditions as $value => $label): ?>
                    <option value="<?= h($value) ?>" <?= ($old['condition'] === $value ? 'selected' : '') ?>>
                      <?= h($label) ?>
                    </option>
                  <?php endforeach; ?>
                </select>
              </div>

              <div class="form-group">
                <label class="form-label">Yapım Yılı</label>
                <input type="number" name="year" class="form-control" 
                       placeholder="Örn: 2023" min="1900" max="<?= (int)date('Y') ?>" 
                       value="<?= h($old['year']) ?>">
              </div>
            </div>

            <div class="form-grid">
              <div class="form-group">
                <label class="form-label">Genişlik (cm)</label>
                <input type="number" name="width" class="form-control" placeholder="Genişlik" min="0" value="<?= h($old['width']) ?>">
              </div>
              
              <div class="form-group">
                <label class="form-label">Yükseklik (cm)</label>
                <input type="number" name="height" class="form-control" placeholder="Yükseklik" min="0" value="<?= h($old['height']) ?>">
              </div>
              
              <div class="form-group">
                <label class="form-label">Derinlik (cm)</label>
                <input type="number" name="depth" class="form-control" placeholder="Derinlik" min="0" value="<?= h($old['depth']) ?>">
              </div>
            </div>

            <div class="form-group">
              <label class="form-label">Materyaller</label>
              <input type="text" name="materials" class="form-control" 
                     placeholder="Örn: Tuval üzerine yağlı boya, ahşap çerçeve" 
                     maxlength="255" value="<?= h($old['materials']) ?>">
            </div>
          </div>

          <!-- Teslimat -->
          <div class="form-section">
            <div class="section-title">
              <i data-lucide="truck" class="w-5 h-5"></i>
              <h2>Teslimat ve Ödeme</h2>
            </div>

            <div class="form-group">
              <label class="form-label required">Teslimat Yöntemi</label>
              <div class="checkbox-group">
                <?php foreach ($delivery_methods as $value => $label): ?>
                  <label class="checkbox-item">
                    <input type="checkbox" name="delivery[]" value="<?= h($value) ?>" 
                      <?= in_array($value, $old['delivery'], true) ? 'checked' : '' ?>>
                    <span class="checkbox-label"><?= h($label) ?></span>
                  </label>
                <?php endforeach; ?>
              </div>
            </div>

            <div class="form-grid">
              <div class="form-group">
                <label class="form-label">Kargo Ücreti</label>
                <input type="number" name="shipping_cost" class="form-control" 
                       placeholder="0.00" min="0" step="0.01" 
                       value="<?= h($old['shipping_cost']) ?>">
              </div>

              <div class="form-group">
                <label class="form-label">Tahmini Teslimat Süresi</label>
                <select name="delivery_time" class="form-control">
                  <option value="">Seçiniz</option>
                  <?php
                    $opts = [
                      '1-3' => '1-3 iş günü',
                      '3-5' => '3-5 iş günü',
                      '5-7' => '5-7 iş günü',
                      '7-14'=> '7-14 iş günü',
                      '14+' => '14+ iş günü'
                    ];
                    foreach ($opts as $v=>$t):
                  ?>
                    <option value="<?= h($v) ?>" <?= ($old['delivery_time'] === $v ? 'selected' : '') ?>><?= h($t) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
            </div>
          </div>

          <!-- Form Actions -->
          <div class="form-actions">
            <button type="submit" class="btn btn-primary" id="publishBtn">
              <i data-lucide="plus" class="w-4 h-4"></i>
              İlanı Yayınla
            </button>

            <button type="button" class="btn btn-secondary" id="draftBtn">
              <i data-lucide="save" class="w-4 h-4"></i>
              Taslak Olarak Kaydet
            </button>

            <button type="reset" class="btn btn-outline">
              Formu Temizle
            </button>
          </div>
        </form>
      </div>

      <!-- Preview Sidebar -->
      <div class="preview-sidebar">
        <div class="preview-card">
          <div class="preview-header">
            <i data-lucide="eye" class="w-5 h-5"></i>
            <h3>Önizleme</h3>
          </div>

          <div class="preview-image" id="previewImage">
            <div class="preview-image-placeholder">
              <i data-lucide="image" class="w-12 h-12"></i>
            </div>
          </div>

          <div class="preview-content">
            <div class="preview-category" id="previewCategory"><?= h($old['category'] ?: 'Kategori') ?></div>
            <h4 class="preview-title" id="previewTitle"><?= h($old['title'] ?: 'İlan Başlığı') ?></h4>
            <p class="preview-description" id="previewDescription">
              <?= h($old['description'] ? mb_substr($old['description'], 0, 120) . (mb_strlen($old['description']) > 120 ? '...' : '') : 'Ürün açıklaması burada görünecek...') ?>
            </p>
            <div class="preview-price" id="previewPrice">₺<?= h($old['price'] ? number_format($old['price'], 2, ',', '.') : '0,00') ?></div>

            <div class="preview-meta">
              <div class="meta-item">
                <span class="meta-value" id="previewStock"><?= h($old['stock'] ?: '1') ?></span>
                <span class="meta-label">Stok</span>
              </div>
              <div class="meta-item">
                <span class="meta-value" id="previewCondition"><?= h($old['condition'] ?: '-') ?></span>
                <span class="meta-label">Durum</span>
              </div>
              <div class="meta-item">
                <span class="meta-value" id="previewYear"><?= h($old['year'] ?: '-') ?></span>
                <span class="meta-label">Yıl</span>
              </div>
            </div>
          </div>
        </div>

        <div class="tips">
          <h4><i data-lucide="lightbulb" class="w-4 h-4"></i> İpuçları</h4>
          <ul>
            <li>Net ve aydınlık fotoğraflar kullanın</li>
            <li>Doğru kategori seçimi arama sonuçlarında görünürlüğü artırır</li>
            <li>Detaylı açıklama alıcılar için daha güven vericidir</li>
            <li>Ürün durumunu doğru belirtin</li>
            <li>Gerçekçi fiyat belirleyin</li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <script>
    lucide.createIcons();

    const form = document.getElementById('listingForm');
    const fileInput = document.getElementById('fileInput');
    const fileUploadBtn = document.getElementById('fileUploadBtn');
    const dropZone = document.getElementById('dropZone');
    const filePreview = document.getElementById('filePreview');
    const previewImage = document.getElementById('previewImage');
    const formAction = document.getElementById('formAction');
    const draftBtn = document.getElementById('draftBtn');

    let uploadedFiles = [];
    let dt = new DataTransfer();

    fileUploadBtn.addEventListener('click', () => fileInput.click());

    fileInput.addEventListener('change', (e) => handleFiles(Array.from(e.target.files || [])));

    dropZone.addEventListener('dragover', (e) => {
      e.preventDefault();
      dropZone.classList.add('drag-over');
    });
    
    dropZone.addEventListener('dragleave', () => {
      dropZone.classList.remove('drag-over');
    });
    
    dropZone.addEventListener('drop', (e) => {
      e.preventDefault();
      dropZone.classList.remove('drag-over');
      handleFiles(Array.from(e.dataTransfer.files || []));
    });

    function handleFiles(files) {
      if (!files.length) return;

      if (uploadedFiles.length + files.length > 8) {
        alert('En fazla 8 fotoğraf yükleyebilirsiniz.');
        return;
      }

      for (const file of files) {
        if (!file.type.match('image.*')) {
          alert('Sadece resim dosyaları yükleyebilirsiniz.');
          continue;
        }
        
        if (file.size > 5 * 1024 * 1024) {
          alert("Dosya boyutu 5MB'dan büyük olamaz: " + file.name);
          continue;
        }

        uploadedFiles.push(file);
        dt.items.add(file);
      }

      fileInput.files = dt.files;
      renderPreviews();
      if (uploadedFiles.length) setMainPreview(uploadedFiles[0]);
    }

    function renderPreviews() {
      filePreview.innerHTML = '';
      uploadedFiles.forEach((file, i) => {
        const reader = new FileReader();
        reader.onload = (ev) => {
          const previewItem = document.createElement('div');
          previewItem.className = 'file-preview';
          previewItem.innerHTML = `
            <img src="${ev.target.result}" alt="${file.name}">
            <button type="button" class="file-preview-remove" data-index="${i}">
              <i data-lucide="x" class="w-3 h-3"></i>
            </button>
          `;
          filePreview.appendChild(previewItem);
          lucide.createIcons();

          previewItem.addEventListener('click', () => setMainPreview(file));

          previewItem.querySelector('.file-preview-remove').addEventListener('click', (e) => {
            e.stopPropagation();
            removeFile(i);
          });
        };
        reader.readAsDataURL(file);
      });
    }

    function removeFile(index) {
      if (!confirm('Bu fotoğrafı silmek istediğinize emin misiniz?')) return;

      uploadedFiles.splice(index, 1);

      dt = new DataTransfer();
      uploadedFiles.forEach(f => dt.items.add(f));
      fileInput.files = dt.files;

      renderPreviews();
      if (uploadedFiles.length) setMainPreview(uploadedFiles[0]);
      else {
        previewImage.innerHTML = '<div class="preview-image-placeholder"><i data-lucide="image" class="w-12 h-12"></i></div>';
        lucide.createIcons();
      }
    }

    function setMainPreview(file) {
      const reader = new FileReader();
      reader.onload = (ev) => {
        previewImage.innerHTML = `<img src="${ev.target.result}" alt="Önizleme">`;
      };
      reader.readAsDataURL(file);
    }

    // Character counters and live preview
    const titleInput = document.querySelector('input[name="title"]');
    const descriptionInput = document.querySelector('textarea[name="description"]');
    const titleCounter = document.getElementById('titleCounter');
    const descriptionCounter = document.getElementById('descriptionCounter');

    const previewTitle = document.getElementById('previewTitle');
    const previewCategory = document.getElementById('previewCategory');
    const previewDescription = document.getElementById('previewDescription');
    const previewPrice = document.getElementById('previewPrice');
    const previewStock = document.getElementById('previewStock');
    const previewCondition = document.getElementById('previewCondition');
    const previewYear = document.getElementById('previewYear');

    titleInput.addEventListener('input', () => {
      const length = titleInput.value.length;
      titleCounter.textContent = `${length}/100`;
      previewTitle.textContent = titleInput.value || 'İlan Başlığı';
    });

    descriptionInput.addEventListener('input', () => {
      const length = descriptionInput.value.length;
      descriptionCounter.textContent = `${length}/2000`;
      const v = descriptionInput.value || 'Ürün açıklaması burada görünecek...';
      previewDescription.textContent = (v.length > 120) ? (v.substring(0, 120) + '...') : v;
    });

    document.querySelector('select[name="category"]').addEventListener('change', (e) => {
      previewCategory.textContent = e.target.value || 'Kategori';
    });

    document.querySelector('input[name="price"]').addEventListener('input', (e) => {
      const p = parseFloat(e.target.value) || 0;
      previewPrice.textContent = '₺' + p.toLocaleString('tr-TR', { 
        minimumFractionDigits: 2, 
        maximumFractionDigits: 2 
      });
    });

    document.querySelector('input[name="stock"]').addEventListener('input', (e) => {
      previewStock.textContent = e.target.value || '1';
    });

    document.querySelector('select[name="condition"]').addEventListener('change', (e) => {
      previewCondition.textContent = e.target.value || '-';
    });

    document.querySelector('input[name="year"]').addEventListener('input', (e) => {
      previewYear.textContent = e.target.value || '-';
    });

    // Draft button
    draftBtn.addEventListener('click', () => {
      formAction.value = 'draft';
      form.submit();
    });

    // Publish button
    form.addEventListener('submit', (e) => {
      if (formAction.value !== 'draft') {
        formAction.value = 'publish';
      }
    });
  </script>
</body>
</html>