<?php
session_start();
require_once __DIR__ . '/../../vendor/autoload.php';

$envFile = __DIR__ . '/../../.env';
if (file_exists($envFile)) {
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/../..');
    $dotenv->safeLoad();
}

use App\Auth;
use App\Csrf;
use App\Database;

Auth::init();
Auth::requireRole(['admin','staff']);
$pdo = Database::getConnection();
$errors = [];
$info = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    try {
      if ($action === 'fetch_services') {
        $labId = (int)($_POST['lab_id'] ?? 0);
        if (!$labId) {
          $errors[] = 'Laboratuvar seçiniz';
        } else {
          $lab = $pdo->prepare('SELECT * FROM external_laboratories WHERE id=:id AND status="active"');
          $lab->execute([':id' => $labId]);
          $labConf = $lab->fetch(PDO::FETCH_ASSOC);
          
          if (!$labConf) {
            $errors[] = 'Laboratuvar bulunamadı';
          } else {
            $pass = (string)($labConf['api_password'] ?? '');
            $wsUrl = trim((string)($labConf['api_url'] ?? ''));
            $kurumKodu = (string)($labConf['api_key'] ?? '');
            
            if (!class_exists('SoapClient')) {
              $errors[] = 'SOAP eklentisi yok';
            } else {
              try {
                $client = new SoapClient($wsUrl . "?WSDL", [
                  'trace' => 1,
                  'soap_version' => SOAP_1_2,
                  'exceptions' => true,
                  'cache_wsdl' => WSDL_CACHE_NONE,
                  'connection_timeout' => 15,
                ]);
                
                $params = [
                  'kurumbilgileri' => [
                    'WebUserKurumId' => 0,
                    'KullaniciAdi' => (string)($labConf['username'] ?? ''),
                    'Sifre' => $pass,
                    'Kodu' => $kurumKodu,
                    'KurumKodu' => ''
                  ]
                ];
                
                $res = $client->HizmetListesiGetir($params);
                
                $services = [];
                if (isset($res->HizmetListesi->Liste->Detay)) {
                  $data = $res->HizmetListesi->Liste->Detay;
                  $services = is_array($data) ? $data : [$data];
                }
                
                // Save to database
                $insertStmt = $pdo->prepare('
                  INSERT INTO external_lab_services 
                  (external_lab_id, service_code, service_name, sut_code, sample_type_id, sample_type_name, container_id, container_name)
                  VALUES (:lab_id, :code, :name, :sut, :sample_id, :sample_name, :cont_id, :cont_name)
                  ON DUPLICATE KEY UPDATE 
                  service_name=VALUES(service_name), 
                  sut_code=VALUES(sut_code),
                  sample_type_id=VALUES(sample_type_id),
                  sample_type_name=VALUES(sample_type_name),
                  container_id=VALUES(container_id),
                  container_name=VALUES(container_name),
                  updated_at=CURRENT_TIMESTAMP
                ');
                
                $count = 0;
                foreach ($services as $s) {
                  $insertStmt->execute([
                    ':lab_id' => $labId,
                    ':code' => (string)($s->Kodu ?? ''),
                    ':name' => (string)($s->Adi ?? ''),
                    ':sut' => (string)($s->SutKodu ?? ''),
                    ':sample_id' => (string)($s->OrnekTurId ?? ''),
                    ':sample_name' => (string)($s->OrnekTurAdi ?? ''),
                    ':cont_id' => (string)($s->KapId ?? ''),
                    ':cont_name' => (string)($s->KapAdi ?? ''),
                  ]);
                  $count++;
                }
                
                $info = "{$count} test başarıyla senkronize edildi";
              } catch (Throwable $e) {
                $errors[] = 'Servis hatası: ' . $e->getMessage();
              }
            }
          }
        }
      } elseif ($action === 'save_mapping') {
        $serviceId = (int)($_POST['service_id'] ?? 0);
        $localCode = trim($_POST['local_test_code'] ?? '');
        $localName = trim($_POST['local_test_name'] ?? '');
        $autoImport = isset($_POST['auto_import']) ? 1 : 0;
        
        if (!$serviceId) {
          $errors[] = 'Geçersiz test';
        } elseif (!$localCode) {
          $errors[] = 'Lokal test kodu gerekli';
        } else {
          $stmt = $pdo->prepare('
            INSERT INTO external_lab_service_mappings 
            (external_lab_service_id, local_test_code, local_test_name, auto_import)
            VALUES (:sid, :code, :name, :auto)
            ON DUPLICATE KEY UPDATE 
            local_test_code=VALUES(local_test_code),
            local_test_name=VALUES(local_test_name),
            auto_import=VALUES(auto_import),
            updated_at=CURRENT_TIMESTAMP
          ');
          $stmt->execute([
            ':sid' => $serviceId,
            ':code' => $localCode,
            ':name' => $localName,
            ':auto' => $autoImport
          ]);
          $info = 'Eşleştirme kaydedildi';
        }
      } elseif ($action === 'delete_mapping') {
        $serviceId = (int)($_POST['service_id'] ?? 0);
        if ($serviceId) {
          $pdo->prepare('DELETE FROM external_lab_service_mappings WHERE external_lab_service_id=:sid')->execute([':sid' => $serviceId]);
          $info = 'Eşleştirme silindi';
        }
      } elseif ($action === 'save_to_local') {
        // Save external lab service directly to local_test_definitions
        $serviceId = (int)($_POST['service_id'] ?? 0);
        $externalCode = trim($_POST['service_code'] ?? '');
        $externalName = trim($_POST['service_name'] ?? '');
        $category = trim($_POST['category'] ?? 'Dışlab');
        $refMin = trim($_POST['reference_min'] ?? '');
        $refMax = trim($_POST['reference_max'] ?? '');
        $unit = trim($_POST['unit'] ?? '');
        
        if (!$serviceId || !$externalCode || !$externalName) {
          $errors[] = 'Gerekli alanlar eksik';
        } else {
          // Check if code already exists
          $check = $pdo->prepare('SELECT id FROM local_test_definitions WHERE code=:code');
          $check->execute([':code' => $externalCode]);
          
          if ($check->rowCount() > 0) {
            $errors[] = "'{$externalCode}' kodu zaten lokal testlerde mevcut";
          } else {
            try {
              $stmt = $pdo->prepare('
                INSERT INTO local_test_definitions 
                (code, name, category, min_ref, max_ref, unit, is_active)
                VALUES (:code, :name, :cat, :ref_min, :ref_max, :unit, 1)
              ');
              $stmt->execute([
                ':code' => $externalCode,
                ':name' => $externalName,
                ':cat' => $category,
                ':ref_min' => $refMin ?: null,
                ':ref_max' => $refMax ?: null,
                ':unit' => $unit ?: null,
              ]);
              
              $localTestId = $pdo->lastInsertId();
              
              // Create mapping
              $mapStmt = $pdo->prepare('
                INSERT INTO external_lab_service_mappings 
                (external_lab_service_id, local_test_code, local_test_name, auto_import)
                VALUES (:sid, :code, :name, 1)
                ON DUPLICATE KEY UPDATE 
                local_test_code=VALUES(local_test_code),
                local_test_name=VALUES(local_test_name),
                auto_import=VALUES(auto_import),
                updated_at=CURRENT_TIMESTAMP
              ');
              $mapStmt->execute([
                ':sid' => $serviceId,
                ':code' => $externalCode,
                ':name' => $externalName,
              ]);
              
              $info = "Test lokal veritabanına kaydedildi: <code>{$externalCode}</code>";
            } catch (\Throwable $e) {
              $errors[] = 'Lokal kayıt başarısız: ' . $e->getMessage();
            }
          }
        }
      }
    } catch (\Throwable $e) {
      $errors[] = 'İşlem başarısız: ' . $e->getMessage();
    }
  }
}

$csrf = App\Csrf::token();

// AJAX endpoint for test search
if (isset($_GET['action']) && $_GET['action'] === 'search_tests') {
  header('Content-Type: application/json');
  $q = trim($_GET['q'] ?? '');
  if (strlen($q) < 2) {
    echo json_encode([]);
    exit;
  }
  // Search in local test definitions
  $stmt = $pdo->prepare('
    SELECT code, name 
    FROM local_test_definitions 
    WHERE (code LIKE :q OR name LIKE :q) 
    AND is_active = 1
    ORDER BY code
    LIMIT 20
  ');
  $stmt->execute([':q' => "%{$q}%"]);
  $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
  echo json_encode($results);
  exit;
}

// Get laboratories
$labs = $pdo->query('SELECT id, name FROM external_laboratories WHERE status="active" ORDER BY name')->fetchAll();

// Get services with mappings
$selectedLab = (int)($_GET['lab_id'] ?? 0);
$search = trim($_GET['q'] ?? '');
$services = [];
if ($selectedLab) {
  $query = '
    SELECT s.*, m.local_test_code, m.local_test_name, m.auto_import
    FROM external_lab_services s
    LEFT JOIN external_lab_service_mappings m ON m.external_lab_service_id = s.id
    WHERE s.external_lab_id = :lab AND s.is_active = 1
  ';
  $params = [':lab' => $selectedLab];
  
  if ($search) {
    $query .= ' AND (s.service_name LIKE :search OR s.service_code LIKE :search)';
    $params[':search'] = "%{$search}%";
  }
  
  $query .= ' ORDER BY s.service_name';
  $stmt = $pdo->prepare($query);
  $stmt->execute($params);
  $services = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$full_width = true; // Enable full width
include __DIR__ . '/../header.php';
?>
<style>
:root {
  --primary: #2563eb;
  --primary-hover: #1d4ed8;
  --success: #059669;
  --success-light: #d1fae5;
  --danger: #dc2626;
  --danger-light: #fee2e2;
  --warning: #d97706;
  --warning-light: #fef3c7;
  --light: #f8fafc;
  --border: #e2e8f0;
  --gray-50: #f9fafb;
  --gray-100: #f3f4f6;
  --gray-200: #e5e7eb;
  --gray-600: #4b5563;
  --gray-700: #374151;
  --gray-900: #111827;
}

body { 
  background: #f8fafc;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  color: var(--gray-900);
  margin: 0;
  padding: 0;
}

.nl-container { 
  width: 100%;
  padding: 0;
  margin: 0;
}

.nl-header {
  background: linear-gradient(135deg, #1e40af 0%, #2563eb 100%);
  color: white;
  padding: 32px 48px;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
}

.nl-header-content {
  max-width: 1600px;
  margin: 0 auto;
}

.nl-title { 
  font-size: 2rem;
  font-weight: 700;
  margin: 0 0 8px 0;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
}

.nl-title i {
  font-size: 1.8rem;
}

.nl-subtitle { 
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-size: 1.05rem;
  font-weight: 400;
}

.nl-body {
  max-width: 1600px;
  margin: 0 auto;
  padding: 32px 48px;
}

.nl-card { 
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
  padding: 28px 32px;
  margin-bottom: 24px;
}

.nl-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 28px;
  flex-wrap: wrap;
}

.nl-toolbar-left {
  flex: 1;
  min-width: 300px;
}

.nl-toolbar-right {
  display: flex;
  gap: 12px;
}

.nl-btn { 
  padding: 11px 24px;
  border-radius: 8px;
  border: none;
  font-weight: 600;
  font-size: 0.95rem;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  white-space: nowrap;
}

.nl-btn:active {
  transform: translateY(1px);
}

.nl-btn-primary { 
  background: var(--primary);
  color: white;
  box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}

.nl-btn-primary:hover { 
  background: var(--primary-hover);
  box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.3);
}

.nl-btn-success { 
  background: var(--success);
  color: white;
}

.nl-btn-success:hover {
  background: #047857;
}

.btn-info {
  background: #06b6d4;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  padding: 6px 10px;
  font-size: 0.875rem;
}

.btn-info:hover {
  background: #0891b2;
}

.nl-btn-danger { 
  background: var(--danger);
  color: white;
}

.nl-btn-danger:hover {
  background: #b91c1c;
}

.nl-table-wrapper {
  overflow-x: auto;
  border-radius: 8px;
  border: 1px solid var(--border);
}

.nl-table { 
  width: 100%;
  border-collapse: collapse;
  background: white;
}

.nl-table thead th { 
  background: var(--gray-50);
  padding: 14px 16px;
  text-align: left;
  font-weight: 600;
  font-size: 0.875rem;
  color: var(--gray-700);
  text-transform: uppercase;
  letter-spacing: 0.05em;
  border-bottom: 2px solid var(--border);
  white-space: nowrap;
}

.nl-table tbody td { 
  padding: 16px;
  border-bottom: 1px solid var(--gray-100);
  font-size: 0.95rem;
  vertical-align: middle;
}

.nl-table tbody tr:last-child td {
  border-bottom: none;
}

.nl-table tbody tr:hover { 
  background: var(--gray-50);
}

.nl-badge { 
  display: inline-flex;
  align-items: center;
  padding: 5px 12px;
  border-radius: 6px;
  font-size: 0.8rem;
  font-weight: 600;
  white-space: nowrap;
}

.nl-badge-success { 
  background: var(--success-light);
  color: #065f46;
}

.nl-badge-warning { 
  background: var(--warning-light);
  color: #92400e;
}

.nl-input { 
  width: 100%;
  padding: 10px 14px;
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.95rem;
  transition: all 0.2s;
  font-family: inherit;
}

.nl-input:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.nl-select { 
  width: 100%;
  padding: 10px 14px;
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.95rem;
  background: white;
  cursor: pointer;
  transition: all 0.2s;
  font-family: inherit;
}

.nl-select:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.nl-autocomplete {
  position: relative;
}

.nl-autocomplete-results {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid var(--border);
  border-top: none;
  border-radius: 0 0 8px 8px;
  max-height: 300px;
  overflow-y: auto;
  z-index: 1000;
  box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
  display: none;
}

.nl-autocomplete-results.active {
  display: block;
}

.nl-autocomplete-item {
  padding: 10px 14px;
  cursor: pointer;
  border-bottom: 1px solid var(--gray-100);
  transition: background 0.15s;
}

.nl-autocomplete-item:hover {
  background: var(--gray-50);
}

.nl-autocomplete-item:last-child {
  border-bottom: none;
}

.nl-autocomplete-code {
  font-weight: 600;
  color: var(--gray-900);
  font-size: 0.9rem;
}

.nl-autocomplete-name {
  font-size: 0.85rem;
  color: var(--gray-600);
  margin-top: 2px;
}

.nl-form-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.btn-icon {
  padding: 8px 12px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
}

.btn-sm {
  padding: 6px 10px;
  font-size: 0.875rem;
}

.alert {
  padding: 14px 18px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-weight: 500;
}

.alert-success {
  background: var(--success-light);
  color: #065f46;
  border: 1px solid #a7f3d0;
}

.alert-danger {
  background: var(--danger-light);
  color: #991b1b;
  border: 1px solid #fecaca;
}

.alert-info {
  background: #dbeafe;
  color: #1e40af;
  border: 1px solid #bfdbfe;
  text-align: center;
}

code {
  background: var(--gray-100);
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.875em;
  font-family: 'Courier New', monospace;
  color: var(--danger);
}

/* Modal Styles */
.modal-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  align-items: center;
  justify-content: center;
}

.modal-overlay.active {
  display: flex;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 32px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  margin-bottom: 24px;
  border-bottom: 2px solid var(--border);
  padding-bottom: 16px;
}

.modal-header h3 {
  margin: 0;
  color: var(--gray-900);
  font-size: 1.5rem;
}

.modal-body {
  margin-bottom: 24px;
}

.form-group {
  margin-bottom: 18px;
}

.form-label {
  display: block;
  margin-bottom: 6px;
  font-weight: 600;
  color: var(--gray-700);
  font-size: 0.95rem;
}

.form-control {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.95rem;
  font-family: inherit;
  transition: all 0.2s;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}

.form-control:disabled {
  background: var(--gray-50);
  color: var(--gray-600);
  cursor: not-allowed;
}

.form-text {
  font-size: 0.85rem;
  color: var(--gray-600);
  margin-top: 4px;
}

.modal-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.modal-btn {
  padding: 10px 20px;
  border-radius: 8px;
  border: none;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.95rem;
}

.modal-btn-primary {
  background: var(--primary);
  color: white;
}

.modal-btn-primary:hover {
  background: var(--primary-hover);
}

.modal-btn-secondary {
  background: var(--gray-200);
  color: var(--gray-900);
}

.modal-btn-secondary:hover {
  background: var(--gray-300);
}

.test-code-display {
  background: var(--gray-50);
  padding: 12px 14px;
  border-radius: 8px;
  border: 1px solid var(--border);
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: var(--primary);
  font-size: 1.1rem;
}

@media (max-width: 1200px) {
  .nl-header, .nl-body {
    padding-left: 24px;
    padding-right: 24px;
  }
}

@media (max-width: 768px) {
  .nl-header, .nl-body {
    padding-left: 16px;
    padding-right: 16px;
  }
  
  .nl-title {
    font-size: 1.5rem;
  }
  
  .nl-toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .nl-toolbar-left, .nl-toolbar-right {
    width: 100%;
  }
  
  .nl-toolbar-right {
    justify-content: stretch;
  }
  
  .nl-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>

<div class="nl-container">
  <div class="nl-header">
    <div class="nl-header-content">
      <h1 class="nl-title"><i class="bi bi-diagram-3"></i> Dışlab Test Eşleştirme</h1>
      <p class="nl-subtitle">Dışlab testlerini çekin ve lokal testlerinizle eşleştirin</p>
    </div>
  </div>

  <div class="nl-body">
    <?php if (!empty($errors)): ?>
      <div class="alert alert-danger">
        <?php foreach ($errors as $err): ?>
          <div><?= htmlspecialchars($err) ?></div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <?php if ($info): ?>
      <div class="alert alert-success"><?= htmlspecialchars($info) ?></div>
    <?php endif; ?>

    <div class="nl-card">
      <div class="nl-toolbar">
        <div class="nl-toolbar-left">
          <form method="GET">
            <select name="lab_id" class="nl-select" onchange="this.form.submit()">
              <option value="">-- Laboratuvar Seçin --</option>
              <?php foreach ($labs as $l): ?>
                <option value="<?= $l['id'] ?>" <?= $selectedLab === (int)$l['id'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($l['name']) ?>
                </option>
              <?php endforeach; ?>
            </select>
          </form>
        </div>
        <?php if ($selectedLab): ?>
          <div class="nl-toolbar-right">
            <form method="POST">
              <input type="hidden" name="_csrf" value="<?= $csrf ?>">
              <input type="hidden" name="action" value="fetch_services">
              <input type="hidden" name="lab_id" value="<?= $selectedLab ?>">
              <button type="submit" class="nl-btn nl-btn-primary">
                <i class="bi bi-arrow-repeat"></i> Testleri Senkronize Et
              </button>
            </form>
          </div>
        <?php endif; ?>
      </div>

      <?php if ($selectedLab): ?>
        <div style="margin-bottom: 20px; display: flex; gap: 12px;">
          <form method="GET" style="flex: 1; display: flex; gap: 8px;">
            <input type="hidden" name="lab_id" value="<?= $selectedLab ?>">
            <input type="text" name="q" class="nl-input" placeholder="Test adı veya kodu ara..." value="<?= htmlspecialchars($search) ?>" style="flex: 1;">
            <button type="submit" class="nl-btn nl-btn-primary">
              <i class="bi bi-search"></i> Ara
            </button>
            <?php if ($search): ?>
              <a href="?lab_id=<?= $selectedLab ?>" class="nl-btn nl-btn-secondary">
                <i class="bi bi-x-lg"></i> Temizle
              </a>
            <?php endif; ?>
          </form>
        </div>
      <?php endif; ?>

      <?php if ($selectedLab && !empty($services)): ?>
        <div class="nl-table-wrapper">
          <?php if ($search): ?>
            <div style="margin-bottom: 12px; color: #666; font-size: 0.95rem;">
              <i class="bi bi-info-circle"></i> 
              "<?= htmlspecialchars($search) ?>" için <?php echo count($services); ?> test bulundu
            </div>
          <?php endif; ?>
          <table class="nl-table">
            <thead>
              <tr>
                <th>Test Adı</th>
                <th>Test Kodu</th>
                <th>SUT Kodu</th>
                <th>Örnek Türü</th>
                <th colspan="2">Lokal Test Eşleştirme</th>
                <th>Durum</th>
                <th>İşlem</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($services as $srv): ?>
                <tr>
                  <td><strong><?= htmlspecialchars($srv['service_name']) ?></strong></td>
                  <td><code><?= htmlspecialchars($srv['service_code']) ?></code></td>
                  <td><?= htmlspecialchars($srv['sut_code'] ?: '-') ?></td>
                  <td><?= htmlspecialchars($srv['sample_type_name'] ?: '-') ?></td>
                  <td colspan="2">
                    <form method="POST" class="nl-form-group" id="form-<?= $srv['id'] ?>">
                      <input type="hidden" name="_csrf" value="<?= $csrf ?>">
                      <input type="hidden" name="action" value="save_mapping">
                      <input type="hidden" name="service_id" value="<?= $srv['id'] ?>">
                      <input type="hidden" name="local_test_code" id="code-<?= $srv['id'] ?>" value="<?= htmlspecialchars($srv['local_test_code'] ?? '') ?>">
                      <input type="hidden" name="local_test_name" id="name-<?= $srv['id'] ?>" value="<?= htmlspecialchars($srv['local_test_name'] ?? '') ?>">
                      
                      <div class="nl-autocomplete">
                        <input type="text" 
                               class="nl-input nl-test-search" 
                               placeholder="Lokal test ara veya yaz..." 
                               value="<?= htmlspecialchars($srv['local_test_code'] ? $srv['local_test_code'] . ' - ' . $srv['local_test_name'] : '') ?>" 
                               data-service-id="<?= $srv['id'] ?>"
                               style="min-width:350px;">
                        <div class="nl-autocomplete-results" id="results-<?= $srv['id'] ?>"></div>
                      </div>
                    </form>
                  </td>
                  <td>
                    <?php if ($srv['local_test_code']): ?>
                      <span class="nl-badge nl-badge-success"><i class="bi bi-check-circle me-1"></i> Eşleşti</span>
                    <?php else: ?>
                      <span class="nl-badge nl-badge-warning"><i class="bi bi-clock me-1"></i> Bekliyor</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <div style="display:flex; gap:6px; flex-wrap:wrap;">
                      <button type="button" class="btn btn-success btn-sm btn-icon" onclick="document.getElementById('form-<?= $srv['id'] ?>').submit()" title="Eşleştir">
                        <i class="bi bi-check-lg"></i>
                      </button>
                      <button type="button" class="btn btn-info btn-sm btn-icon" onclick="saveToLocal(<?= $srv['id'] ?>, '<?= htmlspecialchars(addslashes($srv['service_code'])) ?>', '<?= htmlspecialchars(addslashes($srv['service_name'])) ?>')" title="Lokale Kaydet">
                        <i class="bi bi-download"></i>
                      </button>
                      <?php if ($srv['local_test_code']): ?>
                        <form method="POST" style="display:inline;" onsubmit="return confirm('Eşleştirmeyi silmek istediğinizden emin misiniz?')">
                          <input type="hidden" name="_csrf" value="<?= $csrf ?>">
                          <input type="hidden" name="action" value="delete_mapping">
                          <input type="hidden" name="service_id" value="<?= $srv['id'] ?>">
                          <button type="submit" class="btn btn-danger btn-sm btn-icon" title="Sil">
                            <i class="bi bi-trash"></i>
                          </button>
                        </form>
                      <?php endif; ?>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php elseif ($selectedLab): ?>
        <div class="alert alert-info">
          <i class="bi bi-info-circle me-2"></i>
          <?php if ($search): ?>
            "<?= htmlspecialchars($search) ?>" için test bulunamadı
          <?php else: ?>
            Bu laboratuvar için henüz test bulunmuyor. "Testleri Senkronize Et" butonuna tıklayın.
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
const searchInputs = document.querySelectorAll('.nl-test-search');
let searchTimeout = null;

searchInputs.forEach(input => {
  const serviceId = input.dataset.serviceId;
  const resultsDiv = document.getElementById(`results-${serviceId}`);
  const codeInput = document.getElementById(`code-${serviceId}`);
  const nameInput = document.getElementById(`name-${serviceId}`);
  
  input.addEventListener('input', function() {
    const query = this.value.trim();
    
    clearTimeout(searchTimeout);
    
    if (query.length < 2) {
      resultsDiv.classList.remove('active');
      return;
    }
    
    searchTimeout = setTimeout(() => {
      fetch(`?action=search_tests&q=${encodeURIComponent(query)}`)
        .then(r => r.json())
        .then(data => {
          if (data.length === 0) {
            resultsDiv.innerHTML = '<div class="nl-autocomplete-item" style="color:#94a3b8;">Sonuç bulunamadı</div>';
            resultsDiv.classList.add('active');
            return;
          }
          
          resultsDiv.innerHTML = data.map(item => `
            <div class="nl-autocomplete-item" data-code="${item.code}" data-name="${item.name}">
              <div class="nl-autocomplete-code">${item.code}</div>
              <div class="nl-autocomplete-name">${item.name}</div>
            </div>
          `).join('');
          
          resultsDiv.classList.add('active');
          
          // Add click handlers
          resultsDiv.querySelectorAll('.nl-autocomplete-item[data-code]').forEach(item => {
            item.addEventListener('click', function() {
              const code = this.dataset.code;
              const name = this.dataset.name;
              input.value = `${code} - ${name}`;
              codeInput.value = code;
              nameInput.value = name;
              resultsDiv.classList.remove('active');
            });
          });
        })
        .catch(err => {
          console.error('Search error:', err);
          resultsDiv.classList.remove('active');
        });
    }, 300);
  });
  
  // Close results when clicking outside
  document.addEventListener('click', function(e) {
    if (!input.contains(e.target) && !resultsDiv.contains(e.target)) {
      resultsDiv.classList.remove('active');
    }
  });
  
  // Allow manual entry
  input.addEventListener('blur', function() {
    setTimeout(() => {
      const val = this.value.trim();
      if (val && !codeInput.value) {
        // User typed manually without selecting
        const parts = val.split(' - ');
        if (parts.length >= 2) {
          codeInput.value = parts[0].trim();
          nameInput.value = parts.slice(1).join(' - ').trim();
        } else {
          codeInput.value = val;
          nameInput.value = val;
        }
      }
    }, 200);
  });
});

// Function to save external service directly to local test definitions
function saveToLocal(serviceId, serviceCode, serviceName) {
  // Open modal with test details
  document.getElementById('modalTestCode').textContent = serviceCode;
  document.getElementById('modalTestName').value = serviceName;
  document.getElementById('modalTestCategory').value = 'Dışlab';
  
  // Store data in global variables for form submission
  window.pendingServiceId = serviceId;
  window.pendingServiceCode = serviceCode;
  window.pendingServiceName = serviceName;
  
  // Show modal
  document.getElementById('saveTestModal').classList.add('active');
}

function closeTestModal() {
  document.getElementById('saveTestModal').classList.remove('active');
  window.pendingServiceId = null;
  window.pendingServiceCode = null;
  window.pendingServiceName = null;
}

function submitSaveTest() {
  const serviceId = window.pendingServiceId;
  const serviceCode = window.pendingServiceCode;
  const serviceName = window.pendingServiceName;
  const category = document.getElementById('modalTestCategory').value.trim();
  
  if (!serviceId || !serviceCode || !serviceName) {
    alert('Gerekli bilgiler eksik');
    return;
  }
  
  if (!category) {
    alert('Kategori belirtiniz');
    return;
  }
  
  // Create and submit form
  const form = document.createElement('form');
  form.method = 'POST';
  form.innerHTML = `
    <input type="hidden" name="_csrf" value="<?= $csrf ?>">
    <input type="hidden" name="action" value="save_to_local">
    <input type="hidden" name="service_id" value="${serviceId}">
    <input type="hidden" name="service_code" value="${serviceCode}">
    <input type="hidden" name="service_name" value="${serviceName}">
    <input type="hidden" name="category" value="${category}">
  `;
  document.body.appendChild(form);
  form.submit();
}

// Close modal when clicking outside
document.getElementById('saveTestModal')?.addEventListener('click', function(e) {
  if (e.target === this) {
    closeTestModal();
  }
});
</script>

<!-- Modal for saving test to local -->
<div class="modal-overlay" id="saveTestModal">
  <div class="modal-content">
    <div class="modal-header">
      <h3><i class="bi bi-download"></i> Test Lokal Veritabanına Kaydet</h3>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label class="form-label">Test Kodu <span style="color: #dc2626;">*</span></label>
        <div class="test-code-display" id="modalTestCode">-</div>
        <div class="form-text">Dışlab tarafından atanan kod (değiştirilemez)</div>
      </div>
      
      <div class="form-group">
        <label class="form-label">Test Adı <span style="color: #dc2626;">*</span></label>
        <input type="text" class="form-control" id="modalTestName" disabled>
        <div class="form-text">Dışlab tarafından tanımlanan ad (değiştirilemez)</div>
      </div>
      
      <div class="form-group">
        <label class="form-label">Kategori</label>
        <input type="text" class="form-control" id="modalTestCategory" value="Dışlab">
        <div class="form-text">Test kategorisini belirtiniz (ör. Biyokimya, Hematoloji vb.)</div>
      </div>
    </div>
    <div class="modal-footer">
      <button type="button" class="modal-btn modal-btn-secondary" onclick="closeTestModal()">İptal</button>
      <button type="button" class="modal-btn modal-btn-primary" onclick="submitSaveTest()">Lokale Kaydet</button>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../footer.php'; ?>
