<?php
declare(strict_types=1);

/**
 * DISLAB - Modern Hizmet Kataloğu Yönetimi (TAM SÜRÜM)
 * Fonksiyonel yapı korunmuş, arayüz modernize edilmiştir.
 */

if (session_status() === PHP_SESSION_NONE) { session_start(); }

/* ---------------------------------------------------------
   0) Helpers
------------------------------------------------------------ */
if (!function_exists('h')) {
  function h(?string $s): string { return htmlspecialchars((string)($s ?? ''), ENT_QUOTES, 'UTF-8'); }
}
function xmlv(?string $s): string {
  return htmlspecialchars((string)($s ?? ''), ENT_XML1 | ENT_COMPAT, 'UTF-8');
}
function json_out(array $arr): void {
  while (ob_get_level()) { ob_end_clean(); }
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($arr, JSON_UNESCAPED_UNICODE);
  exit;
}

/* ---------------------------------------------------------
   1) DB Obj Bul
------------------------------------------------------------ */
global $db, $conn, $pdo;
$db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);
if (!$db_obj) {
  $db_path = realpath(__DIR__ . '/../core/db.php');
  if ($db_path && file_exists($db_path)) { require_once $db_path; }
  $db_obj = is_object($db) ? $db : (is_object($conn) ? $conn : $pdo);
}
if (!$db_obj) { die("DB bağlantısı bulunamadı."); }

/* ---------------------------------------------------------
   TOPBAR include (auto-discover)
------------------------------------------------------------ */
$topbar_file = null;
$topbar_candidates = [
  __DIR__ . '/topbar.php',
  __DIR__ . '/../topbar.php',
  __DIR__ . '/../partials/topbar.php',
  __DIR__ . '/../includes/topbar.php',
  __DIR__ . '/../layout/topbar.php',
  __DIR__ . '/../ui/topbar.php',
];
foreach ($topbar_candidates as $p) { if (is_file($p)) { $topbar_file = $p; break; } }

/* ---------------------------------------------------------
   2) Kolon Var mı? (cache)
------------------------------------------------------------ */
$__col_cache = [];
function has_col(PDO $pdo, string $table, string $col): bool {
  global $__col_cache;
  $key = $table . ':' . $col;
  if (isset($__col_cache[$key])) return $__col_cache[$key];
  $sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?";
  $st = $pdo->prepare($sql);
  $st->execute([$table, $col]);
  $__col_cache[$key] = ((int)$st->fetchColumn() > 0);
  return $__col_cache[$key];
}

/* ---------------------------------------------------------
   3) Aktif Konfig
------------------------------------------------------------ */
$conf = $db_obj->query("SELECT * FROM dislab_tanimlari WHERE is_active = 1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: null;

/* ---------------------------------------------------------
   4) SOAP: HizmetListesiGetir
------------------------------------------------------------ */
function dislab_fetch_catalog(PDO $pdo, array $conf): array {
  if (!$conf || empty($conf['ws_url'])) { throw new Exception("Aktif dışlab tanımı bulunamadı."); }
  $pass = (string)($conf['pass_enc'] ?? '');
  $xml_payload = '<?xml version="1.0" encoding="utf-8"?>
  <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
      <HizmetListesiGetir xmlns="http://tenay.com.tr/">
        <kurumbilgileri>
          <WebUserKurumId>0</WebUserKurumId>
          <KullaniciAdi>'.xmlv((string)$conf['username']).'</KullaniciAdi>
          <Sifre>'.xmlv($pass).'</Sifre>
          <Kodu>'.xmlv((string)$conf['kurum_kodu']).'</Kodu>
          <KurumKodu>'.xmlv((string)$conf['kurum_kodu']).'</KurumKodu>
        </kurumbilgileri>
      </HizmetListesiGetir>
    </soap:Body>
  </soap:Envelope>';

  $ch = curl_init((string)$conf['ws_url']);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $xml_payload,
    CURLOPT_HTTPHEADER => ['Content-Type: text/xml; charset=utf-8', 'SOAPAction: "http://tenay.com.tr/HizmetListesiGetir"'],
    CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_TIMEOUT => 90,
  ]);
  $response = curl_exec($ch);
  curl_close($ch);

  $clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:', 'diffgr:', 'msdata:'], '', (string)$response);
  $xml = @simplexml_load_string($clean_xml);
  if (!$xml) throw new Exception("SOAP XML parse edilemedi.");
  $items = $xml->xpath('//*[local-name()="Detay"]');
  if (!$items) return [];

  $out = [];
  foreach ($items as $item) {
    $code = trim((string)$item->Kodu);
    if ($code === '') continue;
    $out[$code] = [
      'dislab_id' => (string)$item->Id, 'dislab_kodu' => $code, 'dislab_adi' => (string)$item->Adi,
      'sut_kodu' => (string)$item->SutKodu, 'ornek_tur_id' => (string)$item->OrnekTurId,
      'ornek_tur_adi' => (string)$item->OrnekTurAdi, 'kap_id' => (string)$item->KapId, 'kap_adi' => (string)$item->KapAdi,
    ];
  }
  return $out;
}

/* ---------------------------------------------------------
   5) AJAX Actions
------------------------------------------------------------ */
if (isset($_GET['action'])) {
  try {
    $action = (string)$_GET['action'];
    $raw = file_get_contents('php://input');
    $payload = $raw ? json_decode($raw, true) : [];

    if ($action === 'sync_all') {
      $catalog = dislab_fetch_catalog($db_obj, (array)$conf);
      $stats = ['added' => 0, 'updated' => 0, 'total_from_ws' => count($catalog)];
      $has_last_sync = has_col($db_obj, 'dislab_test_listesi', 'last_sync');
      $db_obj->beginTransaction();
      $check = $db_obj->prepare("SELECT id FROM dislab_test_listesi WHERE dislab_kodu = ? LIMIT 1");

      foreach ($catalog as $code => $row) {
        $check->execute([$code]);
        $exists = $check->fetch(PDO::FETCH_ASSOC);
        if ($exists) {
          $up = $db_obj->prepare("UPDATE dislab_test_listesi SET dislab_id=?, dislab_adi=?, sut_kodu=?, ornek_tur_id=?, ornek_tur_adi=?, kap_id=?, kap_adi=?, last_sync=" . ($has_last_sync ? "NOW()" : "NULL") . " WHERE dislab_kodu=?");
          $up->execute([$row['dislab_id'], $row['dislab_adi'], $row['sut_kodu'], $row['ornek_tur_id'], $row['ornek_tur_adi'], $row['kap_id'], $row['kap_adi'], $code]);
          $stats['updated']++;
        } else {
          $ins = $db_obj->prepare("INSERT INTO dislab_test_listesi (dislab_id, dislab_kodu, dislab_adi, sut_kodu, ornek_tur_id, ornek_tur_adi, kap_id, kap_adi, is_active, last_sync) VALUES (?,?,?,?,?,?,?,?,1," . ($has_last_sync ? "NOW()" : "NULL") . ")");
          $ins->execute([$row['dislab_id'], $row['dislab_kodu'], $row['dislab_adi'], $row['sut_kodu'], $row['ornek_tur_id'], $row['ornek_tur_adi'], $row['kap_id'], $row['kap_adi']]);
          $stats['added']++;
        }
      }
      $db_obj->commit();
      json_out(['success' => true, 'stats' => $stats]);
    }

    if ($action === 'fetch_list') {
      $q = trim((string)($_GET['q'] ?? ''));
      $only = (string)($_GET['only'] ?? 'all');
      $limit = max(20, min(200, (int)($_GET['limit'] ?? 120)));
      $where = " WHERE 1=1 "; $params = [];
      if ($q !== '') {
        $where .= " AND (dislab_adi LIKE :q1 OR dislab_kodu LIKE :q2 OR sut_kodu LIKE :q3) ";
        $params[':q1'] = $params[':q2'] = $params[':q3'] = "%{$q}%";
      }
      if ($only === 'active') $where .= " AND is_active = 1 ";
      if ($only === 'passive') $where .= " AND is_active = 0 ";
      $has_last_sync = has_col($db_obj,'dislab_test_listesi','last_sync');

      $sql = "SELECT id, dislab_id, dislab_kodu, dislab_adi, sut_kodu, ornek_tur_id, ornek_tur_adi, kap_id, kap_adi, is_active" . ($has_last_sync ? ", last_sync" : "") . " FROM dislab_test_listesi {$where} ORDER BY is_active DESC, dislab_adi ASC LIMIT {$limit}";
      $stmt = $db_obj->prepare($sql);
      foreach ($params as $k => $v) $stmt->bindValue($k, $v);
      $stmt->execute();
      $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);

      $total = (int)$db_obj->query("SELECT COUNT(*) FROM dislab_test_listesi")->fetchColumn();
      $active = (int)$db_obj->query("SELECT COUNT(*) FROM dislab_test_listesi WHERE is_active=1")->fetchColumn();

      ob_start();
      foreach ($tests as $t) {
          $id = (int)$t['id']; $isActive = ((int)$t['is_active'] === 1);
          $last = isset($t['last_sync']) ? (string)$t['last_sync'] : ''; ?>
          <tr>
            <td class="text-center ps-3"><input class="form-check-input rowCheck" type="checkbox" value="<?= $id ?>"></td>
            <td><div class="fw-bold"><?= h($t['dislab_adi']) ?></div><div class="small text-muted">ID: <?= h($t['dislab_id']) ?> <?= $last ? "• $last" : "" ?></div></td>
            <td class="text-center fw-semibold"><?= h($t['dislab_kodu']) ?></td>
            <td class="text-center small"><div><?= h($t['ornek_tur_adi']) ?></div><div class="text-muted"><?= h($t['kap_adi']) ?></div></td>
            <td class="text-center fw-bold text-primary"><?= h($t['sut_kodu']) ?></td>
            <td class="text-center"><span class="badge rounded-pill <?= $isActive ? 'text-bg-success' : 'text-bg-secondary' ?>"><?= $isActive ? 'AKTİF' : 'PASİF' ?></span></td>
            <td class="text-end pe-3">
              <button class="btn btn-sm btn-outline-primary btnEdit" data-id="<?= $id ?>" data-dislab_adi="<?= h($t['dislab_adi']) ?>" data-dislab_kodu="<?= h($t['dislab_kodu']) ?>" data-sut_kodu="<?= h($t['sut_kodu']) ?>" data-ornek_tur_id="<?= h($t['ornek_tur_id']) ?>" data-ornek_tur_adi="<?= h($t['ornek_tur_adi']) ?>" data-kap_id="<?= h($t['kap_id']) ?>" data-kap_adi="<?= h($t['kap_adi']) ?>" data-is_active="<?= (int)$t['is_active'] ?>"><i class="bi bi-pencil"></i></button>
              <button class="btn btn-sm btn-outline-danger btnSingleDelete" data-id="<?= $id ?>"><i class="bi bi-trash"></i></button>
            </td>
          </tr>
      <?php } $html_table = ob_get_clean();

      ob_start();
      foreach ($tests as $t) {
          $id = (int)$t['id']; $isActive = ((int)$t['is_active'] === 1); ?>
          <div class="card shadow-sm border rounded-4 mb-3 p-3">
            <div class="d-flex justify-content-between">
                <input class="form-check-input rowCheck" type="checkbox" value="<?= $id ?>">
                <span class="badge <?= $isActive ? 'text-bg-success' : 'text-bg-secondary' ?>"><?= $isActive ? 'AKTİF' : 'PASİF' ?></span>
            </div>
            <div class="fw-bold my-2"><?= h($t['dislab_adi']) ?></div>
            <div class="small text-muted mb-3">Kod: <?= h($t['dislab_kodu']) ?> • SUT: <?= h($t['sut_kodu']) ?></div>
            <div class="d-grid gap-2 d-flex">
                <button class="btn btn-sm btn-primary flex-grow-1 btnEdit" data-id="<?= $id ?>" data-dislab_adi="<?= h($t['dislab_adi']) ?>" data-dislab_kodu="<?= h($t['dislab_kodu']) ?>" data-sut_kodu="<?= h($t['sut_kodu']) ?>" data-ornek_tur_id="<?= h($t['ornek_tur_id']) ?>" data-ornek_tur_adi="<?= h($t['ornek_tur_adi']) ?>" data-kap_id="<?= h($t['kap_id']) ?>" data-kap_adi="<?= h($t['kap_adi']) ?>" data-is_active="<?= (int)$t['is_active'] ?>">Düzenle</button>
                <button class="btn btn-sm btn-outline-danger btnSingleDelete" data-id="<?= $id ?>"><i class="bi bi-trash"></i></button>
            </div>
          </div>
      <?php } $html_cards = ob_get_clean();

      json_out(['success' => true, 'html_table' => $html_table, 'html_cards' => $html_cards, 'summary' => ['total' => $total, 'active' => $active]]);
    }

    if ($action === 'bulk_delete') {
      $ids = array_filter(array_map('intval', $payload['ids'] ?? []), fn($x) => $x > 0);
      if (!$ids) json_out(['success'=>false,'error'=>'Seçim yok']);
      $ph = implode(',', array_fill(0, count($ids), '?'));
      $st = $db_obj->prepare("DELETE FROM dislab_test_listesi WHERE id IN ($ph)");
      $st->execute($ids);
      json_out(['success'=>true]);
    }

    if ($action === 'bulk_set_active') {
      $ids = array_filter(array_map('intval', $payload['ids'] ?? []), fn($x) => $x > 0);
      $state = (int)($payload['state'] ?? 1) ? 1 : 0;
      if (!$ids) json_out(['success'=>false,'error'=>'Seçim yok']);
      $ph = implode(',', array_fill(0, count($ids), '?'));
      $st = $db_obj->prepare("UPDATE dislab_test_listesi SET is_active = ? WHERE id IN ($ph)");
      $st->execute(array_merge([$state], $ids));
      json_out(['success'=>true]);
    }

    if ($action === 'update_one') {
      $st = $db_obj->prepare("UPDATE dislab_test_listesi SET dislab_adi=?, sut_kodu=?, ornek_tur_adi=?, ornek_tur_id=?, kap_adi=?, kap_id=?, is_active=? WHERE id=?");
      $st->execute([$payload['dislab_adi'],$payload['sut_kodu'],$payload['ornek_tur_adi'],$payload['ornek_tur_id'],$payload['kap_adi'],$payload['kap_id'],$payload['is_active'],$payload['id']]);
      json_out(['success'=>true]);
    }

    if ($action === 'resync_selected') {
        $ids = array_filter(array_map('intval', $payload['ids'] ?? []), fn($x) => $x > 0);
        $catalog = dislab_fetch_catalog($db_obj, (array)$conf);
        $st = $db_obj->prepare("SELECT id, dislab_kodu FROM dislab_test_listesi WHERE id IN (".implode(',', array_fill(0, count($ids), '?')).")");
        $st->execute($ids); $rows = $st->fetchAll(PDO::FETCH_ASSOC);
        $updated = 0; $db_obj->beginTransaction();
        $up = $db_obj->prepare("UPDATE dislab_test_listesi SET dislab_id=?, dislab_adi=?, sut_kodu=?, ornek_tur_id=?, ornek_tur_adi=?, kap_id=?, kap_adi=?, last_sync=NOW() WHERE dislab_kodu=?");
        foreach ($rows as $r) {
            $code = $r['dislab_kodu'];
            if (isset($catalog[$code])) {
                $row = $catalog[$code];
                $up->execute([$row['dislab_id'],$row['dislab_adi'],$row['sut_kodu'],$row['ornek_tur_id'],$row['ornek_tur_adi'],$row['kap_id'],$row['kap_adi'],$code]);
                $updated++;
            }
        }
        $db_obj->commit();
        json_out(['success'=>true, 'updated'=>$updated]);
    }
  } catch (Throwable $e) { json_out(['success'=>false,'error'=>$e->getMessage()]); }
}

$self = basename($_SERVER['PHP_SELF']);
$total = (int)$db_obj->query("SELECT COUNT(*) FROM dislab_test_listesi")->fetchColumn();
$active = (int)$db_obj->query("SELECT COUNT(*) FROM dislab_test_listesi WHERE is_active=1")->fetchColumn();
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Dışlab Hizmet Kataloğu</title>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    :root{ --bg:#f6f8fc; --pri:#4361ee; --topbar-h: 72px; }
    body{ font-family:'Plus Jakarta Sans',sans-serif; background:var(--bg); color:#1e293b; }
    .with-topbar .wrap{ padding-top: var(--topbar-h); }
    .wrap{ padding:20px; }
    .hero{ background:#fff; border:1px solid #e2e8f0; border-radius:16px; padding:20px; box-shadow:0 1px 3px rgba(0,0,0,0.05); }
    .cardx{ background:#fff; border:1px solid #e2e8f0; border-radius:16px; box-shadow:0 4px 20px rgba(0,0,0,0.05); overflow:hidden; }
    .search-ctrl{ border:2px solid #e2e8f0; border-radius:12px; padding:12px 12px 12px 45px; width:100%; transition:0.2s; background:#fff; outline:none; }
    .search-ctrl:focus{ border-color:var(--pri); box-shadow:0 0 0 4px rgba(67,97,238,0.1); }
    #overlay{ position:fixed; inset:0; display:none; align-items:center; justify-content:center; background:rgba(255,255,255,0.8); z-index:9999; backdrop-filter:blur(4px); }
    .table thead th{ background:#f8fafc; color:#64748b; font-size:12px; text-transform:uppercase; padding:15px; border-bottom:1px solid #e2e8f0; }
  </style>
</head>
<body class="<?= $topbar_file ? 'with-topbar' : '' ?>">

<?php if ($topbar_file) { $page_title = 'Dışlab Kataloğu'; require_once $topbar_file; } ?>

<div id="overlay">
  <div class="bg-white p-4 rounded-4 shadow-lg text-center border" style="width:300px;">
    <div class="spinner-border text-primary mb-2"></div>
    <div class="fw-bold" id="ovTitle">Yükleniyor</div>
    <div class="small text-muted" id="ovSub">Lütfen bekleyin...</div>
  </div>
</div>

<div class="wrap container-fluid">
  <div class="hero mb-4 d-flex flex-column flex-md-row justify-content-between align-items-center gap-3">
    <div>
        <h2 class="fw-bold mb-1">Hizmet Kataloğu</h2>
        <div class="d-flex gap-2">
            <span class="badge bg-light text-dark border">Toplam: <b id="sumTotal"><?= $total ?></b></span>
            <span class="badge bg-light text-success border">Aktif: <b id="sumActive"><?= $active ?></b></span>
            <span class="badge bg-primary text-white" id="selCountBadge">Seçili: <b id="selCount">0</b></span>
        </div>
    </div>
    <button class="btn btn-primary px-4 py-2 fw-bold rounded-3" id="btnSync"><i class="bi bi-arrow-repeat me-2"></i>WS Senkronizasyon</button>
  </div>

  <div class="cardx">
    <div class="p-3 border-bottom bg-light bg-opacity-25">
      <div class="row g-2 align-items-center">
        <div class="col-md-5 position-relative">
            <i class="bi bi-search position-absolute top-50 translate-middle-y ms-3 text-muted"></i>
            <input type="text" id="searchInput" class="search-ctrl" placeholder="Test adı veya kod ile ara...">
        </div>
        <div class="col-md-7 d-flex gap-2 justify-content-md-end flex-wrap">
            <select id="onlySelect" class="form-select w-auto rounded-3">
                <option value="all">Filtre: Tümü</option>
                <option value="active">Sadece Aktif</option>
                <option value="passive">Sadece Pasif</option>
            </select>
            <button class="btn btn-outline-primary rounded-3" id="btnResyncSelected" disabled>Sync</button>
            <button class="btn btn-outline-success rounded-3" id="btnSetActive" disabled>Aktif Yap</button>
            <button class="btn btn-outline-warning rounded-3" id="btnSetPassive" disabled>Pasif Yap</button>
            <button class="btn btn-outline-danger rounded-3" id="btnDeleteSelected" disabled><i class="bi bi-trash"></i></button>
        </div>
      </div>
    </div>

    <div class="table-responsive d-none d-md-block">
      <table class="table table-hover align-middle mb-0">
        <thead>
          <tr>
            <th class="text-center" width="50"><input class="form-check-input" id="checkAll" type="checkbox"></th>
            <th>Test Tanımı</th><th class="text-center">Kod</th><th class="text-center">Örnek/Kap</th><th class="text-center">SUT</th><th class="text-center">Durum</th><th class="text-end">İşlem</th>
          </tr>
        </thead>
        <tbody id="tableBody"></tbody>
      </table>
    </div>
    <div class="d-md-none p-3" id="cardBody"></div>
  </div>
</div>

<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
    <div class="modal-content rounded-4 border-0 shadow">
      <div class="modal-header">
        <h5 class="fw-bold m-0">Test Düzenle</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-4">
        <input type="hidden" id="e_id">
        <div class="row g-3">
            <div class="col-md-8"><label class="form-label fw-bold small">Test Adı</label><input type="text" id="e_dislab_adi" class="form-control rounded-3"></div>
            <div class="col-md-4"><label class="form-label fw-bold small">Durum</label><select id="e_is_active" class="form-select rounded-3"><option value="1">Aktif</option><option value="0">Pasif</option></select></div>
            <div class="col-md-4"><label class="form-label fw-bold small">SUT Kodu</label><input type="text" id="e_sut_kodu" class="form-control"></div>
            <div class="col-md-4"><label class="form-label fw-bold small">Örnek Tür ID</label><input type="text" id="e_ornek_tur_id" class="form-control"></div>
            <div class="col-md-4"><label class="form-label fw-bold small">Kap ID</label><input type="text" id="e_kap_id" class="form-control"></div>
            <div class="col-md-6"><label class="form-label fw-bold small">Örnek Tür Adı</label><input type="text" id="e_ornek_tur_adi" class="form-control"></div>
            <div class="col-md-6"><label class="form-label fw-bold small">Kap Adı</label><input type="text" id="e_kap_adi" class="form-control"></div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-light" data-bs-dismiss="modal">Vazgeç</button><button class="btn btn-primary px-4" id="btnSaveEdit">Değişiklikleri Kaydet</button></div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  const apiPath = '<?= $self ?>';
  const editModal = new bootstrap.Modal('#editModal');
  let selected = new Set();

  function showOverlay(t, s) { document.getElementById('ovTitle').innerText = t; document.getElementById('ovSub').innerText = s; document.getElementById('overlay').style.display='flex'; }
  function hideOverlay() { document.getElementById('overlay').style.display='none'; }

  function updateToolbar() {
    const n = selected.size; document.getElementById('selCount').innerText = n;
    const en = n > 0;
    ['btnDeleteSelected','btnSetActive','btnSetPassive','btnResyncSelected'].forEach(id => document.getElementById(id).disabled = !en);
  }

  async function loadTable() {
    const q = document.getElementById('searchInput').value;
    const only = document.getElementById('onlySelect').value;
    showOverlay('Liste yükleniyor','Lütfen bekleyin...');
    const res = await fetch(`${apiPath}?action=fetch_list&q=${encodeURIComponent(q)}&only=${only}`);
    const d = await res.json();
    document.getElementById('tableBody').innerHTML = d.html_table;
    document.getElementById('cardBody').innerHTML = d.html_cards;
    document.getElementById('sumTotal').innerText = d.summary.total;
    document.getElementById('sumActive').innerText = d.summary.active;
    
    // Checkboxları geri yükle
    document.querySelectorAll('.rowCheck').forEach(ch => { if(selected.has(parseInt(ch.value))) ch.checked = true; });
    hideOverlay();
  }

  // Tümünü Seç
  document.getElementById('checkAll').addEventListener('change', e => {
    const isChecked = e.target.checked;
    document.querySelectorAll('.rowCheck').forEach(ch => {
        ch.checked = isChecked;
        const id = parseInt(ch.value);
        if(isChecked) selected.add(id); else selected.delete(id);
    });
    updateToolbar();
  });

  // Checkbox Değişimi
  document.addEventListener('change', e => {
    if(e.target.classList.contains('rowCheck') && e.target.id !== 'checkAll') {
        const id = parseInt(e.target.value);
        if(e.target.checked) selected.add(id); else selected.delete(id);
        updateToolbar();
    }
  });

  // Arama Debounce
  document.getElementById('searchInput').addEventListener('input', () => {
    clearTimeout(window.tmr); window.tmr = setTimeout(loadTable, 300);
  });
  document.getElementById('onlySelect').addEventListener('change', loadTable);

  // İşlem Butonları (Düzenle / Sil)
  document.addEventListener('click', async e => {
    const btnEdit = e.target.closest('.btnEdit');
    const btnDel = e.target.closest('.btnSingleDelete');
    
    if (btnEdit) {
        const d = btnEdit.dataset;
        document.getElementById('e_id').value = d.id;
        document.getElementById('e_dislab_adi').value = d.dislab_adi;
        document.getElementById('e_sut_kodu').value = d.sut_kodu;
        document.getElementById('e_ornek_tur_id').value = d.ornek_tur_id;
        document.getElementById('e_ornek_tur_adi').value = d.ornek_tur_adi;
        document.getElementById('e_kap_id').value = d.kap_id;
        document.getElementById('e_kap_adi').value = d.kap_adi;
        document.getElementById('e_is_active').value = d.is_active;
        editModal.show();
    }
    
    if (btnDel) {
        if(!confirm('Bu kaydı silmek istediğinize emin misiniz?')) return;
        const id = btnDel.dataset.id;
        showOverlay('Siliniyor...','');
        await fetch(`${apiPath}?action=bulk_delete`, { method:'POST', body:JSON.stringify({ids:[id]}) });
        loadTable();
    }
  });

  // Modal Kaydet
  document.getElementById('btnSaveEdit').addEventListener('click', async () => {
    const payload = {
        id: document.getElementById('e_id').value,
        dislab_adi: document.getElementById('e_dislab_adi').value,
        sut_kodu: document.getElementById('e_sut_kodu').value,
        ornek_tur_id: document.getElementById('e_ornek_tur_id').value,
        ornek_tur_adi: document.getElementById('e_ornek_tur_adi').value,
        kap_id: document.getElementById('e_kap_id').value,
        kap_adi: document.getElementById('e_kap_adi').value,
        is_active: document.getElementById('e_is_active').value
    };
    showOverlay('Kaydediliyor...','');
    await fetch(`${apiPath}?action=update_one`, { method:'POST', body:JSON.stringify(payload) });
    editModal.hide();
    loadTable();
  });

  // Toplu İşlemler
  document.getElementById('btnSetActive').addEventListener('click', () => bulkAction('bulk_set_active', {state:1}));
  document.getElementById('btnSetPassive').addEventListener('click', () => bulkAction('bulk_set_active', {state:0}));
  document.getElementById('btnDeleteSelected').addEventListener('click', () => { if(confirm('Seçili kayıtlar silinecek?')) bulkAction('bulk_delete'); });
  document.getElementById('btnResyncSelected').addEventListener('click', () => bulkAction('resync_selected'));

  async function bulkAction(act, extra = {}) {
    showOverlay('İşlem yapılıyor...','');
    await fetch(`${apiPath}?action=${act}`, { method:'POST', body:JSON.stringify({ids:Array.from(selected), ...extra}) });
    selected.clear(); updateToolbar(); loadTable();
  }

  document.getElementById('btnSync').addEventListener('click', async () => {
    showOverlay('Senkronizasyon','Web servisten veriler çekiliyor...');
    const res = await fetch(`${apiPath}?action=sync_all`);
    const d = await res.json();
    alert(`İşlem Tamamlandı\nEklenen: ${d.stats.added}\nGüncellenen: ${d.stats.updated}`);
    loadTable();
  });

  window.onload = loadTable;
</script>
</body>
</html>