<?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($s, ENT_QUOTES, 'UTF-8'); }

/* -----------------------------
   3) DB helpers
------------------------------ */
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 $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 = $_SESSION['csrf_dislab'];

function dl_bool_post(string $name): int { return isset($_POST[$name]) ? 1 : 0; }
function dl_redirect(string $url): void {
  if (!headers_sent()) { header("Location: $url"); exit; }
  echo "<script>location.href=".json_encode($url).";</script>";
  exit;
}

/* -----------------------------
   5) 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) {
        if (dl_db_exec("DELETE FROM dislab_tanimlari WHERE id = ?", [(string)$id])) {
          $_SESSION['flash_ok'] = L('Kayıt silindi.', 'Record deleted.', $lang);
          dl_redirect("?sayfa=dislab-tanimlari");
        }
      }
    }

    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 Adresi 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'] ?? '')) ?: null,
          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]);
          }
          $_SESSION['flash_ok'] = L('Kayıt güncellendi.', 'Record updated.', $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);
          $_SESSION['flash_ok'] = L('Kayıt eklendi.', 'Record created.', $lang);
        }
        dl_redirect("?sayfa=dislab-tanimlari");
      }
    }
  }
}

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

$rows = dl_db_fetch_all("SELECT * FROM dislab_tanimlari ORDER BY id DESC");
$editId = (int)($_GET['edit'] ?? 0);
$editRow = $editId > 0 ? dl_db_fetch_one("SELECT * FROM dislab_tanimlari WHERE id = ?", [(string)$editId]) : null;

/* -----------------------------
   6) UI Helpers
------------------------------ */
function dl_v(?array $row, string $k, string $default=''): string { return (string)($row[$k] ?? $default); }
function dl_ck(?array $row, string $k): string { return ($row && (int)$row[$k] === 1) ? 'checked' : ''; }
?>

<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&display=swap" rel="stylesheet">

<style>
  body { background: #f4f7fe; font-family: 'Plus Jakarta Sans', sans-serif; color: #1e293b; }
  .main-card { background: white; border: none; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.04); }
  .btn-primary { background: #3b5bff; border: none; padding: 10px 20px; border-radius: 12px; font-weight: 700; }
  .btn-primary:hover { background: #2f49e6; }
  .btn-light { background: #f1f5f9; border: none; border-radius: 12px; font-weight: 600; }
  .table thead th { background: #f8fafc; color: #64748b; font-size: 12px; text-transform: uppercase; letter-spacing: 0.5px; border: none; padding: 15px; }
  .table td { vertical-align: middle; padding: 15px; border-color: #f1f5f9; }
  .status-badge { padding: 6px 12px; border-radius: 8px; font-size: 12px; font-weight: 700; }
  .status-active { background: #ecfdf5; color: #059669; }
  .status-inactive { background: #fef2f2; color: #dc2626; }
  .modal-content { border: none; border-radius: 24px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.2); }
  .form-control, .form-select { border-radius: 12px; padding: 12px; border: 1px solid #e2e8f0; font-weight: 600; }
  .form-control:focus { box-shadow: 0 0 0 4px rgba(59,91,255,0.1); border-color: #3b5bff; }
  .form-check-input:checked { background-color: #3b5bff; border-color: #3b5bff; }
</style>

<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <div>
      <h2 class="fw-800 mb-1"><?= e(L('Dışlab Tanımları', 'External Lab Definitions', $lang)) ?></h2>
      <p class="text-muted small fw-600 mb-0"><?= e(L('Laboratuvar entegrasyonlarını ve otomasyon ayarlarını yönetin.', 'Manage lab integrations and automation settings.', $lang)) ?></p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#defModal">
      <i class="bi bi-plus-lg me-2"></i><?= e(L('Yeni Tanım', 'New Definition', $lang)) ?>
    </button>
  </div>

  <?php if ($flash_ok): ?>
    <div class="alert alert-success border-0 shadow-sm mb-4" style="border-radius:15px;">
      <i class="bi bi-check-circle-fill me-2"></i><?= e($flash_ok) ?>
    </div>
  <?php endif; ?>

  <div class="main-card overflow-hidden">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead>
          <tr>
            <th><?= L('Durum','Status',$lang) ?></th>
            <th><?= L('Tanım Bilgileri','Definition Info',$lang) ?></th>
            <th><?= L('Bağlantı Türü','Connection',$lang) ?></th>
            <th class="text-end"><?= L('İşlemler','Actions',$lang) ?></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($rows as $r): ?>
          <tr>
            <td style="width: 120px;">
              <span class="status-badge <?= (int)$r['is_active'] === 1 ? 'status-active' : 'status-inactive' ?>">
                <?= (int)$r['is_active'] === 1 ? L('Aktif','Active',$lang) : L('Pasif','Inactive',$lang) ?>
              </span>
            </td>
            <td>
              <div class="fw-bold text-dark"><?= e((string)$r['name']) ?></div>
              <div class="text-muted small"><?= e((string)$r['ws_url']) ?></div>
            </td>
            <td>
              <span class="badge bg-light text-dark rounded-pill px-3"><?= e((string)$r['pass_type']) ?></span>
              <?php if($r['username']): ?> <small class="ms-2 text-muted"><i class="bi bi-person me-1"></i><?= e($r['username']) ?></small> <?php endif; ?>
            </td>
            <td class="text-end">
              <a href="?sayfa=dislab-tanimlari&edit=<?= (int)$r['id'] ?>" class="btn btn-light btn-sm me-1">
                <i class="bi bi-pencil-square"></i>
              </a>
              <form method="post" class="d-inline" onsubmit="return confirm('Silinsin mi?');">
                <input type="hidden" name="csrf" value="<?= $CSRF ?>">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <button type="submit" class="btn btn-light btn-sm text-danger"><i class="bi bi-trash"></i></button>
              </form>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<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">
        <input type="hidden" name="csrf" value="<?= $CSRF ?>">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?= (int)($editRow['id'] ?? 0) ?>">
        
        <div class="modal-header border-0 p-4 pb-0">
          <h5 class="fw-800 mb-0"><?= $editRow ? L('Tanımı Düzenle','Edit Definition',$lang) : L('Yeni Tanım Ekle','Add New Definition',$lang) ?></h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>

        <div class="modal-body p-4">
          <div class="row g-3">
            <div class="col-md-8">
              <label class="form-label small fw-bold text-muted"><?= L('Tanım Adı','Definition Name',$lang) ?> *</label>
              <input type="text" name="name" class="form-control" required value="<?= e(dl_v($editRow,'name')) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label small fw-bold text-muted"><?= L('Aktif mi?','Is Active?',$lang) ?></label>
              <div class="form-check form-switch pt-2">
                <input class="form-check-input" type="checkbox" name="is_active" style="width: 40px; height: 20px;" <?= ($editRow ? (((int)$editRow['is_active']===1)?'checked':'') : 'checked') ?>>
              </div>
            </div>
            
            <div class="col-12">
              <label class="form-label small fw-bold text-muted"><?= L('Web Servis URL','Web Service URL',$lang) ?> *</label>
              <input type="url" name="ws_url" class="form-control" required value="<?= e(dl_v($editRow,'ws_url')) ?>">
            </div>

            <div class="col-md-6">
              <label class="form-label small fw-bold text-muted"><?= L('Kullanıcı Adı','Username',$lang) ?></label>
              <input type="text" name="username" class="form-control" value="<?= e(dl_v($editRow,'username')) ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label small fw-bold text-muted"><?= L('Kurum Kodu','Institution Code',$lang) ?></label>
              <input type="text" name="kurum_kodu" class="form-control" value="<?= e(dl_v($editRow,'kurum_kodu')) ?>">
            </div>

            <div class="col-md-4">
              <label class="form-label small fw-bold text-muted"><?= L('Şifre Türü','Pass Type',$lang) ?></label>
              <select class="form-select" name="pass_type">
                <option value="password" <?= dl_v($editRow,'pass_type')==='password'?'selected':'' ?>>Password</option>
                <option value="token" <?= dl_v($editRow,'pass_type')==='token'?'selected':'' ?>>Token</option>
                <option value="apikey" <?= dl_v($editRow,'pass_type')==='apikey'?'selected':'' ?>>API Key</option>
              </select>
            </div>
            <div class="col-md-8">
              <label class="form-label small fw-bold text-muted"><?= L('Şifre / Key','Password / Key',$lang) ?></label>
              <input type="password" name="pass_plain" class="form-control" placeholder="<?= $editRow ? L('Değiştirmek için yazın','Type to change','') : '' ?>">
            </div>

            <div class="col-12 mt-4">
              <h6 class="fw-bold mb-3"><i class="bi bi-gear-fill me-2 text-primary"></i><?= L('Otomasyon Seçenekleri','Automation Options',$lang) ?></h6>
              <div class="row g-3 bg-light p-3 rounded-4">
                <?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):
                ?>
                <div class="col-md-6">
                  <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="<?= $key ?>" id="<?= $key ?>" <?= dl_ck($editRow, $key) ?>>
                    <label class="form-check-label small fw-semibold" for="<?= $key ?>"><?= $label ?></label>
                  </div>
                </div>
                <?php endforeach; ?>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer border-0 p-4 pt-0">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal"><?= L('Vazgeç','Cancel',$lang) ?></button>
          <button type="submit" class="btn btn-primary px-4"><?= L('Kaydet','Save',$lang) ?></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>
  // Eğer düzenleme modundaysak (URL'de edit=ID varsa) modali otomatik aç
  <?php if ($editId > 0): ?>
    const myModal = new bootstrap.Modal(document.getElementById('defModal'));
    myModal.show();
    // Modal kapandığında URL'deki edit parametresini temizle (temiz bir görünüm için)
    document.getElementById('defModal').addEventListener('hidden.bs.modal', function () {
        window.history.replaceState({}, document.title, "?sayfa=dislab-tanimlari");
    });
  <?php endif; ?>
</script>