<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();
if (!ob_get_level()) { ob_start(); }

/* -----------------------------
   0) Paths + Core includes
------------------------------ */
$root = realpath(__DIR__ . '/..');
if (!$root) { http_response_code(500); exit('Root path bulunamadı.'); }

$dbFile     = $root . '/core/db.php';
$cryptoFile = $root . '/core/crypto.php';
$authFile   = $root . '/core/auth.php';

if (is_file($dbFile))     require_once $dbFile;
if (is_file($cryptoFile)) require_once $cryptoFile;
if (is_file($authFile))   require_once $authFile;

/* -----------------------------
   1) AuthZ
------------------------------ */
$role   = $_SESSION['role'] ?? 'staff';
$userId = (int)($_SESSION['user_id'] ?? 0);
if ($role !== 'admin') { http_response_code(403); exit('Yetkisiz erişim.'); }

/* -----------------------------
   2) Lang (TR/EN)
------------------------------ */
$lang = $_GET['lang'] ?? $_POST['lang'] ?? ($_SESSION['lang'] ?? ($_COOKIE['lang'] ?? 'tr'));
$lang = in_array($lang, ['tr','en'], true) ? $lang : 'tr';
$_SESSION['lang'] = $lang;
@setcookie('lang', $lang, time() + (86400 * 365), "/");

function L(string $tr, string $en, string $lang): string { return $lang === 'en' ? $en : $tr; }
function e(?string $s): string { return htmlspecialchars((string)($s ?? ''), ENT_QUOTES, 'UTF-8'); }

/* -----------------------------
   3) DB helpers (PDO + mysqli)
------------------------------ */
function dl_db_is_pdo(): bool    { return isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof PDO; }
function dl_db_is_mysqli(): bool { return isset($GLOBALS['db']) && $GLOBALS['db'] instanceof mysqli; }

function dl_db_fetch_all(string $sql, array $params = []): array {
  if (dl_db_is_pdo()) {
    $st = $GLOBALS['pdo']->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
  }
  if (dl_db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return [];
    if ($params) {
      $types = str_repeat('s', count($params));
      $st->bind_param($types, ...$params);
    }
    $st->execute();
    $res = $st->get_result();
    $rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];
    $st->close();
    return $rows ?: [];
  }
  return [];
}

function dl_db_fetch_one(string $sql, array $params = []): ?array {
  $rows = dl_db_fetch_all($sql, $params);
  return $rows[0] ?? null;
}

function dl_db_exec(string $sql, array $params = []): bool {
  if (dl_db_is_pdo()) {
    $st = $GLOBALS['pdo']->prepare($sql);
    return (bool)$st->execute($params);
  }
  if (dl_db_is_mysqli()) {
    $db = $GLOBALS['db'];
    $st = $db->prepare($sql);
    if (!$st) return false;
    if ($params) {
      $types = str_repeat('s', count($params));
      $st->bind_param($types, ...$params);
    }
    $ok = $st->execute();
    $st->close();
    return (bool)$ok;
  }
  return false;
}

function dl_encrypt(string $plain): string {
  if ($plain === '') return '';
  if (function_exists('crypto_encrypt')) return (string)crypto_encrypt($plain);
  if (function_exists('encrypt'))         return (string)encrypt($plain);
  return $plain;
}

/* -----------------------------
   4) CSRF
------------------------------ */
if (empty($_SESSION['csrf_dislab'])) {
  $_SESSION['csrf_dislab'] = bin2hex(random_bytes(16));
}
$CSRF = (string)$_SESSION['csrf_dislab'];

function dl_bool_post(string $name): int { return isset($_POST[$name]) ? 1 : 0; }

function dl_page_url(array $extra = [], array $remove = []): string {
  $params = [];
  if (isset($_GET['sayfa'])) $params['sayfa'] = (string)$_GET['sayfa'];

  // Varsayılanlar
  $params['lang'] = $GLOBALS['lang'] ?? 'tr';

  // Mevcut query'den q/edit gibi şeyleri taşımak istersen
  if (isset($GLOBALS['q']) && $GLOBALS['q'] !== '') $params['q'] = (string)$GLOBALS['q'];

  // remove
  foreach ($remove as $rk) { unset($params[$rk]); }

  // override/add
  foreach ($extra as $k => $v) {
    if ($v === null || $v === '') unset($params[$k]);
    else $params[$k] = (string)$v;
  }

  $qs = http_build_query($params);
  return $qs ? ('?' . $qs) : (basename((string)($_SERVER['PHP_SELF'] ?? '')));
}

function dl_redirect(string $url): void {
  if (!headers_sent()) { header("Location: $url"); exit; }
  echo "<script>location.href=".json_encode($url).";</script>";
  exit;
}

/* -----------------------------
   5) Query params
------------------------------ */
$q = trim((string)($_GET['q'] ?? ''));
$editId = (int)($_GET['edit'] ?? 0);

/* -----------------------------
   6) Handle actions
------------------------------ */
$flash_ok = '';
$flash_err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $postedCsrf = (string)($_POST['csrf'] ?? '');
  if (!hash_equals($CSRF, $postedCsrf)) {
    $flash_err = L('Güvenlik doğrulaması başarısız (CSRF).', 'Security verification failed (CSRF).', $lang);
  } else {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'delete') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id > 0) {
        $ok = dl_db_exec("DELETE FROM dislab_tanimlari WHERE id = ?", [(string)$id]);
        if ($ok) {
          $_SESSION['flash_ok'] = L('Kayıt silindi.', 'Record deleted.', $lang);
          dl_redirect(dl_page_url([], ['edit']));
        } else {
          $flash_err = L('Silme işlemi başarısız.', 'Delete failed.', $lang);
        }
      }
    }

    if ($action === 'toggle_active') {
      $id = (int)($_POST['id'] ?? 0);
      if ($id > 0) {
        $row = dl_db_fetch_one("SELECT id, is_active FROM dislab_tanimlari WHERE id = ?", [(string)$id]);
        if ($row) {
          $next = ((int)$row['is_active'] === 1) ? 0 : 1;
          $ok = dl_db_exec("UPDATE dislab_tanimlari SET is_active=?, updated_by=? WHERE id=?", [(string)$next, (string)$userId, (string)$id]);
          if ($ok) {
            $_SESSION['flash_ok'] = $next ? L('Tanım aktif edildi.', 'Definition activated.', $lang)
                                          : L('Tanım pasif edildi.', 'Definition deactivated.', $lang);
            dl_redirect(dl_page_url([], ['edit']));
          } else {
            $flash_err = L('Durum güncellenemedi.', 'Status could not be updated.', $lang);
          }
        }
      }
    }

    if ($action === 'save') {
      $id = (int)($_POST['id'] ?? 0);

      $name = trim((string)($_POST['name'] ?? ''));
      $ws_url = trim((string)($_POST['ws_url'] ?? ''));
      $pass_plain = (string)($_POST['pass_plain'] ?? '');

      if ($name === '' || $ws_url === '') {
        $flash_err = L('Ad ve Web Servis URL zorunlu.', 'Name and Web Service URL are required.', $lang);
      } else {
        $params = [
          (string)dl_bool_post('is_active'),
          $name,
          $ws_url,
          (trim((string)($_POST['kurum_kodu'] ?? '')) !== '' ? trim((string)$_POST['kurum_kodu']) : null),
          (trim((string)($_POST['username'] ?? '')) !== '' ? trim((string)$_POST['username']) : null),
          (string)($_POST['pass_type'] ?? 'password'),
          (string)dl_bool_post('opt_auto_send_on_service_add'),
          (string)dl_bool_post('opt_auto_send_on_barcode_accept'),
          (string)dl_bool_post('opt_dont_fetch_pdf'),
          (string)dl_bool_post('opt_fetch_results_no_approve'),
          (string)dl_bool_post('opt_auto_irsaliye'),
          (string)dl_bool_post('opt_dont_auto_query_results'),
          (string)$userId
        ];

        if ($id > 0) {
          $sql = "UPDATE dislab_tanimlari SET
                    is_active=?,
                    name=?,
                    ws_url=?,
                    kurum_kodu=?,
                    username=?,
                    pass_type=?,
                    opt_auto_send_on_service_add=?,
                    opt_auto_send_on_barcode_accept=?,
                    opt_dont_fetch_pdf=?,
                    opt_fetch_results_no_approve=?,
                    opt_auto_irsaliye=?,
                    opt_dont_auto_query_results=?,
                    updated_by=?
                  WHERE id=?";
          $params[] = (string)$id;

          $ok = dl_db_exec($sql, $params);
          if ($ok && $pass_plain !== '') {
            dl_db_exec("UPDATE dislab_tanimlari SET pass_enc=? WHERE id=?", [dl_encrypt($pass_plain), (string)$id]);
          }
          if ($ok) {
            $_SESSION['flash_ok'] = L('Kayıt güncellendi.', 'Record updated.', $lang);
            dl_redirect(dl_page_url([], ['edit']));
          }
          $flash_err = L('Güncelleme işlemi başarısız.', 'Update failed.', $lang);
        } else {
          $sql = "INSERT INTO dislab_tanimlari (
                    is_active, name, ws_url, kurum_kodu, username, pass_type,
                    opt_auto_send_on_service_add, opt_auto_send_on_barcode_accept, opt_dont_fetch_pdf,
                    opt_fetch_results_no_approve, opt_auto_irsaliye, opt_dont_auto_query_results,
                    updated_by, pass_enc
                  ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
          $params[] = dl_encrypt($pass_plain);

          $ok = dl_db_exec($sql, $params);
          if ($ok) {
            $_SESSION['flash_ok'] = L('Kayıt eklendi.', 'Record created.', $lang);
            dl_redirect(dl_page_url([], ['edit']));
          }
          $flash_err = L('Kayıt ekleme başarısız.', 'Create failed.', $lang);
        }
      }
    }
  }
}

if (!empty($_SESSION['flash_ok'])) {
  $flash_ok = (string)$_SESSION['flash_ok'];
  unset($_SESSION['flash_ok']);
}

/* -----------------------------
   7) Data load
------------------------------ */
$editRow = $editId > 0 ? dl_db_fetch_one("SELECT * FROM dislab_tanimlari WHERE id = ?", [(string)$editId]) : null;

$where = "WHERE 1=1";
$params = [];
if ($q !== '') {
  $where .= " AND (name LIKE ? OR ws_url LIKE ? OR username LIKE ? OR kurum_kodu LIKE ?)";
  $like = "%{$q}%";
  $params = [$like, $like, $like, $like];
}

$rows = dl_db_fetch_all("SELECT * FROM dislab_tanimlari {$where} ORDER BY id DESC", $params);

$statTotal  = (int)(dl_db_fetch_one("SELECT COUNT(*) AS c FROM dislab_tanimlari", [])['c'] ?? 0);
$statActive = (int)(dl_db_fetch_one("SELECT COUNT(*) AS c FROM dislab_tanimlari WHERE is_active=1", [])['c'] ?? 0);
$statPassive = max(0, $statTotal - $statActive);

/* -----------------------------
   8) Topbar include (smart)
------------------------------ */
$current_page = (string)($_GET['sayfa'] ?? ''); // topbar bazı sistemlerde bunu ister
$topbarPath = null;

$candidates = [
  __DIR__ . '/topbar.php',
  $root . '/topbar.php',
  $root . '/partials/topbar.php',
  $root . '/includes/topbar.php',
  $root . '/layout/topbar.php',
  $root . '/components/topbar.php',
];

foreach ($candidates as $p) {
  if (is_file($p)) { $topbarPath = $p; break; }
}

/* -----------------------------
   9) Texts
------------------------------ */
$T = [
  'title' => L('Dışlab Tanımları', 'External Lab Definitions', $lang),
  'subtitle' => L('Laboratuvar entegrasyonlarını ve otomasyon seçeneklerini yönetin.', 'Manage lab integrations and automation options.', $lang),
  'new' => L('Yeni Tanım', 'New Definition', $lang),
  'search_ph' => L('Ara: tanım adı, URL, kullanıcı adı, kurum kodu…', 'Search: name, URL, username, institution code…', $lang),
  'active' => L('Aktif', 'Active', $lang),
  'passive' => L('Pasif', 'Inactive', $lang),
  'save' => L('Kaydet', 'Save', $lang),
  'cancel' => L('Vazgeç', 'Cancel', $lang),
  'edit' => L('Düzenle', 'Edit', $lang),
  'delete' => L('Sil', 'Delete', $lang),
  'confirm_del' => L('Silinsin mi?', 'Delete this record?', $lang),
  'toggle' => L('Durum Değiştir', 'Toggle Status', $lang),
];
?>
<!doctype html>
<html lang="<?= e($lang) ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= e($T['title']) ?></title>

  <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: #f4f7fb;
      --surface: #ffffff;
      --text: #0f172a;
      --muted: #64748b;
      --line: #e6ebf2;

      --pri: #2563eb;
      --pri2:#1d4ed8;

      --okbg:#ecfdf5; --ok:#059669;
      --nobg:#fef2f2; --no:#dc2626;

      --r12: 12px;
      --r16: 16px;
      --r20: 20px;
      --shadow: 0 10px 26px rgba(15,23,42,.06);
      --shadow2: 0 20px 70px rgba(15,23,42,.14);
    }

    *{ box-sizing:border-box; }
    body{
      margin:0;
      background: var(--bg);
      color: var(--text);
      font-family: "Segoe UI", system-ui, -apple-system, Roboto, Arial, sans-serif;
    }

    /* TOPBAR wrap: topbar.php içeriğini bozmadan oturtur */
    .app-topbar{
      position: sticky;
      top: 0;
      z-index: 1030;
      background: var(--surface);
      border-bottom: 1px solid var(--line);
    }
    .app-topbar .container-fluid{
      max-width: none !important; /* uçtan uca */
    }

    /* page layout */
    .page{
      padding: 18px 18px 22px 18px;
    }
    @media (max-width: 768px){
      .page{ padding: 14px; }
    }

    /* hero */
    .hero{
      background:
        radial-gradient(900px 260px at 20% 0%, rgba(37,99,235,.16), transparent 55%),
        radial-gradient(900px 260px at 90% 10%, rgba(2,132,199,.14), transparent 60%),
        linear-gradient(180deg, rgba(255,255,255,.92), rgba(255,255,255,.86));
      border: 1px solid rgba(37,99,235,.14);
      border-radius: var(--r20);
      box-shadow: var(--shadow);
      padding: 16px;
    }
    .hero h1{
      font-size: 22px;
      margin:0;
      font-weight: 800;
      letter-spacing: -0.02em;
    }
    .hero p{
      margin:6px 0 0 0;
      color: var(--muted);
      font-weight: 600;
      font-size: 13px;
    }

    .btn-pri{
      background: var(--pri);
      border-color: var(--pri);
      border-radius: 12px;
      font-weight: 800;
      padding: 10px 14px;
    }
    .btn-pri:hover{ background: var(--pri2); border-color: var(--pri2); }

    .cardx{
      background: var(--surface);
      border: 1px solid var(--line);
      border-radius: var(--r20);
      box-shadow: var(--shadow);
      overflow: hidden;
    }

    .stat{
      display:flex;
      gap:10px;
      flex-wrap:wrap;
      margin-top: 12px;
    }
    .pill{
      display:inline-flex;
      align-items:center;
      gap:8px;
      border: 1px solid var(--line);
      background:#fff;
      border-radius: 999px;
      padding: 8px 12px;
      color: var(--muted);
      font-weight: 700;
      font-size: 13px;
    }
    .pill b{ color: var(--text); }

    .search{
      width:100%;
      border:2px solid #dbe3ef;
      border-radius: 14px;
      padding: 12px 44px 12px 44px;
      outline: none;
      font-weight: 700;
      transition: .15s;
      background:#fff;
    }
    .search:focus{ border-color: var(--pri); box-shadow: 0 0 0 .2rem rgba(37,99,235,.12); }

    .table thead th{
      background:#f8fafc;
      color:#64748b;
      font-size:12px;
      letter-spacing:.04em;
      text-transform:uppercase;
      border-bottom: 1px solid var(--line);
      padding: 14px;
      white-space: nowrap;
    }
    .table tbody td{
      border-bottom: 1px solid #eef2f7;
      padding: 14px;
      vertical-align: middle;
    }

    .badge-status{
      font-weight: 900;
      font-size: 12px;
      padding: 8px 12px;
      border-radius: 999px;
      border: 1px solid transparent;
      white-space: nowrap;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }
    .badge-active{ background: var(--okbg); color: var(--ok); border-color: rgba(5,150,105,.18); }
    .badge-passive{ background: var(--nobg); color: var(--no); border-color: rgba(220,38,38,.18); }

    .mono{ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; }
    .muted{ color: var(--muted); }

    .btn-ico{
      border-radius: 12px;
      font-weight: 900;
      padding: 9px 11px;
      border: 1px solid var(--line);
      background: #fff;
    }
    .btn-ico:hover{ background:#f8fafc; }

    /* Mobile cards */
    .m-card{
      border: 1px solid var(--line);
      background:#fff;
      border-radius: var(--r16);
      box-shadow: 0 6px 18px rgba(15,23,42,.05);
      padding: 14px;
    }
    .m-title{ font-weight: 900; font-size: 15px; line-height:1.25; }
    .m-sub{ color: var(--muted); font-size: 12px; font-weight: 700; word-break: break-word; }
    .m-actions{ display:grid; grid-template-columns: 1fr 1fr 1fr; gap:10px; }
    .m-actions .btn{ border-radius: 12px; font-weight: 900; }

    .modal-content{
      border: 0;
      border-radius: 18px;
      box-shadow: var(--shadow2);
    }
    .form-control, .form-select{
      border-radius: 14px;
      padding: 12px;
      border: 1px solid #e2e8f0;
      font-weight: 700;
    }
    .form-control:focus, .form-select:focus{
      border-color: var(--pri);
      box-shadow: 0 0 0 4px rgba(37,99,235,.12);
    }
    .help{
      font-size: 12px;
      color: var(--muted);
      font-weight: 600;
      margin-top: 6px;
    }

    /* overlay */
    #overlay{
      position: fixed; inset: 0;
      background: rgba(255,255,255,.84);
      backdrop-filter: blur(3px);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }
    .ov{
      width: min(520px, 92vw);
      background: #fff;
      border: 1px solid var(--line);
      border-radius: 18px;
      box-shadow: 0 18px 60px rgba(15,23,42,.18);
      padding: 16px;
    }
    .ov .t{ font-weight: 900; font-size: 16px; }
    .ov .s{ color: var(--muted); font-weight: 700; font-size: 13px; margin-top: 4px; }
  </style>
</head>

<body>
  <!-- TOPBAR -->
  <div class="app-topbar">
    <?php if ($topbarPath): ?>
      <?php
        // topbar.php bazen kendi içinde değişken bekler: $lang, $current_page vs.
        // burada zaten set ettik.
        include $topbarPath;
      ?>
    <?php else: ?>
      <!-- Fallback Topbar (topbar.php yoksa) -->
      <div class="container-fluid py-3 px-3 px-lg-4">
        <div class="d-flex align-items-center justify-content-between">
          <div class="d-flex align-items-center gap-2">
            <i class="bi bi-hospital fs-4 text-primary"></i>
            <div class="fw-bold">NEPHRO ERP</div>
            <span class="text-muted small fw-semibold">/ <?= e($T['title']) ?></span>
          </div>
          <div class="d-flex gap-2">
            <a class="btn btn-outline-secondary btn-sm" href="<?= e(dl_page_url(['lang'=>'tr'], ['edit'])) ?>">TR</a>
            <a class="btn btn-outline-secondary btn-sm" href="<?= e(dl_page_url(['lang'=>'en'], ['edit'])) ?>">EN</a>
          </div>
        </div>
      </div>
    <?php endif; ?>
  </div>

  <!-- Overlay -->
  <div id="overlay">
    <div class="ov">
      <div class="d-flex align-items-center gap-3">
        <div class="spinner-border" role="status" aria-hidden="true"></div>
        <div>
          <div class="t" id="ovT"><?= e(L('İşleniyor…','Processing…',$lang)) ?></div>
          <div class="s" id="ovS"><?= e(L('Lütfen bekleyin.','Please wait.',$lang)) ?></div>
        </div>
      </div>
      <div class="progress mt-3" style="height:10px;">
        <div class="progress-bar progress-bar-striped progress-bar-animated" style="width:100%"></div>
      </div>
    </div>
  </div>

  <!-- PAGE (FULL WIDTH) -->
  <div class="container-fluid page px-3 px-lg-4">
    <div class="hero">
      <div class="d-flex flex-wrap align-items-start justify-content-between gap-3">
        <div>
          <h1><?= e($T['title']) ?></h1>
          <p><?= e($T['subtitle']) ?></p>

          <div class="stat">
            <span class="pill"><i class="bi bi-database-check"></i> <?= e(L('Toplam','Total',$lang)) ?>: <b><?= (int)$statTotal ?></b></span>
            <span class="pill"><i class="bi bi-check-circle"></i> <?= e(L('Aktif','Active',$lang)) ?>: <b><?= (int)$statActive ?></b></span>
            <span class="pill"><i class="bi bi-slash-circle"></i> <?= e(L('Pasif','Inactive',$lang)) ?>: <b><?= (int)$statPassive ?></b></span>
          </div>
        </div>

        <div class="d-flex gap-2 flex-wrap">
          <a class="btn btn-outline-secondary" style="border-radius:12px;font-weight:900;"
             href="<?= e(dl_page_url([], ['edit'])) ?>">
            <i class="bi bi-arrow-clockwise me-1"></i><?= e(L('Yenile','Refresh',$lang)) ?>
          </a>

          <button class="btn btn-pri text-white"
                  data-bs-toggle="modal" data-bs-target="#defModal"
                  id="btnNew">
            <i class="bi bi-plus-lg me-1"></i><?= e($T['new']) ?>
          </button>
        </div>
      </div>
    </div>

    <div class="mt-3">
      <?php if ($flash_ok): ?>
        <div class="alert alert-success border-0 shadow-sm" style="border-radius:16px;">
          <i class="bi bi-check-circle-fill me-2"></i><?= e($flash_ok) ?>
        </div>
      <?php endif; ?>
      <?php if ($flash_err): ?>
        <div class="alert alert-danger border-0 shadow-sm" style="border-radius:16px;">
          <i class="bi bi-exclamation-triangle-fill me-2"></i><?= e($flash_err) ?>
        </div>
      <?php endif; ?>
    </div>

    <div class="cardx mt-3">
      <div class="p-3 border-bottom" style="background:#fbfcff;">
        <form method="get" class="row g-2 align-items-center">
          <?php if (isset($_GET['sayfa'])): ?>
            <input type="hidden" name="sayfa" value="<?= e((string)$_GET['sayfa']) ?>">
          <?php endif; ?>
          <input type="hidden" name="lang" value="<?= e($lang) ?>">

          <div class="col-12 col-lg-8">
            <div class="position-relative">
              <i class="bi bi-search position-absolute top-50 translate-middle-y ms-3 muted fs-5"></i>
              <input class="search" name="q" value="<?= e($q) ?>" placeholder="<?= e($T['search_ph']) ?>">
            </div>
          </div>

          <div class="col-12 col-lg-4 d-flex gap-2 justify-content-lg-end flex-wrap">
            <button class="btn btn-outline-primary" style="border-radius:12px;font-weight:900;" type="submit">
              <i class="bi bi-funnel me-1"></i><?= e(L('Filtrele','Filter',$lang)) ?>
            </button>

            <?php if ($q !== ''): ?>
              <a class="btn btn-outline-secondary" style="border-radius:12px;font-weight:900;"
                 href="<?= e(dl_page_url(['q'=>null], ['edit'])) ?>">
                <i class="bi bi-x-circle me-1"></i><?= e(L('Temizle','Clear',$lang)) ?>
              </a>
            <?php endif; ?>
          </div>
        </form>
      </div>

      <!-- Desktop table -->
      <div class="table-responsive d-none d-md-block">
        <table class="table mb-0 align-middle">
          <thead>
            <tr>
              <th style="width:140px;"><?= e(L('Durum','Status',$lang)) ?></th>
              <th><?= e(L('Tanım','Definition',$lang)) ?></th>
              <th style="width:170px;"><?= e(L('Bağlantı','Connection',$lang)) ?></th>
              <th style="width:220px;" class="text-end"><?= e(L('İşlemler','Actions',$lang)) ?></th>
            </tr>
          </thead>
          <tbody>
            <?php if (!$rows): ?>
              <tr>
                <td colspan="4" class="text-center py-5 muted">
                  <i class="bi bi-inboxes fs-3 d-block mb-2"></i>
                  <?= e(L('Kayıt bulunamadı.','No records found.',$lang)) ?>
                </td>
              </tr>
            <?php endif; ?>

            <?php foreach ($rows as $r): ?>
              <?php $isActive = ((int)$r['is_active'] === 1); ?>
              <tr>
                <td>
                  <span class="badge-status <?= $isActive ? 'badge-active' : 'badge-passive' ?>">
                    <i class="bi <?= $isActive ? 'bi-check-circle' : 'bi-slash-circle' ?>"></i>
                    <?= $isActive ? e($T['active']) : e($T['passive']) ?>
                  </span>
                </td>

                <td>
                  <div class="fw-bold"><?= e((string)$r['name']) ?></div>
                  <div class="m-0 muted small">
                    <i class="bi bi-link-45deg me-1"></i><span class="mono"><?= e((string)$r['ws_url']) ?></span>
                  </div>
                  <div class="mt-1 small muted">
                    <?php if (!empty($r['kurum_kodu'])): ?>
                      <span class="me-3"><i class="bi bi-building me-1"></i><?= e((string)$r['kurum_kodu']) ?></span>
                    <?php endif; ?>
                    <?php if (!empty($r['username'])): ?>
                      <span><i class="bi bi-person me-1"></i><?= e((string)$r['username']) ?></span>
                    <?php endif; ?>
                  </div>
                </td>

                <td>
                  <span class="badge bg-light text-dark border rounded-pill px-3 py-2 fw-bold">
                    <i class="bi bi-shield-lock me-1"></i><?= e((string)$r['pass_type']) ?>
                  </span>
                </td>

                <td class="text-end">
                  <div class="d-inline-flex gap-2">
                    <form method="post" class="d-inline">
                      <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
                      <input type="hidden" name="action" value="toggle_active">
                      <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                      <input type="hidden" name="lang" value="<?= e($lang) ?>">
                      <button type="submit" class="btn-ico" title="<?= e($T['toggle']) ?>">
                        <i class="bi bi-arrow-repeat"></i>
                      </button>
                    </form>

                    <button
                      type="button"
                      class="btn-ico btnEdit"
                      title="<?= e($T['edit']) ?>"
                      data-bs-toggle="modal" data-bs-target="#defModal"
                      data-id="<?= (int)$r['id'] ?>"
                      data-is_active="<?= (int)$r['is_active'] ?>"
                      data-name="<?= e((string)$r['name']) ?>"
                      data-ws_url="<?= e((string)$r['ws_url']) ?>"
                      data-kurum_kodu="<?= e((string)$r['kurum_kodu']) ?>"
                      data-username="<?= e((string)$r['username']) ?>"
                      data-pass_type="<?= e((string)$r['pass_type']) ?>"
                      data-opt_auto_send_on_service_add="<?= (int)($r['opt_auto_send_on_service_add'] ?? 0) ?>"
                      data-opt_auto_send_on_barcode_accept="<?= (int)($r['opt_auto_send_on_barcode_accept'] ?? 0) ?>"
                      data-opt_dont_fetch_pdf="<?= (int)($r['opt_dont_fetch_pdf'] ?? 0) ?>"
                      data-opt_fetch_results_no_approve="<?= (int)($r['opt_fetch_results_no_approve'] ?? 0) ?>"
                      data-opt_auto_irsaliye="<?= (int)($r['opt_auto_irsaliye'] ?? 0) ?>"
                      data-opt_dont_auto_query_results="<?= (int)($r['opt_dont_auto_query_results'] ?? 0) ?>"
                    >
                      <i class="bi bi-pencil-square"></i>
                    </button>

                    <form method="post" class="d-inline" onsubmit="return confirm(<?= json_encode($T['confirm_del']) ?>);">
                      <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
                      <input type="hidden" name="action" value="delete">
                      <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                      <input type="hidden" name="lang" value="<?= e($lang) ?>">
                      <button type="submit" class="btn-ico text-danger" title="<?= e($T['delete']) ?>">
                        <i class="bi bi-trash3"></i>
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <!-- Mobile cards -->
      <div class="d-md-none p-3">
        <?php if (!$rows): ?>
          <div class="text-center py-5 muted">
            <i class="bi bi-inboxes fs-3 d-block mb-2"></i>
            <?= e(L('Kayıt bulunamadı.','No records found.',$lang)) ?>
          </div>
        <?php endif; ?>

        <div class="d-grid gap-3">
          <?php foreach ($rows as $r): ?>
            <?php $isActive = ((int)$r['is_active'] === 1); ?>
            <div class="m-card">
              <div class="d-flex justify-content-between align-items-start gap-3">
                <div>
                  <div class="m-title"><?= e((string)$r['name']) ?></div>
                  <div class="m-sub mt-1"><i class="bi bi-link-45deg me-1"></i><?= e((string)$r['ws_url']) ?></div>
                  <div class="m-sub mt-1">
                    <i class="bi bi-shield-lock me-1"></i><?= e((string)$r['pass_type']) ?>
                    <?php if (!empty($r['username'])): ?>
                      <span class="ms-2"><i class="bi bi-person me-1"></i><?= e((string)$r['username']) ?></span>
                    <?php endif; ?>
                  </div>
                </div>

                <span class="badge-status <?= $isActive ? 'badge-active' : 'badge-passive' ?>">
                  <i class="bi <?= $isActive ? 'bi-check-circle' : 'bi-slash-circle' ?>"></i>
                  <?= $isActive ? e($T['active']) : e($T['passive']) ?>
                </span>
              </div>

              <div class="m-actions mt-3">
                <form method="post">
                  <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
                  <input type="hidden" name="action" value="toggle_active">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="lang" value="<?= e($lang) ?>">
                  <button type="submit" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-repeat me-1"></i><?= e(L('Durum','Status',$lang)) ?>
                  </button>
                </form>

                <button
                  type="button"
                  class="btn btn-outline-primary btnEdit"
                  data-bs-toggle="modal" data-bs-target="#defModal"
                  data-id="<?= (int)$r['id'] ?>"
                  data-is_active="<?= (int)$r['is_active'] ?>"
                  data-name="<?= e((string)$r['name']) ?>"
                  data-ws_url="<?= e((string)$r['ws_url']) ?>"
                  data-kurum_kodu="<?= e((string)$r['kurum_kodu']) ?>"
                  data-username="<?= e((string)$r['username']) ?>"
                  data-pass_type="<?= e((string)$r['pass_type']) ?>"
                  data-opt_auto_send_on_service_add="<?= (int)($r['opt_auto_send_on_service_add'] ?? 0) ?>"
                  data-opt_auto_send_on_barcode_accept="<?= (int)($r['opt_auto_send_on_barcode_accept'] ?? 0) ?>"
                  data-opt_dont_fetch_pdf="<?= (int)($r['opt_dont_fetch_pdf'] ?? 0) ?>"
                  data-opt_fetch_results_no_approve="<?= (int)($r['opt_fetch_results_no_approve'] ?? 0) ?>"
                  data-opt_auto_irsaliye="<?= (int)($r['opt_auto_irsaliye'] ?? 0) ?>"
                  data-opt_dont_auto_query_results="<?= (int)($r['opt_dont_auto_query_results'] ?? 0) ?>"
                >
                  <i class="bi bi-pencil-square me-1"></i><?= e($T['edit']) ?>
                </button>

                <form method="post" onsubmit="return confirm(<?= json_encode($T['confirm_del']) ?>);">
                  <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
                  <input type="hidden" name="action" value="delete">
                  <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                  <input type="hidden" name="lang" value="<?= e($lang) ?>">
                  <button type="submit" class="btn btn-outline-danger">
                    <i class="bi bi-trash3 me-1"></i><?= e($T['delete']) ?>
                  </button>
                </form>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      </div>

    </div><!-- cardx -->
  </div><!-- container-fluid -->

  <!-- Modal: Create/Edit -->
  <div class="modal fade" id="defModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
        <form method="post" id="defForm" autocomplete="off">
          <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
          <input type="hidden" name="action" value="save">
          <input type="hidden" name="lang" value="<?= e($lang) ?>">
          <input type="hidden" name="id" id="f_id" value="<?= (int)($editRow['id'] ?? 0) ?>">

          <div class="modal-header border-0 p-4 pb-2">
            <div>
              <div class="fw-bold" style="font-size:16px;">
                <i class="bi bi-sliders2-vertical me-2 text-primary"></i>
                <span id="modalTitle"><?= $editRow ? e(L('Tanımı Düzenle','Edit Definition',$lang)) : e(L('Yeni Tanım Ekle','Add New Definition',$lang)) ?></span>
              </div>
              <div class="help mb-0"><?= e(L('Dışlab bağlantı bilgilerini ve otomasyon ayarlarını yönetin.', 'Manage external lab connection and automation settings.', $lang)) ?></div>
            </div>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>

          <div class="modal-body p-4 pt-2">
            <div class="row g-3">
              <div class="col-md-8">
                <label class="form-label small fw-bold text-muted"><?= e(L('Tanım Adı','Definition Name',$lang)) ?> *</label>
                <input type="text" name="name" id="f_name" class="form-control" required value="<?= e((string)($editRow['name'] ?? '')) ?>">
              </div>

              <div class="col-md-4">
                <label class="form-label small fw-bold text-muted"><?= e(L('Durum','Status',$lang)) ?></label>
                <div class="d-flex align-items-center gap-2 mt-2">
                  <div class="form-check form-switch m-0">
                    <input class="form-check-input" type="checkbox" name="is_active" id="f_is_active"
                           style="width:46px;height:24px;"
                           <?= ($editRow ? (((int)$editRow['is_active']===1)?'checked':'') : 'checked') ?>>
                  </div>
                  <span class="fw-bold" id="activeLabel"><?= e(L('Aktif','Active',$lang)) ?></span>
                </div>
              </div>

              <div class="col-12">
                <label class="form-label small fw-bold text-muted"><?= e(L('Web Servis URL','Web Service URL',$lang)) ?> *</label>
                <input type="url" name="ws_url" id="f_ws_url" class="form-control" required value="<?= e((string)($editRow['ws_url'] ?? '')) ?>">
              </div>

              <div class="col-md-6">
                <label class="form-label small fw-bold text-muted"><?= e(L('Kullanıcı Adı','Username',$lang)) ?></label>
                <input type="text" name="username" id="f_username" class="form-control" value="<?= e((string)($editRow['username'] ?? '')) ?>">
              </div>

              <div class="col-md-6">
                <label class="form-label small fw-bold text-muted"><?= e(L('Kurum Kodu','Institution Code',$lang)) ?></label>
                <input type="text" name="kurum_kodu" id="f_kurum_kodu" class="form-control" value="<?= e((string)($editRow['kurum_kodu'] ?? '')) ?>">
              </div>

              <div class="col-md-4">
                <label class="form-label small fw-bold text-muted"><?= e(L('Şifre Türü','Pass Type',$lang)) ?></label>
                <?php $pt = (string)($editRow['pass_type'] ?? 'password'); ?>
                <select class="form-select" name="pass_type" id="f_pass_type">
                  <option value="password" <?= $pt==='password'?'selected':'' ?>>Password</option>
                  <option value="token"    <?= $pt==='token'?'selected':'' ?>>Token</option>
                  <option value="apikey"   <?= $pt==='apikey'?'selected':'' ?>>API Key</option>
                </select>
              </div>

              <div class="col-md-8">
                <label class="form-label small fw-bold text-muted"><?= e(L('Şifre / Key','Password / Key',$lang)) ?></label>
                <input type="password" name="pass_plain" id="f_pass_plain" class="form-control"
                       placeholder="<?= e($editRow ? L('Değiştirmek için yazın','Type to change',$lang) : L('Gerekliyse girin','Enter if required',$lang)) ?>">
                <div class="help"><?= e(L('Boş bırakırsanız mevcut şifre korunur.', 'Leave blank to keep existing password.', $lang)) ?></div>
              </div>

              <div class="col-12 mt-2">
                <div class="card border-0" style="background:#f8fafc;border-radius:16px;">
                  <div class="card-body p-3">
                    <div class="fw-bold mb-2">
                      <i class="bi bi-gear me-2 text-primary"></i><?= e(L('Otomasyon Seçenekleri','Automation Options',$lang)) ?>
                    </div>

                    <div class="row g-2">
                      <?php
                        $opts = [
                          'opt_auto_send_on_service_add'     => L('Hizmet eklendiğinde otomatik gönder','Auto-send on service add',$lang),
                          'opt_auto_send_on_barcode_accept'  => L('Barkod kabulde otomatik gönder','Auto-send on barcode accept',$lang),
                          'opt_dont_fetch_pdf'               => L('PDF çekme','Do not fetch PDF',$lang),
                          'opt_fetch_results_no_approve'     => L('Onaylamadan sonuç al','Fetch without approve',$lang),
                          'opt_auto_irsaliye'                => L('Otomatik irsaliye','Auto dispatch note',$lang),
                          'opt_dont_auto_query_results'      => L('Otomatik sorgulama yapma','No auto query',$lang),
                        ];
                        foreach ($opts as $key => $label):
                          $checked = ($editRow && (int)($editRow[$key] ?? 0) === 1) ? 'checked' : '';
                      ?>
                        <div class="col-md-6">
                          <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="<?= e($key) ?>" id="<?= e($key) ?>" <?= $checked ?>>
                            <label class="form-check-label small fw-bold" for="<?= e($key) ?>"><?= e($label) ?></label>
                          </div>
                        </div>
                      <?php endforeach; ?>
                    </div>

                    <div class="help mt-2">
                      <?= e(L('Bu seçenekler entegrasyon akışını etkiler. Değişiklikten sonra test edin.',
                              'These options affect the integration flow. Test after changing.',
                              $lang)) ?>
                    </div>
                  </div>
                </div>
              </div>

            </div><!-- row -->
          </div><!-- modal-body -->

          <div class="modal-footer border-0 p-4 pt-0">
            <button type="button" class="btn btn-outline-secondary" style="border-radius:12px;font-weight:900;" data-bs-dismiss="modal">
              <?= e($T['cancel']) ?>
            </button>
            <button type="submit" class="btn btn-pri text-white">
              <i class="bi bi-check2 me-1"></i><?= e($T['save']) ?>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    const overlay = document.getElementById('overlay');
    const ovT = document.getElementById('ovT');
    const ovS = document.getElementById('ovS');

    function showOverlay(t, s){
      if (t) ovT.textContent = t;
      if (s) ovS.textContent = s;
      overlay.style.display = 'flex';
    }
    function hideOverlay(){ overlay.style.display = 'none'; }

    const modalEl = document.getElementById('defModal');
    const modalTitle = document.getElementById('modalTitle');

    const f_id = document.getElementById('f_id');
    const f_name = document.getElementById('f_name');
    const f_ws_url = document.getElementById('f_ws_url');
    const f_kurum_kodu = document.getElementById('f_kurum_kodu');
    const f_username = document.getElementById('f_username');
    const f_pass_type = document.getElementById('f_pass_type');
    const f_is_active = document.getElementById('f_is_active');
    const activeLabel = document.getElementById('activeLabel');

    function setActiveLabel(){
      activeLabel.textContent = f_is_active.checked ? <?= json_encode(L('Aktif','Active',$lang)) ?> : <?= json_encode(L('Pasif','Inactive',$lang)) ?>;
    }
    f_is_active.addEventListener('change', setActiveLabel);
    setActiveLabel();

    document.getElementById('btnNew')?.addEventListener('click', () => {
      modalTitle.textContent = <?= json_encode(L('Yeni Tanım Ekle','Add New Definition',$lang)) ?>;
      f_id.value = '0';
      f_name.value = '';
      f_ws_url.value = '';
      f_kurum_kodu.value = '';
      f_username.value = '';
      f_pass_type.value = 'password';
      f_is_active.checked = true;
      setActiveLabel();

      [
        'opt_auto_send_on_service_add',
        'opt_auto_send_on_barcode_accept',
        'opt_dont_fetch_pdf',
        'opt_fetch_results_no_approve',
        'opt_auto_irsaliye',
        'opt_dont_auto_query_results'
      ].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.checked = false;
      });
    });

    document.querySelectorAll('.btnEdit').forEach(btn => {
      btn.addEventListener('click', () => {
        modalTitle.textContent = <?= json_encode(L('Tanımı Düzenle','Edit Definition',$lang)) ?>;

        f_id.value = btn.dataset.id || '0';
        f_name.value = btn.dataset.name || '';
        f_ws_url.value = btn.dataset.ws_url || '';
        f_kurum_kodu.value = btn.dataset.kurum_kodu || '';
        f_username.value = btn.dataset.username || '';
        f_pass_type.value = btn.dataset.pass_type || 'password';
        f_is_active.checked = (parseInt(btn.dataset.is_active || '0', 10) === 1);
        setActiveLabel();

        const map = [
          'opt_auto_send_on_service_add',
          'opt_auto_send_on_barcode_accept',
          'opt_dont_fetch_pdf',
          'opt_fetch_results_no_approve',
          'opt_auto_irsaliye',
          'opt_dont_auto_query_results'
        ];
        map.forEach(k => {
          const el = document.getElementById(k);
          if (!el) return;
          const v = parseInt(btn.dataset[k] || '0', 10);
          el.checked = (v === 1);
        });
      });
    });

    // URL'de edit varsa modali aç (geriye uyumluluk)
    <?php if ($editId > 0 && $editRow): ?>
      document.addEventListener('DOMContentLoaded', () => {
        const m = new bootstrap.Modal(modalEl);
        m.show();

        modalEl.addEventListener('hidden.bs.modal', () => {
          const url = new URL(window.location.href);
          url.searchParams.delete('edit');
          window.history.replaceState({}, document.title, url.toString());
        });
      });
    <?php endif; ?>

    document.getElementById('defForm')?.addEventListener('submit', () => {
      showOverlay(<?= json_encode(L('Kaydediliyor…','Saving…',$lang)) ?>, <?= json_encode(L('Değişiklikler veritabanına yazılıyor.','Writing changes to the database.',$lang)) ?>);
    });

    document.querySelectorAll('form').forEach(f => {
      const act = f.querySelector('input[name="action"]')?.value || '';
      if (act === 'delete' || act === 'toggle_active') {
        f.addEventListener('submit', () => {
          showOverlay(<?= json_encode(L('İşleniyor…','Processing…',$lang)) ?>, <?= json_encode(L('Lütfen bekleyin.','Please wait.',$lang)) ?>);
        });
      }
    });
  </script>
</body>
</html>
