<?php
declare(strict_types=1);

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

// ✅ Header already sent fix: output buffer
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), "/");

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

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

function nl_db_fetch_all(string $sql, array $params = []): array {
  if (nl_db_is_pdo()) {
    $st = $GLOBALS['pdo']->prepare($sql);
    $st->execute($params);
    return $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
  }
  if (nl_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 nl_db_fetch_one(string $sql, array $params = []): ?array {
  $rows = nl_db_fetch_all($sql, $params);
  return $rows[0] ?? null;
}
function nl_db_exec(string $sql, array $params = []): bool {
  if (nl_db_is_pdo()) {
    $st = $GLOBALS['pdo']->prepare($sql);
    return $st->execute($params);
  }
  if (nl_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;
}

/* -----------------------------
   4) POST helper (dot(.) => underscore(_) fix)
   PHP name="mail.smtp_host" => $_POST["mail_smtp_host"]
------------------------------ */
function nl_post(string $key, $default = null) {
  $k1 = $key;
  $k2 = str_replace('.', '_', $key);
  if (array_key_exists($k1, $_POST)) return $_POST[$k1];
  if (array_key_exists($k2, $_POST)) return $_POST[$k2];
  return $default;
}

/* -----------------------------
   5) Crypto wrappers (optional)
------------------------------ */
function nl_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);
  if (function_exists('settings_encrypt')) return (string)settings_encrypt($plain);
  return $plain; // fallback
}
function nl_decrypt(string $cipher): string {
  if ($cipher === '') return '';
  if (function_exists('crypto_decrypt'))   return (string)crypto_decrypt($cipher);
  if (function_exists('decrypt'))         return (string)decrypt($cipher);
  if (function_exists('settings_decrypt')) return (string)settings_decrypt($cipher);
  return $cipher; // fallback
}

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

/* -----------------------------
   7) Fields (single screen)
------------------------------ */
$FIELDS = [
  // LAB
  ['group'=>'lab', 'key'=>'lab.enabled',      'type'=>'switch',   'secret'=>0, 'tr'=>'Aktif',             'en'=>'Enabled'],
  ['group'=>'lab', 'key'=>'lab.base_url',     'type'=>'url',      'secret'=>0, 'tr'=>'Base URL',          'en'=>'Base URL', 'ph'=>'https://...'],
  ['group'=>'lab', 'key'=>'lab.username',     'type'=>'text',     'secret'=>0, 'tr'=>'Kullanıcı Adı',     'en'=>'Username'],
  ['group'=>'lab', 'key'=>'lab.password',     'type'=>'password', 'secret'=>1, 'tr'=>'Şifre',             'en'=>'Password'],

  // SMS
  ['group'=>'sms', 'key'=>'sms.enabled',      'type'=>'switch',   'secret'=>0, 'tr'=>'Aktif',             'en'=>'Enabled'],
  ['group'=>'sms', 'key'=>'sms.provider',     'type'=>'select',   'secret'=>0, 'tr'=>'Sağlayıcı',         'en'=>'Provider',
    'options'=>['netgsm'=>'NetGSM', 'iletimerkezi'=>'İletiMerkezi', 'twilio'=>'Twilio']
  ],
  ['group'=>'sms', 'key'=>'sms.api_key',      'type'=>'password', 'secret'=>1, 'tr'=>'API Key',           'en'=>'API Key'],
  ['group'=>'sms', 'key'=>'sms.sender',       'type'=>'text',     'secret'=>0, 'tr'=>'Başlık (Sender)',   'en'=>'Sender/Title'],

  // e-Nabız
  ['group'=>'enabiz', 'key'=>'enabiz.enabled',       'type'=>'switch',   'secret'=>0, 'tr'=>'Aktif',         'en'=>'Enabled'],
  ['group'=>'enabiz', 'key'=>'enabiz.base_url',      'type'=>'url',      'secret'=>0, 'tr'=>'Base URL',      'en'=>'Base URL', 'ph'=>'https://...'],
  ['group'=>'enabiz', 'key'=>'enabiz.client_id',     'type'=>'text',     'secret'=>0, 'tr'=>'Client ID',     'en'=>'Client ID'],
  ['group'=>'enabiz', 'key'=>'enabiz.client_secret', 'type'=>'password', 'secret'=>1, 'tr'=>'Client Secret', 'en'=>'Client Secret'],

  // Mail
  ['group'=>'mail', 'key'=>'mail.enabled',     'type'=>'switch',   'secret'=>0, 'tr'=>'Aktif',           'en'=>'Enabled'],
  ['group'=>'mail', 'key'=>'mail.smtp_host',   'type'=>'text',     'secret'=>0, 'tr'=>'SMTP Host',       'en'=>'SMTP Host'],
  ['group'=>'mail', 'key'=>'mail.smtp_port',   'type'=>'number',   'secret'=>0, 'tr'=>'SMTP Port',       'en'=>'SMTP Port', 'ph'=>'587'],
  ['group'=>'mail', 'key'=>'mail.smtp_user',   'type'=>'text',     'secret'=>0, 'tr'=>'SMTP Kullanıcı',   'en'=>'SMTP Username'],
  ['group'=>'mail', 'key'=>'mail.smtp_pass',   'type'=>'password', 'secret'=>1, 'tr'=>'SMTP Şifre',       'en'=>'SMTP Password'],
  ['group'=>'mail', 'key'=>'mail.smtp_secure', 'type'=>'select',   'secret'=>0, 'tr'=>'Güvenlik',         'en'=>'Security',
    'options'=>['tls'=>'TLS', 'ssl'=>'SSL', 'none'=>'None']
  ],
  ['group'=>'mail', 'key'=>'mail.from_email',  'type'=>'email',    'secret'=>0, 'tr'=>'Gönderici E-posta', 'en'=>'From Email'],
  ['group'=>'mail', 'key'=>'mail.from_name',   'type'=>'text',     'secret'=>0, 'tr'=>'Gönderici Adı',     'en'=>'From Name'],
];

/* -----------------------------
   8) Load existing settings
------------------------------ */
function nl_load_settings(): array {
  $rows = nl_db_fetch_all("SELECT skey, svalue, is_secret, updated_at, updated_by FROM app_settings");
  $SET = [];
  foreach ($rows as $r) {
    $k = (string)($r['skey'] ?? '');
    if ($k === '') continue;
    $SET[$k] = [
      'value'     => (string)($r['svalue'] ?? ''),
      'is_secret' => (int)($r['is_secret'] ?? 0),
      'updated_at'=> (string)($r['updated_at'] ?? ''),
      'updated_by'=> (string)($r['updated_by'] ?? ''),
    ];
  }
  return $SET;
}
$SET = nl_load_settings();

/* -----------------------------
   9) Save helper
------------------------------ */
function nl_upsert_setting(string $key, string $storeValue, int $isSecret, int $userId): bool {
  $exists = nl_db_fetch_one("SELECT skey FROM app_settings WHERE skey = ? LIMIT 1", [$key]);
  if ($exists) {
    return nl_db_exec(
      "UPDATE app_settings
       SET svalue = ?, is_secret = ?, updated_by = ?, updated_at = NOW()
       WHERE skey = ?",
      [$storeValue, (string)$isSecret, (string)$userId, $key]
    );
  }
  return nl_db_exec(
    "INSERT INTO app_settings (skey, svalue, is_secret, updated_by, updated_at)
     VALUES (?, ?, ?, ?, NOW())",
    [$key, $storeValue, (string)$isSecret, (string)$userId]
  );
}

/* -----------------------------
   10) Value getters for view
------------------------------ */
function nl_get(string $key, string $default = ''): string {
  $row = $GLOBALS['SET'][$key] ?? null;
  if (!$row) return $default;
  return (string)($row['value'] ?? $default);
}
function nl_get_secret_plain(string $key): string {
  $row = $GLOBALS['SET'][$key] ?? null;
  if (!$row) return '';
  $cipher = (string)($row['value'] ?? '');
  if ($cipher === '') return '';
  // secret olarak işaretliyse decrypt dene
  return nl_decrypt($cipher);
}
function nl_has_value(string $key): bool {
  $row = $GLOBALS['SET'][$key] ?? null;
  return $row && (string)$row['value'] !== '';
}
function nl_checked(string $key): string {
  $v = nl_get($key, '0');
  return ($v === '1' || strtolower($v) === 'true') ? 'checked' : '';
}
function nl_selected(string $key, string $opt): string {
  return nl_get($key, '') === $opt ? 'selected' : '';
}

/* -----------------------------
   11) Mail test (PHPMailer)
------------------------------ */
function nl_mail_test(array &$flash_ok, array &$flash_err, string $lang): void {
  $smtpEnabled = nl_get('mail.enabled', '0') === '1';
  if (!$smtpEnabled) {
    $flash_err[] = L('Mail entegrasyonu kapalı (mail.enabled=0).', 'Mail integration is disabled (mail.enabled=0).', $lang);
    return;
  }

  $host   = trim(nl_get('mail.smtp_host', ''));
  $port   = (int)(nl_get('mail.smtp_port', '587') ?: 587);
  $user   = trim(nl_get('mail.smtp_user', ''));
  $pass   = nl_get_secret_plain('mail.smtp_pass'); // ✅ decrypt
  $secure = trim(nl_get('mail.smtp_secure', 'tls'));
  $fromE  = trim(nl_get('mail.from_email', ''));
  $fromN  = trim(nl_get('mail.from_name', 'Nephro Link'));

  $to = trim((string)nl_post('mail_test_to', ''));
  if ($to === '') $to = $fromE;

  // basic validation
  if ($host === '' || $fromE === '' || $to === '') {
    $flash_err[] = L('SMTP Host / From Email / Test Alıcı boş olamaz.', 'SMTP Host / From Email / Test Recipient cannot be empty.', $lang);
    return;
  }
  if (!filter_var($fromE, FILTER_VALIDATE_EMAIL) || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
    $flash_err[] = L('E-posta formatı geçersiz.', 'Invalid email format.', $lang);
    return;
  }

  // PHPMailer autoload
  $autoload = $GLOBALS['root'] . '/vendor/autoload.php';
  if (!is_file($autoload)) {
    $flash_err[] = L('PHPMailer bulunamadı. vendor/autoload.php eksik.', 'PHPMailer not found. vendor/autoload.php is missing.', $lang);
    return;
  }
  require_once $autoload;

  try {
    // PHPMailer namespaces
    $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
    $mail->CharSet = 'UTF-8';
    $mail->isSMTP();
    $mail->Host = $host;
    $mail->Port = $port;

    // auth: user varsa auth aç
    if ($user !== '') {
      $mail->SMTPAuth = true;
      $mail->Username = $user;
      $mail->Password = $pass;
    } else {
      $mail->SMTPAuth = false;
    }

    if ($secure === 'none') {
      $mail->SMTPSecure = '';
      $mail->SMTPAutoTLS = false;
    } elseif ($secure === 'ssl') {
      $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
    } else {
      $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
    }

    $mail->setFrom($fromE, $fromN ?: 'Nephro Link');
    $mail->addAddress($to);

    $mail->Subject = 'Nephro Link SMTP Test';
    $mail->Body    = "SMTP test başarılı ✅\n\nTarih: " . date('Y-m-d H:i:s');
    $mail->AltBody = $mail->Body;

    $mail->send();
    $flash_ok[] = L('Mail test başarılı. E-posta gönderildi.', 'Mail test successful. Email sent.', $lang);
  } catch (\Throwable $ex) {
    // Şifre vs sızdırma yok, sadece hata mesajı
    $flash_err[] = L('Mail test hatası: ', 'Mail test error: ', $lang) . $ex->getMessage();
  }
}

/* -----------------------------
   12) POST: Save / Test
------------------------------ */
$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 {
    $do = (string)($_POST['do'] ?? 'save');

    if ($do === 'mail_test') {
      // ✅ test: kaydetmeden test eder
      nl_mail_test($flash_ok, $flash_err, $lang);

      // test sonrası SET tekrar yükle (ekran stabil kalsın)
      $GLOBALS['SET'] = $SET = nl_load_settings();
    } else {
      // ✅ save
      $allOk = true;

      foreach ($GLOBALS['FIELDS'] as $f) {
        $key    = (string)$f['key'];
        $type   = (string)$f['type'];
        $secret = (int)$f['secret'];

        // switch: checkbox yoksa 0 kabul
        if ($type === 'switch') {
          $newVal = (nl_post($key, null) !== null) ? '1' : '0';
          $ok = nl_upsert_setting($key, $newVal, 0, $GLOBALS['userId']);
          if (!$ok) $allOk = false;
          continue;
        }

        // select/text/url/email/number: trim
        $newVal = trim((string) nl_post($key, ''));

        // secret alan: boş bırakılırsa eski korunur (silme yok)
        if ($secret === 1) {
          if ($newVal === '') {
            continue;
          }
          $store = nl_encrypt($newVal);
          $ok = nl_upsert_setting($key, $store, 1, $GLOBALS['userId']);
          if (!$ok) $allOk = false;
          continue;
        }

        // normal alan
        $ok = nl_upsert_setting($key, $newVal, 0, $GLOBALS['userId']);
        if (!$ok) $allOk = false;
      }

      if ($allOk) {
        $_SESSION['flash_settings_ok'] = L('Ayarlar kaydedildi.', 'Settings saved.', $lang);

        if (!headers_sent()) {
          header("Location: ?sayfa=ayarlar&saved=1");
          exit;
        }
        echo "<script>location.href='?sayfa=ayarlar&saved=1';</script>";
        echo "<noscript><meta http-equiv='refresh' content='0;url=?sayfa=ayarlar&saved=1'></noscript>";
        exit;
      } else {
        $flash_err[] = L('Kaydetme sırasında bir hata oluştu.', 'An error occurred while saving.', $lang);
      }

      // save sonrası SET tekrar yükle (bazı server’larda redirect olmadan da düzgün görünsün)
      $GLOBALS['SET'] = $SET = nl_load_settings();
    }
  }
}

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

?>
<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">
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&family=Inter:wght@400;600;700&display=swap" rel="stylesheet">

<style>
  :root{
    --nl-bg:#f4f7fe;
    --nl-card:#ffffff;
    --nl-text:#0f172a;
    --nl-muted:#64748b;
    --nl-border:#e5e7eb;
    --nl-primary:#3b5bff;
    --nl-primary-2:#2f49e6;
    --nl-shadow: 0 10px 30px rgba(2,6,23,.06);
    --nl-radius: 18px;
  }
  .nl-page{
    font-family: "Plus Jakarta Sans","Inter",system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
    background: var(--nl-bg);
    width:100%;
    padding: 18px;
  }
  .nl-top{
    display:flex; align-items:flex-start; justify-content:space-between;
    gap:12px; flex-wrap:wrap;
    margin-bottom:14px;
  }
  .nl-title{
    margin:0;
    font-weight:800;
    letter-spacing:-0.02em;
    color:var(--nl-text);
    font-size: 26px;
    line-height: 1.1;
  }
  .nl-sub{
    margin:6px 0 0 0;
    color:var(--nl-muted);
    font-size: 13.5px;
    font-weight:600;
  }
  .nl-actions{
    display:flex; gap:10px; align-items:center; justify-content:flex-end;
    flex-wrap: wrap;
  }

  .nl-grid{
    display:grid;
    grid-template-columns: 1fr;
    gap: 14px;
  }
  @media (min-width: 992px){
    .nl-grid{ grid-template-columns: 1fr 1fr; }
  }

  .nl-card{
    background: var(--nl-card);
    border: 1px solid var(--nl-border);
    border-radius: var(--nl-radius);
    box-shadow: var(--nl-shadow);
    overflow:hidden;
  }
  .nl-card-h{
    padding: 16px 16px 10px 16px;
    display:flex; align-items:flex-start; justify-content:space-between;
    gap:10px;
    border-bottom: 1px solid rgba(229,231,235,.65);
  }
  .nl-card-h .left{
    display:flex; gap:10px; align-items:flex-start;
  }
  .nl-ico{
    width:40px; height:40px; border-radius: 12px;
    display:flex; align-items:center; justify-content:center;
    background: rgba(59,91,255,.10);
    color: var(--nl-primary);
    font-size: 18px;
    flex: 0 0 auto;
  }
  .nl-h-title{
    margin:0;
    font-weight:800;
    color:var(--nl-text);
    font-size: 15px;
    line-height:1.2;
  }
  .nl-h-desc{
    margin:4px 0 0 0;
    color:var(--nl-muted);
    font-size: 12.8px;
    font-weight:600;
  }

  .nl-body{ padding: 14px 16px 16px 16px; }

  .nl-field{
    border: 1px solid rgba(229,231,235,.9);
    border-radius: 16px;
    padding: 12px;
    margin-bottom: 12px;
    background: #fbfcff;
  }
  .nl-field:last-child{ margin-bottom:0; }

  .nl-label{
    display:flex; align-items:center; justify-content:space-between;
    gap:10px;
    margin-bottom: 8px;
  }
  .nl-label .t{
    font-weight:800;
    color:var(--nl-text);
    font-size: 13px;
  }
  .nl-label .hint{
    color:var(--nl-muted);
    font-size: 12px;
    font-weight:600;
  }

  .nl-input{
    width:100%;
    box-sizing:border-box;
    border:1px solid rgba(229,231,235,.95);
    background: #ffffff;
    border-radius: 14px;
    padding: 12px 12px;
    font-weight:700;
    color:var(--nl-text);
    outline:none;
    min-width: 0;
  }
  .nl-input:focus{
    border-color: rgba(59,91,255,.55);
    box-shadow: 0 0 0 4px rgba(59,91,255,.12);
  }

  .nl-row{
    display:flex; align-items:center; justify-content:space-between;
    gap: 10px;
  }

  .nl-secret-note{
    margin-top: 8px;
    color: var(--nl-muted);
    font-size: 12px;
    font-weight:600;
  }

  .nl-footer{
    margin-top: 14px;
    padding-top: 14px;
    border-top: 1px solid rgba(229,231,235,.75);
    display:flex;
    justify-content:flex-end;
    gap: 10px;
    flex-wrap: wrap;
  }
  .nl-save{
    border:0;
    background: var(--nl-primary);
    color:#fff;
    font-weight:800;
    padding: 12px 18px;
    border-radius: 14px;
    box-shadow: 0 12px 24px rgba(59,91,255,.18);
  }
  .nl-save:hover{ background: var(--nl-primary-2); }

  .nl-test{
    border: 1px solid rgba(229,231,235,.95);
    background: #ffffff;
    color: var(--nl-text);
    font-weight: 800;
    padding: 12px 16px;
    border-radius: 14px;
  }
  .nl-test:hover{
    border-color: rgba(59,91,255,.35);
    box-shadow: 0 10px 20px rgba(2,6,23,.04);
  }

  .nl-badge-ok{
    background: rgba(16,185,129,.12);
    color:#059669;
    border:1px solid rgba(16,185,129,.22);
    border-radius: 999px;
    padding: 9px 12px;
    font-weight:800;
    font-size: 12.5px;
    display:flex; align-items:center; gap:8px;
  }

  /* Switch */
  .nl-switch{ width: 46px; height: 26px; }
</style>

<div class="nl-page">
  <div class="nl-top">
    <div>
      <h1 class="nl-title"><?= e(L('Sistem Ayarları', 'System Settings', $lang)) ?></h1>
      <div class="nl-sub"><?= e(L('Tüm entegrasyon bilgilerini tek ekranda yönet.', 'Manage all integration credentials on one screen.', $lang)) ?></div>
    </div>

    <div class="nl-actions">
      <?php if (!empty($flash_ok)): ?>
        <div class="nl-badge-ok">
          <i class="bi bi-check2-circle"></i> <?= e(implode(' • ', $flash_ok)) ?>
        </div>
      <?php endif; ?>

      <?php if (!empty($flash_err)): ?>
        <div class="alert alert-danger mb-0 py-2" style="border-radius:14px;">
          <i class="bi bi-exclamation-triangle me-1"></i> <?= e(implode(' • ', $flash_err)) ?>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <form method="post" action="?sayfa=ayarlar">
    <input type="hidden" name="csrf" value="<?= e($CSRF) ?>">
    <input type="hidden" name="lang" value="<?= e($lang) ?>">

    <div class="nl-grid">

      <!-- Dış Lab -->
      <div class="nl-card">
        <div class="nl-card-h">
          <div class="left">
            <div class="nl-ico"><i class="bi bi-flask"></i></div>
            <div>
              <div class="nl-h-title"><?= e(L('Dış Laboratuvar', 'External Lab', $lang)) ?></div>
              <div class="nl-h-desc"><?= e(L('Servis URL ve giriş bilgileri.', 'Service URL and credentials.', $lang)) ?></div>
            </div>
          </div>
        </div>
        <div class="nl-body">
          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Aktif', 'Enabled', $lang)) ?></div>
              <div class="hint"><?= e(L('Aç/Kapat', 'On/Off', $lang)) ?></div>
            </div>
            <div class="nl-row">
              <div class="text-muted fw-semibold" style="font-size:12px;">lab.enabled</div>
              <input class="form-check-input nl-switch" type="checkbox" name="lab.enabled" <?= nl_checked('lab.enabled') ?>>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Base URL', 'Base URL', $lang)) ?></div>
              <div class="hint">lab.base_url</div>
            </div>
            <input class="nl-input" type="url" name="lab.base_url" placeholder="https://..." value="<?= e(nl_get('lab.base_url')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Kullanıcı Adı', 'Username', $lang)) ?></div>
              <div class="hint">lab.username</div>
            </div>
            <input class="nl-input" type="text" name="lab.username" value="<?= e(nl_get('lab.username')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Şifre', 'Password', $lang)) ?></div>
              <div class="hint">lab.password</div>
            </div>
            <input class="nl-input" type="password" name="lab.password" placeholder="<?= e(L('Boş bırakırsan mevcut şifre korunur.', 'Leave blank to keep current password.', $lang)) ?>">
            <div class="nl-secret-note">
              <?= nl_has_value('lab.password')
                ? e(L('Kayıtlı değer var. Değiştirmek için yeni değer gir.', 'A value is saved. Enter a new one to change.', $lang))
                : e(L('Kayıtlı değer yok. Değer girerek kaydedebilirsin.', 'No saved value. Enter one to save.', $lang)); ?>
            </div>
          </div>
        </div>
      </div>

      <!-- SMS -->
      <div class="nl-card">
        <div class="nl-card-h">
          <div class="left">
            <div class="nl-ico"><i class="bi bi-chat-left-text"></i></div>
            <div>
              <div class="nl-h-title">SMS</div>
              <div class="nl-h-desc"><?= e(L('SMS sağlayıcı ve API bilgileri.', 'SMS provider and API credentials.', $lang)) ?></div>
            </div>
          </div>
        </div>
        <div class="nl-body">

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Aktif', 'Enabled', $lang)) ?></div>
              <div class="hint"><?= e(L('Aç/Kapat', 'On/Off', $lang)) ?></div>
            </div>
            <div class="nl-row">
              <div class="text-muted fw-semibold" style="font-size:12px;">sms.enabled</div>
              <input class="form-check-input nl-switch" type="checkbox" name="sms.enabled" <?= nl_checked('sms.enabled') ?>>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Sağlayıcı', 'Provider', $lang)) ?></div>
              <div class="hint">sms.provider</div>
            </div>
            <select class="nl-input" name="sms.provider">
              <option value="netgsm" <?= nl_selected('sms.provider','netgsm') ?>>NetGSM</option>
              <option value="iletimerkezi" <?= nl_selected('sms.provider','iletimerkezi') ?>>İletiMerkezi</option>
              <option value="twilio" <?= nl_selected('sms.provider','twilio') ?>>Twilio</option>
            </select>
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t">API Key</div>
              <div class="hint">sms.api_key</div>
            </div>
            <input class="nl-input" type="password" name="sms.api_key" placeholder="<?= e(L('Boş bırakırsan mevcut key korunur.', 'Leave blank to keep current key.', $lang)) ?>">
            <div class="nl-secret-note">
              <?= nl_has_value('sms.api_key')
                ? e(L('Kayıtlı değer var. Değiştirmek için yeni değer gir.', 'A value is saved. Enter a new one to change.', $lang))
                : e(L('Kayıtlı değer yok. Değer girerek kaydedebilirsin.', 'No saved value. Enter one to save.', $lang)); ?>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Başlık (Sender)', 'Sender/Title', $lang)) ?></div>
              <div class="hint">sms.sender</div>
            </div>
            <input class="nl-input" type="text" name="sms.sender" value="<?= e(nl_get('sms.sender')) ?>">
          </div>

        </div>
      </div>

      <!-- e-Nabız -->
      <div class="nl-card">
        <div class="nl-card-h">
          <div class="left">
            <div class="nl-ico"><i class="bi bi-heart-pulse"></i></div>
            <div>
              <div class="nl-h-title">e-Nabız</div>
              <div class="nl-h-desc"><?= e(L('e-Nabız istemci bilgileri.', 'e-Nabız client credentials.', $lang)) ?></div>
            </div>
          </div>
        </div>
        <div class="nl-body">

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Aktif', 'Enabled', $lang)) ?></div>
              <div class="hint"><?= e(L('Aç/Kapat', 'On/Off', $lang)) ?></div>
            </div>
            <div class="nl-row">
              <div class="text-muted fw-semibold" style="font-size:12px;">enabiz.enabled</div>
              <input class="form-check-input nl-switch" type="checkbox" name="enabiz.enabled" <?= nl_checked('enabiz.enabled') ?>>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Base URL', 'Base URL', $lang)) ?></div>
              <div class="hint">enabiz.base_url</div>
            </div>
            <input class="nl-input" type="url" name="enabiz.base_url" placeholder="https://..." value="<?= e(nl_get('enabiz.base_url')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t">Client ID</div>
              <div class="hint">enabiz.client_id</div>
            </div>
            <input class="nl-input" type="text" name="enabiz.client_id" value="<?= e(nl_get('enabiz.client_id')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label">
              <div class="t">Client Secret</div>
              <div class="hint">enabiz.client_secret</div>
            </div>
            <input class="nl-input" type="password" name="enabiz.client_secret" placeholder="<?= e(L('Boş bırakırsan mevcut secret korunur.', 'Leave blank to keep current secret.', $lang)) ?>">
            <div class="nl-secret-note">
              <?= nl_has_value('enabiz.client_secret')
                ? e(L('Kayıtlı değer var. Değiştirmek için yeni değer gir.', 'A value is saved. Enter a new one to change.', $lang))
                : e(L('Kayıtlı değer yok. Değer girerek kaydedebilirsin.', 'No saved value. Enter one to save.', $lang)); ?>
            </div>
          </div>

        </div>
      </div>

      <!-- Mail -->
      <div class="nl-card">
        <div class="nl-card-h">
          <div class="left">
            <div class="nl-ico"><i class="bi bi-envelope-paper"></i></div>
            <div>
              <div class="nl-h-title"><?= e(L('Mail (SMTP)', 'Mail (SMTP)', $lang)) ?></div>
              <div class="nl-h-desc"><?= e(L('SMTP sunucu ve gönderici ayarları.', 'SMTP server and sender settings.', $lang)) ?></div>
            </div>
          </div>
        </div>
        <div class="nl-body">

          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Aktif', 'Enabled', $lang)) ?></div>
              <div class="hint"><?= e(L('Aç/Kapat', 'On/Off', $lang)) ?></div>
            </div>
            <div class="nl-row">
              <div class="text-muted fw-semibold" style="font-size:12px;">mail.enabled</div>
              <input class="form-check-input nl-switch" type="checkbox" name="mail.enabled" <?= nl_checked('mail.enabled') ?>>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t">SMTP Host</div><div class="hint">mail.smtp_host</div></div>
            <input class="nl-input" type="text" name="mail.smtp_host" value="<?= e(nl_get('mail.smtp_host')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t">SMTP Port</div><div class="hint">mail.smtp_port</div></div>
            <input class="nl-input" type="number" name="mail.smtp_port" placeholder="587" value="<?= e(nl_get('mail.smtp_port')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t"><?= e(L('SMTP Kullanıcı', 'SMTP Username', $lang)) ?></div><div class="hint">mail.smtp_user</div></div>
            <input class="nl-input" type="text" name="mail.smtp_user" value="<?= e(nl_get('mail.smtp_user')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t"><?= e(L('SMTP Şifre', 'SMTP Password', $lang)) ?></div><div class="hint">mail.smtp_pass</div></div>
            <input class="nl-input" type="password" name="mail.smtp_pass" placeholder="<?= e(L('Boş bırakırsan mevcut şifre korunur.', 'Leave blank to keep current password.', $lang)) ?>">
            <div class="nl-secret-note">
              <?= nl_has_value('mail.smtp_pass')
                ? e(L('Kayıtlı değer var. Değiştirmek için yeni değer gir.', 'A value is saved. Enter a new one to change.', $lang))
                : e(L('Kayıtlı değer yok. Değer girerek kaydedebilirsin.', 'No saved value. Enter one to save.', $lang)); ?>
            </div>
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t"><?= e(L('Güvenlik', 'Security', $lang)) ?></div><div class="hint">mail.smtp_secure</div></div>
            <select class="nl-input" name="mail.smtp_secure">
              <option value="tls"  <?= nl_selected('mail.smtp_secure','tls') ?>>TLS</option>
              <option value="ssl"  <?= nl_selected('mail.smtp_secure','ssl') ?>>SSL</option>
              <option value="none" <?= nl_selected('mail.smtp_secure','none') ?>>None</option>
            </select>
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t"><?= e(L('Gönderici E-posta', 'From Email', $lang)) ?></div><div class="hint">mail.from_email</div></div>
            <input class="nl-input" type="email" name="mail.from_email" value="<?= e(nl_get('mail.from_email')) ?>">
          </div>

          <div class="nl-field">
            <div class="nl-label"><div class="t"><?= e(L('Gönderici Adı', 'From Name', $lang)) ?></div><div class="hint">mail.from_name</div></div>
            <input class="nl-input" type="text" name="mail.from_name" value="<?= e(nl_get('mail.from_name')) ?>">
          </div>

          <!-- ✅ TEST ALANI (DB’ye yazılmaz) -->
          <div class="nl-field">
            <div class="nl-label">
              <div class="t"><?= e(L('Test Alıcı E-posta', 'Test Recipient Email', $lang)) ?></div>
              <div class="hint"><?= e(L('Sadece test için', 'Only for testing', $lang)) ?></div>
            </div>
            <input class="nl-input" type="email" name="mail_test_to" placeholder="<?= e(L('Boşsa From Email kullanılır', 'If empty, From Email will be used', $lang)) ?>" value="<?= e((string)nl_post('mail_test_to','')) ?>">
          </div>

        </div>
      </div>

    </div>

    <div class="nl-footer">
      <!-- ✅ MAIL TEST ET -->
      <button class="nl-test" type="submit" name="do" value="mail_test">
        <i class="bi bi-send-check me-2"></i>
        <?= e(L('Mail Test Et', 'Test Email', $lang)) ?>
      </button>

      <!-- ✅ KAYDET -->
      <button class="nl-save" type="submit" name="do" value="save">
        <i class="bi bi-check2-circle me-2"></i>
        <?= e(L('Değişiklikleri Kaydet', 'Save Changes', $lang)) ?>
      </button>
    </div>

  </form>
</div>
