<?php
declare(strict_types=1);

/**
 * seller/ilanlar.php
 * - ✅ DB’den çeker (ilanlar + ilan_gorseller)
 * - ✅ Satıcı giriş kontrolü (require_role('seller'))
 * - ✅ Sil / Toplu işlemler DB üzerinde (seller_id kontrolü)
 * - ✅ Tasarım korunur
 * - ✅ SAĞ FİLTRELER ÇALIŞIR (Durum / Kategori / Stok)
 */

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'] ?? 0);

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

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

/* =========================
   STATUS NORMALIZE (ilanlar.durum: aktif/pasif/taslak)
========================= */
function normalize_status(string $s): string {
  $x = mb_strtolower(trim($s));
  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'], true) => 'taslak',
    default => ($x !== '' ? $x : 'taslak')
  };
}

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-600 border border-slate-200'],
    'taslak' => ['Taslak', 'bg-violet-100 text-violet-800 border border-violet-200'],
    default  => [ucfirst($durum ?: '—'), 'bg-gray-100 text-gray-700 border border-gray-200'],
  };
}

/* =========================
   SİLME / TOPLU İŞLEMLER (DB)
========================= */
$flash = '';

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

  // Tekil sil
  if ($action === 'delete') {
    $deleteId = (int)($_POST['id'] ?? 0);

    if ($deleteId > 0) {
      try {
        db()->prepare("DELETE FROM ilanlar WHERE id=? AND seller_id=?")->execute([$deleteId, $sellerId]);
        $flash = 'İlan başarıyla silindi.';
      } catch (Throwable $e) {
        $flash = 'Silme sırasında hata oluştu.';
      }
    }
  }

  // Toplu işlemler
  if (in_array($action, ['bulk_delete','bulk_deactivate','bulk_renew'], true)) {
    $ids = $_POST['ids'] ?? [];
    $ids = array_map('intval', is_array($ids) ? $ids : []);
    $ids = array_values(array_filter($ids, fn($v)=>$v>0));

    if (empty($ids)) {
      $flash = 'Önce en az 1 ilan seçmelisin.';
    } else {
      $placeholders = implode(',', array_fill(0, count($ids), '?'));

      try {
        if ($action === 'bulk_delete') {
          $params = array_merge($ids, [$sellerId]);
          db()->prepare("DELETE FROM ilanlar WHERE id IN ($placeholders) AND seller_id=?")->execute($params);
          $flash = 'Seçili ilanlar silindi.';
        }

        if ($action === 'bulk_deactivate') {
          $params = array_merge($ids, [$sellerId]);
          db()->prepare("UPDATE ilanlar SET durum='pasif', updated_at=NOW() WHERE id IN ($placeholders) AND seller_id=?")->execute($params);
          $flash = 'Seçili ilanlar pasifleştirildi.';
        }

        if ($action === 'bulk_renew') {
          // expires_at yok -> updated_at güncelle
          $params = array_merge($ids, [$sellerId]);
          db()->prepare("UPDATE ilanlar SET updated_at=NOW() WHERE id IN ($placeholders) AND seller_id=?")->execute($params);
          $flash = 'Seçili ilanlar yenilendi.';
        }

      } catch (Throwable $e) {
        $flash = 'Toplu işlem sırasında hata oluştu.';
      }
    }
  }
}

/* =========================
   SEARCH
========================= */
$q = trim((string)($_GET['q'] ?? ''));

/* =========================
   DB'DEN İLANLARI ÇEK (ilanlar + cover görsel)
========================= */
$ilanlar = [];

try {
  $sql = "
    SELECT
      i.id,
      i.baslik,
      i.kategori,
      i.fiyat,
      i.stok,
      i.durum,
      i.favori,
      i.goruntulenme,
      i.created_at,
      i.updated_at,
      (
        SELECT ig.url
        FROM ilan_gorseller ig
        WHERE ig.ilan_id = i.id
        ORDER BY ig.is_cover DESC, ig.sort_order ASC, ig.id ASC
        LIMIT 1
      ) AS gorsel
    FROM ilanlar i
    WHERE i.seller_id = ?
      " . ($q !== '' ? " AND (i.baslik LIKE ? OR i.kategori LIKE ?) " : "") . "
    ORDER BY i.created_at DESC
  ";

  $st = db()->prepare($sql);
  if ($q !== '') {
    $like = "%{$q}%";
    $st->execute([$sellerId, $like, $like]);
  } else {
    $st->execute([$sellerId]);
  }

  foreach ($st->fetchAll() as $r) {
    $ilanlar[] = [
      'id'           => (int)($r['id'] ?? 0),
      'baslik'       => (string)($r['baslik'] ?? 'İlan'),
      'kategori'     => (string)($r['kategori'] ?? 'Genel'),
      'fiyat'        => (float)($r['fiyat'] ?? 0),
      'stok'         => (int)($r['stok'] ?? 0),
      'durum'        => normalize_status((string)($r['durum'] ?? 'taslak')),
      'favori'       => (int)($r['favori'] ?? 0),
      'goruntulenme' => (int)($r['goruntulenme'] ?? 0),
      'created_at'   => (string)($r['created_at'] ?? ''),
      'updated_at'   => (string)($r['updated_at'] ?? ''),
      'gorsel'       => (string)($r['gorsel'] ?? ''),
    ];
  }

} catch (Throwable $e) {
  $ilanlar = [];
}

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8" />
  <title>Satıcı Paneli — İlanlar</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>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

  <style>
    :root {
      --primary: #000000;
      --primary-gradient: linear-gradient(135deg, #000000 0%, #2D2D2D 100%);
      --card-gradient: linear-gradient(180deg, #FFFFFF 0%, #FCFCFC 100%);
      --accent: #7C3AED;
      --accent-light: #8B5CF6;
      --success: #10B981;
      --warning: #F59E0B;
      --danger: #EF4444;
      --info: #3B82F6;

      --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: #1E293B;
      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 0.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;
      display: flex;
      flex-direction: column;
    }

    @media (min-width: 768px) { .page-content { padding: 1.5rem 1.25rem; } }
    @media (min-width: 1024px) { .page-content { padding: 2rem; flex-direction: row; gap: 2rem; } }

    .main-content { flex: 1; min-width: 0; }

    .filter-sidebar { width: 100%; margin-bottom: 1.5rem; }
    @media (min-width: 1024px) { .filter-sidebar { width: 320px; margin-bottom: 0; flex-shrink: 0; } }

    .filter-card {
      background: var(--card-gradient);
      border-radius: var(--radius-xl);
      padding: 1.5rem;
      border: 1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
      margin-bottom: 1.5rem;
    }

    .filter-title {
      font-size: 1rem;
      font-weight: 800;
      color: #0F172A;
      margin-bottom: 1rem;
      display: flex;
      align-items: center;
      gap: 0.5rem;
    }

    .filter-options { display: flex; flex-direction: column; gap: 0.75rem; }

    .filter-option {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem;
      border-radius: var(--radius-md);
      transition: var(--transition);
      cursor: pointer;
    }

    .filter-option:hover { background: #F8FAFC; }
    .filter-option.active { background: #F5F3FF; color: #7C3AED; font-weight: 600; }

    .filter-option input[type="checkbox"] {
      width: 1rem;
      height: 1rem;
      border-radius: 4px;
      accent-color: #000000;
    }

    .filter-count {
      margin-left: auto;
      font-size: 0.75rem;
      color: #64748B;
      background: #F1F5F9;
      padding: 0.125rem 0.375rem;
      border-radius: var(--radius-sm);
      min-width: 1.75rem;
      text-align: center;
    }

    .status-filter {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 0.5rem;
    }

    .status-option {
      padding: 0.5rem;
      border-radius: var(--radius-md);
      text-align: center;
      font-size: 0.8125rem;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      border: 1px solid #E2E8F0;
      user-select: none;
    }

    .status-option:hover { transform: translateY(-1px); box-shadow: var(--shadow-sm); }
    .status-option.active { border-color: #000000; background: #000000; color: white; }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 0.75rem;
      margin-bottom: 1.5rem;
    }

    @media (min-width: 640px) { .stats-grid { grid-template-columns: repeat(4, 1fr); } }

    .stat-card {
      background: var(--card-gradient);
      border-radius: var(--radius-lg);
      padding: 1rem;
      border: 1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
      transition: var(--transition);
      position: relative;
      overflow: hidden;
    }

    .stat-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); border-color: #CBD5E1; }

    .stat-value { font-size: 1.25rem; font-weight: 900; color: #0F172A; line-height: 1; margin-bottom: 0.25rem; }
    .stat-label { font-size: 0.75rem; color: #64748B; font-weight: 500; }

    .page-header { display: flex; flex-direction: column; gap: 1rem; margin-bottom: 1.5rem; }
    @media (min-width: 768px) { .page-header { flex-direction: row; align-items: flex-end; justify-content: space-between; } }

    .page-title { font-size: 1.5rem; font-weight: 900; color: #0F172A; line-height: 1.2; letter-spacing: -0.02em; }
    .page-subtitle { font-size: 0.875rem; color: #64748B; font-weight: 500; margin-top: 0.25rem; }

    .toolbar {
      background: var(--card-gradient);
      border-radius: var(--radius-xl);
      padding: 1.25rem;
      border: 1px solid #E2E8F0;
      box-shadow: var(--shadow-sm);
      margin-bottom: 1.5rem;
    }

    .toolbar-content { display: flex; flex-direction: column; gap: 1.25rem; }
    @media (min-width: 768px) { .toolbar-content { flex-direction: row; align-items: center; justify-content: space-between; } }

    .toolbar-left, .toolbar-right { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; }

    .btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      padding: 0.5rem 1rem;
      border-radius: var(--radius-md);
      font-weight: 600;
      font-size: 0.8125rem;
      transition: var(--transition);
      border: none;
      cursor: pointer;
      white-space: nowrap;
      text-decoration: none;
    }

    .btn-primary {
      background: var(--primary-gradient);
      color: white;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    .btn-primary:hover {
      background: linear-gradient(135deg, #111111 0%, #333333 100%);
      transform: translateY(-1px);
      box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
    }

    .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);
    }

    .search-box { position: relative; min-width: 200px; }
    @media (min-width: 768px) { .search-box { min-width: 240px; } }

    .search-input {
      width: 100%;
      padding: 0.625rem 0.875rem 0.625rem 2.5rem;
      border-radius: var(--radius-md);
      border: 1px solid #E2E8F0;
      background: white;
      font-size: 0.8125rem;
      font-weight: 500;
      transition: var(--transition);
    }

    .search-input:focus {
      outline: none;
      border-color: var(--accent);
      box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.1);
    }

    .search-icon {
      position: absolute;
      left: 0.875rem;
      top: 50%;
      transform: translateY(-50%);
      color: #94A3B8;
      font-size: 0.875rem;
    }

    .products-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 0.75rem; }
    @media (min-width: 640px) { .products-grid { grid-template-columns: repeat(3, 1fr); gap: 1rem; } }
    @media (min-width: 1024px) { .products-grid { grid-template-columns: repeat(4, 1fr); gap: 1.25rem; } }
    @media (min-width: 1400px) { .products-grid { grid-template-columns: repeat(5, 1fr); gap: 1.25rem; } }

    .product-card {
      background: white;
      border-radius: var(--radius-lg);
      box-shadow: var(--shadow-sm);
      transition: var(--transition);
      border: 1px solid #E2E8F0;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      height: 260px;
    }
    @media (min-width: 1024px) { .product-card { height: 280px; } }
    .product-card:hover { transform: translateY(-4px); box-shadow: var(--shadow-lg); border-color: #CBD5E1; }

    .image-container { position: relative; height: 120px; overflow: hidden; background: linear-gradient(135deg, #F1F5F9 0%, #E2E8F0 100%); }
    .product-image { width: 100%; height: 100%; object-fit: cover; transition: transform 0.6s ease; }
    .product-card:hover .product-image { transform: scale(1.05); }

    .product-badges {
      position: absolute;
      top: 0.5rem;
      left: 0.5rem;
      right: 0.5rem;
      display: flex;
      justify-content: space-between;
      z-index: 10;
    }

    .status-badge {
      padding: 0.25rem 0.5rem;
      border-radius: var(--radius-sm);
      font-size: 0.6875rem;
      font-weight: 700;
      letter-spacing: 0.02em;
      backdrop-filter: blur(8px);
      background: rgba(255, 255, 255, 0.9);
      border: 1px solid rgba(255, 255, 255, 0.2);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .checkbox-badge {
      width: 1.75rem;
      height: 1.75rem;
      border-radius: var(--radius-sm);
      background: rgba(255, 255, 255, 0.9);
      border: 1px solid rgba(255, 255, 255, 0.2);
      backdrop-filter: blur(8px);
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .checkbox-badge input { width: 0.875rem; height: 0.875rem; border-radius: 3px; cursor: pointer; accent-color: #000000; }

    .product-content {
      padding: 0.75rem;
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 0.45rem;
    }

    .product-meta {
      display:flex;
      align-items:center;
      justify-content:space-between;
      gap:.5rem;
    }
    .product-id { font-size: 0.625rem; color: #94A3B8; font-weight: 700; }
    .product-kategori { font-size: 0.625rem; color:#64748B; font-weight: 700; }

    .product-title {
      font-size: 0.8rem;
      font-weight: 800;
      color: #0F172A;
      line-height: 1.25;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      min-height: 2em;
      margin-top: .05rem;
    }

    .price-section { display: flex; align-items: baseline; justify-content: space-between; gap: 0.5rem; margin-top: .1rem; }
    .current-price { font-size: 1.05rem; font-weight: 900; color: #0F172A; line-height: 1; }

    .mini-stats {
      font-size: 0.6875rem;
      color:#64748B;
      font-weight: 600;
      padding-top: .35rem;
      border-top: 1px solid #F1F5F9;
      margin-top: .25rem;
      display:flex;
      gap:.45rem;
      flex-wrap: wrap;
    }
    .mini-dot{ opacity:.6; }

    .stock-badge {
      font-size: 0.625rem;
      font-weight: 800;
      color: #EF4444;
      background: rgba(239, 68, 68, 0.1);
      padding: 0.125rem 0.375rem;
      border-radius: var(--radius-sm);
      white-space: nowrap;
    }

    .product-actions {
      display: flex;
      align-items: center;
      gap: 0.375rem;
      padding: 0.5rem;
      border-top: 1px solid #F1F5F9;
      background: #F8FAFC;
    }

    .action-btn {
      flex: 1;
      padding: 0.375rem;
      border-radius: var(--radius-md);
      font-weight: 600;
      font-size: 0.6875rem;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.25rem;
      transition: var(--transition);
      border: none;
      cursor: pointer;
      text-decoration: none;
    }

    .action-btn-edit { background: white; color: #334155; border: 1px solid #E2E8F0; }
    .action-btn-edit:hover { background: #F8FAFC; border-color: #CBD5E1; transform: translateY(-1px); }

    .dropdown-menu {
      position: absolute;
      right: 0.75rem;
      bottom: 3rem;
      width: 140px;
      background: white;
      border-radius: var(--radius-lg);
      box-shadow: var(--shadow-xl);
      border: 1px solid #E2E8F0;
      overflow: hidden;
      z-index: 50;
      display: none;
      animation: slideUp 0.2s ease;
    }

    @keyframes slideUp {
      from { opacity: 0; transform: translateY(10px); }
      to   { opacity: 1; transform: translateY(0); }
    }

    .dropdown-menu.show { display: block; }

    .dropdown-item {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.5rem 0.75rem;
      font-size: 0.6875rem;
      font-weight: 500;
      color: #334155;
      text-decoration: none;
      transition: var(--transition);
      border: none;
      background: none;
      width: 100%;
      text-align: left;
      cursor: pointer;
    }

    .dropdown-item:hover { background:#F8FAFC; }
    .dropdown-item.danger { color:#B91C1C; }
    .dropdown-item.danger:hover { background: rgba(239,68,68,.08); }

    .flash-message {
      background: linear-gradient(135deg, rgba(16, 185, 129, 0.1), rgba(16, 185, 129, 0.05));
      border: 1px solid rgba(16, 185, 129, 0.2);
      border-radius: var(--radius-lg);
      padding: 0.875rem 1rem;
      margin-bottom: 1.5rem;
      display: flex;
      align-items: center;
      gap: 0.625rem;
      animation: slideIn 0.5s ease;
    }

    .empty-state {
      background: var(--card-gradient);
      border-radius: var(--radius-xl);
      padding: 2.5rem 1.5rem;
      border: 2px dashed #E2E8F0;
      text-align: center;
      grid-column: 1 / -1;
    }

    .empty-state-icon {
      width: 3.5rem;
      height: 3.5rem;
      margin: 0 auto 1.25rem;
      border-radius: var(--radius-full);
      background: linear-gradient(135deg, #F1F5F9 0%, #E2E8F0 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #94A3B8;
    }

    .empty-state-title { font-size: 1.25rem; font-weight: 700; color: #0F172A; margin-bottom: 0.5rem; }
    .empty-state-description { color: #64748B; max-width: 350px; margin: 0 auto 1.25rem; line-height: 1.5; font-size: 0.875rem; }

    @media (max-width: 480px) {
      .page-content { padding: 1rem 0.875rem; }
      .page-title { font-size: 1.25rem; }
      .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 0.5rem; }
      .toolbar { padding: 1rem; }
      .product-card { height: 250px; }
      .image-container { height: 100px; }
    }

    @media (max-width: 360px) { .products-grid { grid-template-columns: 1fr; } }
  </style>
</head>

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

    <div class="main-content">
      <header class="page-header">
        <div>
          <h1 class="page-title">İlanlarım</h1>
          <p class="page-subtitle">Sanat eserlerinizi yönetin</p>
        </div>

        <a href="urun-ekle.php" class="btn btn-primary">
          <i data-lucide="plus" class="w-3.5 h-3.5"></i>
          Yeni Ekle
        </a>
      </header>

      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-value"><?= count($ilanlar) ?></div>
          <div class="stat-label">Toplam İlan</div>
        </div>

        <div class="stat-card">
          <div class="stat-value"><?= count(array_filter($ilanlar, fn($x) => normalize_status((string)($x['durum'] ?? '')) === 'aktif')) ?></div>
          <div class="stat-label">Aktif</div>
        </div>

        <div class="stat-card">
          <div class="stat-value"><?= array_sum(array_map(fn($x)=> (int)($x['favori'] ?? 0), $ilanlar)) ?></div>
          <div class="stat-label">Favori</div>
        </div>

        <div class="stat-card">
          <div class="stat-value"><?= array_sum(array_map(fn($x)=> (int)($x['goruntulenme'] ?? 0), $ilanlar)) ?></div>
          <div class="stat-label">Görüntülenme</div>
        </div>
      </div>

      <?php if ($flash): ?>
      <div class="flash-message">
        <div class="flash-icon">
          <i data-lucide="check-circle" class="w-4 h-4"></i>
        </div>
        <div class="flash-text"><?= h($flash) ?></div>
      </div>
      <?php endif; ?>

      <div class="toolbar">
        <div class="toolbar-content">
          <div class="toolbar-left">
            <form id="bulkForm" method="post"></form>

            <button type="submit" form="bulkForm" name="action" value="bulk_renew" class="btn btn-secondary">
              <i data-lucide="refresh-cw" class="w-3.5 h-3.5"></i>
              Yenile
            </button>

            <button type="submit" form="bulkForm" name="action" value="bulk_deactivate" class="btn btn-secondary">
              <i data-lucide="pause" class="w-3.5 h-3.5"></i>
              Pasifleştir
            </button>

            <button type="submit" form="bulkForm" name="action" value="bulk_delete" class="btn btn-danger">
              <i data-lucide="trash-2" class="w-3.5 h-3.5"></i>
              Sil
            </button>
          </div>

          <div class="toolbar-right">
            <form method="get" class="search-box">
              <div class="search-icon">
                <i data-lucide="search" class="w-3.5 h-3.5"></i>
              </div>
              <input
                type="text"
                name="q"
                value="<?= h($q) ?>"
                placeholder="İlan ara..."
                class="search-input"
              />
            </form>
          </div>
        </div>
      </div>

      <?php if (empty($ilanlar)): ?>
        <div class="empty-state">
          <div class="empty-state-icon">
            <i data-lucide="package" class="w-6 h-6"></i>
          </div>
          <h2 class="empty-state-title">Henüz ilanınız yok</h2>
          <p class="empty-state-description">
            İlk sanat eserinizi ekleyerek satışa başlayın.
          </p>
          <a href="urun-ekle.php" class="btn btn-primary">
            <i data-lucide="plus" class="w-3.5 h-3.5"></i>
            İlk İlanını Ekle
          </a>
        </div>
      <?php else: ?>

        <section class="products-grid" id="productsGrid">
          <?php foreach ($ilanlar as $ilan): ?>
            <?php
              $id = (int)($ilan['id'] ?? 0);
              $img = trim((string)($ilan['gorsel'] ?? ''));
              if ($img === '') $img = 'https://picsum.photos/seed/ilan-'.$id.'/600/600';

              [$dLabel, $dClass] = durum_pill((string)($ilan['durum'] ?? 'taslak'));

              $stok = (int)($ilan['stok'] ?? 0);
              $fiyat = (float)($ilan['fiyat'] ?? 0);
              $kategori = (string)($ilan['kategori'] ?? 'Genel');
              $favori = (int)($ilan['favori'] ?? 0);
              $goruntulenme = (int)($ilan['goruntulenme'] ?? 0);
              $updatedAt = (string)($ilan['updated_at'] ?? '');
              $statusNorm = normalize_status((string)($ilan['durum'] ?? 'taslak'));
            ?>

            <article
              class="product-card"
              data-id="<?= $id ?>"
              data-status="<?= h($statusNorm) ?>"
              data-category="<?= h($kategori) ?>"
              data-stock="<?= (int)$stok ?>"
              data-fav="<?= (int)$favori ?>"
              data-updated="<?= h($updatedAt) ?>"
            >
              <div class="image-container">
                <img src="<?= h($img) ?>" alt="<?= h($ilan['baslik'] ?? 'İlan') ?>" class="product-image" loading="lazy">

                <div class="product-badges">
                  <div class="status-badge <?= h($dClass) ?>">
                    <?= h($dLabel) ?>
                  </div>

                  <div class="checkbox-badge">
                    <input form="bulkForm" type="checkbox" name="ids[]" value="<?= $id ?>" class="row-checkbox">
                  </div>
                </div>
              </div>

              <div class="product-content">
                <div class="product-meta">
                  <span class="product-kategori"><?= h($kategori) ?></span>
                  <span class="product-id">#<?= $id ?></span>
                </div>

                <h3 class="product-title"><?= h($ilan['baslik'] ?? 'İlan') ?></h3>

                <div class="price-section">
                  <span class="current-price"><?= number_format($fiyat, 2, ',', '.') ?> ₺</span>
                  <?php if ($stok <= 3 && $stok > 0): ?>
                    <span class="stock-badge">Son <?= $stok ?></span>
                  <?php elseif ($stok === 0): ?>
                    <span class="stock-badge">Tükendi</span>
                  <?php endif; ?>
                </div>

                <div class="mini-stats">
                  <span>Stok: <b class="text-slate-900"><?= $stok ?></b></span>
                  <span class="mini-dot">•</span>
                  <span>Favori: <b class="text-slate-900"><?= $favori ?></b></span>
                  <span class="mini-dot">•</span>
                  <span>Görüntü: <b class="text-slate-900"><?= $goruntulenme ?></b></span>
                </div>
              </div>

              <div class="product-actions">
                <a href="ilan-duzenle.php?id=<?= $id ?>" class="action-btn action-btn-edit">
                  <i data-lucide="edit" class="w-3 h-3"></i>
                  Düzenle
                </a>

                <div class="relative">
                  <button type="button" class="action-btn action-btn-edit menu-toggle" data-id="<?= $id ?>">
                    <i data-lucide="more-vertical" class="w-3 h-3"></i>
                  </button>

                  <div class="dropdown-menu" id="menu-<?= $id ?>">
                    <a href="ilan-duzenle.php?id=<?= $id ?>" class="dropdown-item">
                      <i data-lucide="edit" class="w-3 h-3"></i>
                      Düzenle
                    </a>

                    <button type="button" class="dropdown-item" onclick="window.open('ilan-detay.php?id=<?= $id ?>', '_blank')">
                      <i data-lucide="eye" class="w-3 h-3"></i>
                      Görüntüle
                    </button>

                    <button type="button" class="dropdown-item" onclick="navigator.clipboard?.writeText(String(window.location.origin + '/ilan-detay.php?id=<?= $id ?>'))">
                      <i data-lucide="copy" class="w-3 h-3"></i>
                      Kopyala
                    </button>

                    <form method="post" onsubmit="return confirm('Bu ilanı silmek istediğinizden emin misiniz?');">
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="id" value="<?= $id ?>">
                      <button type="submit" class="dropdown-item danger">
                        <i data-lucide="trash-2" class="w-3 h-3"></i>
                        Sil
                      </button>
                    </form>
                  </div>
                </div>
              </div>
            </article>

          <?php endforeach; ?>
        </section>

      <?php endif; ?>
    </div>

    <aside class="filter-sidebar" id="filterSidebar">
      <div class="filter-card">
        <h3 class="filter-title">
          <i data-lucide="filter"></i>
          Durum
        </h3>

        <div class="status-filter" id="statusFilter">
          <div class="status-option active" data-status-filter="aktif">Aktif</div>
          <div class="status-option" data-status-filter="pasif">Pasif</div>
          <div class="status-option" data-status-filter="expired">Süresi Dolan</div>
          <div class="status-option" data-status-filter="out">Tükendi</div>
          <div class="status-option" data-status-filter="taslak">Taslak</div>
          <div class="status-option" data-status-filter="featured">Öne Çıkan</div>
        </div>
      </div>

      <div class="filter-card">
        <h3 class="filter-title">
          <i data-lucide="tag"></i>
          Kategoriler
        </h3>

        <div class="filter-options" id="categoryFilters">
          <?php
            $categories = array_values(array_unique(array_map(fn($x)=> (string)($x['kategori'] ?? 'Genel'), $ilanlar)));
            if (empty($categories)) $categories = ['Genel'];
            foreach ($categories as $category):
              $count = count(array_filter($ilanlar, fn($x) => (string)($x['kategori'] ?? 'Genel') === $category));
          ?>
          <label class="filter-option category-filter" data-category="<?= h($category) ?>">
            <input type="checkbox" checked value="<?= h($category) ?>" class="category-checkbox">
            <span><?= h($category) ?></span>
            <span class="filter-count"><?= $count ?></span>
          </label>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="filter-card">
        <h3 class="filter-title">
          <i data-lucide="package"></i>
          Stok Durumu
        </h3>

        <div class="filter-options" id="stockFilters">
          <label class="filter-option stock-filter" data-stock-filter="in">
            <input type="checkbox" checked value="in" class="stock-checkbox">
            <span>Stokta var (<?= count(array_filter($ilanlar, fn($x) => (int)($x['stok'] ?? 0) > 0)) ?>)</span>
          </label>
          <label class="filter-option stock-filter" data-stock-filter="low">
            <input type="checkbox" value="low" class="stock-checkbox">
            <span>Az stok (1-3)</span>
            <span class="filter-count"><?= count(array_filter($ilanlar, fn($x) => (int)($x['stok'] ?? 0) > 0 && (int)($x['stok'] ?? 0) <= 3)) ?></span>
          </label>
          <label class="filter-option stock-filter" data-stock-filter="out">
            <input type="checkbox" value="out" class="stock-checkbox">
            <span>Stokta yok</span>
            <span class="filter-count"><?= count(array_filter($ilanlar, fn($x) => (int)($x['stok'] ?? 0) === 0)) ?></span>
          </label>
        </div>
      </div>
    </aside>

  </div>
</main>

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

    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);

    let activeMenu = null;

    document.addEventListener('click', function(e) {
      const menuToggle = e.target.closest('.menu-toggle');
      const dropdownMenu = e.target.closest('.dropdown-menu');

      document.querySelectorAll('.dropdown-menu').forEach(menu => menu.classList.remove('show'));

      if (menuToggle) {
        e.preventDefault();
        e.stopPropagation();
        const productId = menuToggle.getAttribute('data-id');
        const menu = document.getElementById(`menu-${productId}`);
        if (menu && menu !== activeMenu) {
          menu.classList.add('show');
          activeMenu = menu;
        } else {
          activeMenu = null;
        }
      }

      if (!dropdownMenu && !menuToggle) activeMenu = null;
    });

    window.addEventListener('scroll', function() {
      if (activeMenu) {
        activeMenu.classList.remove('show');
        activeMenu = null;
      }
    });

    const bulkForm = document.getElementById('bulkForm');
    if (bulkForm) {
      bulkForm.addEventListener('submit', function(e) {
        const submitButton = e.submitter;
        const action = submitButton?.value;

        const checkedBoxes = document.querySelectorAll('.row-checkbox:checked');
        if (checkedBoxes.length === 0) {
          e.preventDefault();
          alert('Önce en az 1 ilan seçmelisin.');
          return;
        }

        if (action && action.includes('delete')) {
          if (!confirm(`${checkedBoxes.length} ilanı silmek istediğinizden emin misiniz?`)) {
            e.preventDefault();
          }
        }
      });
    }

    /* =========================
       ✅ SAĞ FİLTRELER (ÇALIŞIR)
       - Tasarım aynı, sadece JS ile kartları gizle/göster
    ========================= */
    const cards = Array.from(document.querySelectorAll('.product-card'));
    const statusOptions = Array.from(document.querySelectorAll('.status-option'));
    const categoryCheckboxes = Array.from(document.querySelectorAll('.category-checkbox'));
    const stockCheckboxes = Array.from(document.querySelectorAll('.stock-checkbox'));

    let filterTouched = false;

    function markTouched() { filterTouched = true; }

    function parseDateSafe(s) {
      if (!s) return null;
      const d = new Date(String(s).replace(' ', 'T'));
      return isNaN(d.getTime()) ? null : d;
    }

    function isExpired(updatedAtStr) {
      const d = parseDateSafe(updatedAtStr);
      if (!d) return false;
      const now = new Date();
      const diffDays = (now.getTime() - d.getTime()) / (1000 * 60 * 60 * 24);
      return diffDays >= 30; // ✅ "Süresi dolan" için pratik eşik
    }

    function getActiveStatusFilter() {
      const active = statusOptions.find(x => x.classList.contains('active'));
      return active ? (active.getAttribute('data-status-filter') || '') : '';
    }

    function getSelectedCategories() {
      const selected = categoryCheckboxes.filter(c => c.checked).map(c => c.value);
      return selected;
    }

    function getSelectedStock() {
      const selected = stockCheckboxes.filter(c => c.checked).map(c => c.value);
      return selected;
    }

    function applyFilters() {
      if (!filterTouched) return; // ✅ ilk açılışta listeyi bozma

      const statusFilter = getActiveStatusFilter(); // aktif/pasif/taslak/expired/out/featured
      const cats = getSelectedCategories();
      const stocks = getSelectedStock();

      const allCatsSelected = (cats.length === categoryCheckboxes.length);
      const allStockNone = (stocks.length === 0);

      cards.forEach(card => {
        const st = card.getAttribute('data-status') || '';
        const cat = card.getAttribute('data-category') || '';
        const stock = parseInt(card.getAttribute('data-stock') || '0', 10);
        const fav = parseInt(card.getAttribute('data-fav') || '0', 10);
        const upd = card.getAttribute('data-updated') || '';

        // category match
        const catOK = allCatsSelected ? true : cats.includes(cat);

        // stock match
        let stockOK = true;
        if (!allStockNone) {
          const groupIn  = stock > 0;
          const groupLow = stock > 0 && stock <= 3;
          const groupOut = stock === 0;
          stockOK = (
            (stocks.includes('in')  && groupIn) ||
            (stocks.includes('low') && groupLow) ||
            (stocks.includes('out') && groupOut)
          );
        }

        // status match
        let statusOK = true;
        if (statusFilter === 'aktif' || statusFilter === 'pasif' || statusFilter === 'taslak') {
          statusOK = (st === statusFilter);
        } else if (statusFilter === 'out') {
          statusOK = (stock === 0);
        } else if (statusFilter === 'expired') {
          statusOK = isExpired(upd);
        } else if (statusFilter === 'featured') {
          statusOK = (fav > 0);
        }

        const show = catOK && stockOK && statusOK;
        card.style.display = show ? '' : 'none';
      });
    }

    // status click
    statusOptions.forEach(option => {
      option.addEventListener('click', function() {
        markTouched();
        statusOptions.forEach(opt => opt.classList.remove('active'));
        this.classList.add('active');
        applyFilters();
      });
    });

    // checkbox click/changes
    document.querySelectorAll('.filter-option').forEach(option => {
      option.addEventListener('click', function(e) {
        // mevcut davranış (tasarım korunur)
        if (e.target.tagName === 'INPUT') return;
        const checkbox = this.querySelector('input[type="checkbox"]');
        if (checkbox) {
          checkbox.checked = !checkbox.checked;
          this.classList.toggle('active', checkbox.checked);
          markTouched();
          applyFilters();
        }
      });
    });

    categoryCheckboxes.forEach(ch => {
      ch.addEventListener('change', () => { markTouched(); applyFilters(); });
    });

    stockCheckboxes.forEach(ch => {
      ch.addEventListener('change', () => { markTouched(); applyFilters(); });
    });
  });
</script>
</body>
</html>
