<?php
require_once __DIR__ . '/../../vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..' . '/../');
$dotenv->safeLoad();
require_once __DIR__ . '/../i18n.php';

use App\Auth;
use App\Database;

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

$full_width = true;

// AJAX: Test paketi detayını getir
if (isset($_GET['action']) && $_GET['action'] === 'get_package_tests') {
  header('Content-Type: application/json');
  $packageId = (int)($_GET['package_id'] ?? 0);
  
  if ($packageId <= 0) {
    echo json_encode(['error' => 'Geçersiz paket']);
    exit;
  }
  
  $stmt = $pdo->prepare('
    SELECT test_code, test_name 
    FROM test_package_items 
    WHERE package_id = :pid
    ORDER BY sort_order, test_name
  ');
  $stmt->execute([':pid' => $packageId]);
  $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
  echo json_encode($tests);
  exit;
}

// Aktif hastaları getir
$activePatients = $pdo->query('
  SELECT p.id, p.first_name, p.last_name, p.national_id, p.phone, p.birth_date, p.gender,
         r.referral_reason, i.name as institution_name
  FROM patients p
  LEFT JOIN patient_referrals r ON r.patient_id = p.id
  LEFT JOIN institutions i ON i.id = r.institution_id
  ORDER BY p.first_name, p.last_name
  LIMIT 100
')->fetchAll(PDO::FETCH_ASSOC);

// Test paketlerini getir
$packages = $pdo->query('
  SELECT id, name, description, package_type
  FROM test_packages
  WHERE is_active = 1
  ORDER BY name
')->fetchAll(PDO::FETCH_ASSOC);

// Manuel test listesi
$manualTests = $pdo->query('
  SELECT code, name, category
  FROM local_test_definitions
  WHERE is_active = 1
  ORDER BY category, name
')->fetchAll(PDO::FETCH_ASSOC);

// Gönderilen kayıtlar
$sentRecords = $pdo->query('
  SELECT dr.id, dr.patient_id, dr.first_name, dr.last_name, dr.referans_id, 
         dr.gelis_tarihi, dr.status, dr.created_at, dr.response_xml,
         COUNT(drt.id) as test_count
  FROM dislab_records dr
  LEFT JOIN dislab_records_tests drt ON drt.record_id = dr.id
  GROUP BY dr.id
  ORDER BY dr.created_at DESC
  LIMIT 50
')->fetchAll(PDO::FETCH_ASSOC);

include __DIR__ . '/../header.php';
?>
<style>
:root {
  --primary: #3b82f6;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --info: #06b6d4;
  --gray-50: #f9fafb;
  --gray-100: #f3f4f6;
  --gray-700: #374151;
  --gray-900: #111827;
}

.dislab-grid {
  display: grid;
  grid-template-columns: 350px 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.dislab-panel {
  background: white;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  display: flex;
  flex-direction: column;
  max-height: 600px;
}

.panel-header {
  padding: 16px 20px;
  border-bottom: 2px solid #f3f4f6;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.panel-header .badge-count {
  background: rgba(255,255,255,0.3);
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 13px;
}

.panel-body {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

/* Hasta Listesi */
.patient-list-item {
  padding: 12px;
  margin-bottom: 8px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 12px;
  background: white;
}

.patient-list-item:hover {
  background: #f0f9ff;
  border-color: var(--primary);
  transform: translateX(2px);
}

.patient-list-item.selected {
  background: #dbeafe;
  border-color: var(--primary);
  border-width: 2px;
}

.patient-checkbox {
  width: 20px;
  height: 20px;
  cursor: pointer;
  flex-shrink: 0;
}

.patient-info {
  flex: 1;
}

.patient-name {
  font-weight: 600;
  color: var(--gray-900);
  margin-bottom: 2px;
}

.patient-meta {
  font-size: 12px;
  color: #666;
}

/* Test Paketleri */
.package-selector {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
  margin-bottom: 20px;
}

.package-card {
  padding: 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
}

.package-card:hover {
  border-color: var(--primary);
  background: #f0f9ff;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.package-card.active {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-color: #667eea;
  color: white;
}

.package-card i {
  font-size: 24px;
  display: block;
  margin-bottom: 8px;
}

.package-card .name {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.package-card .desc {
  font-size: 11px;
  opacity: 0.8;
}

.test-search-input {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 12px;
}

.test-search-input:focus {
  outline: none;
  border-color: var(--primary);
}

.test-list {
  max-height: 400px;
  overflow-y: auto;
}

.test-list-item {
  padding: 10px 12px;
  margin-bottom: 6px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 10px;
  background: white;
}

.test-list-item:hover {
  background: #fef3c7;
  border-color: var(--warning);
  transform: translateX(2px);
}

.test-list-item.selected {
  background: #fef3c7;
  border-color: var(--warning);
  border-width: 2px;
}

.test-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  flex-shrink: 0;
}

.test-item-info {
  flex: 1;
}

.test-item-name {
  font-weight: 600;
  color: var(--gray-900);
  font-size: 13px;
}

.test-item-code {
  font-size: 11px;
  color: #666;
  font-family: monospace;
}

.test-category-header {
  padding: 8px 12px;
  background: #f3f4f6;
  font-weight: 600;
  color: var(--gray-700);
  font-size: 12px;
  margin-bottom: 6px;
  border-radius: 4px;
  position: sticky;
  top: 0;
  z-index: 1;
}

.selected-test-tag {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 12px 16px;
  border-radius: 24px;
  font-size: 14px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.selected-test-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.selected-test-tag .test-name {
  font-weight: 700;
  letter-spacing: 0.3px;
}

.selected-test-tag .test-code {
  opacity: 0.9;
  font-size: 12px;
  font-weight: 700;
  padding: 2px 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-family: 'Courier New', monospace;
}

.selected-test-tag .remove-btn {
  background: rgba(255, 255, 255, 0.25);
  border: none;
  color: white;
  cursor: pointer;
  padding: 6px 8px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  transition: all 0.2s;
  margin-left: 4px;
}

.selected-test-tag .remove-btn:hover {
  background: rgba(255, 255, 255, 0.45);
  transform: rotate(90deg);
}

/* Önizleme Paneli */
.preview-summary {
  padding: 16px;
  background: #f9fafb;
  border-radius: 8px;
  margin-bottom: 16px;
}

.preview-stat {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e5e7eb;
}

.preview-stat:last-child {
  border-bottom: none;
}

.preview-stat .label {
  color: #666;
  font-size: 13px;
}

.preview-stat .value {
  font-weight: 600;
  color: var(--gray-900);
}

.preview-items {
  max-height: 300px;
  overflow-y: auto;
}

.preview-patient {
  padding: 12px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  margin-bottom: 8px;
}

.preview-patient-name {
  font-weight: 600;
  color: var(--gray-900);
  margin-bottom: 6px;
}

.preview-tests {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.test-badge {
  display: inline-block;
  padding: 3px 8px;
  background: #e0e7ff;
  color: #4338ca;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
}

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

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

.form-control {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  font-size: 14px;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary);
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
  width: 100%;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 4px 6px rgba(102, 126, 234, 0.3);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(102, 126, 234, 0.4);
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
}

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

.btn-secondary {
  background: var(--gray-100);
  color: var(--gray-900);
  border: 2px solid #e5e7eb;
}

.records-table {
  width: 100%;
  border-collapse: collapse;
}

.records-table th {
  padding: 12px;
  background: #f9fafb;
  text-align: left;
  font-weight: 600;
  color: var(--gray-700);
  font-size: 13px;
  border-bottom: 2px solid #e5e7eb;
}

.records-table td {
  padding: 12px;
  border-bottom: 1px solid #f3f4f6;
  font-size: 13px;
}

.records-table tbody tr:hover {
  background: #f9fafb;
}

.badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 11px;
  font-weight: 600;
}

.badge-sent {
  background: #d1fae5;
  color: #065f46;
}

.badge-pending {
  background: #fef3c7;
  color: #92400e;
}

.badge-error {
  background: #fee2e2;
  color: #991b1b;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 12px;
  display: block;
}

/* Modal */
.modal {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.6);
  z-index: 9999;
  overflow: auto;
  padding: 20px;
  align-items: center;
  justify-content: center;
}

.modal-content {
  background: white;
  margin: 0;
  padding: 0;
  border-radius: 12px;
  max-width: 900px;
  width: 90%;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3);
}

.modal-tabs {
  display: flex;
  border-bottom: 2px solid #e5e7eb;
  background: #f9fafb;
  padding: 0;
  margin: 0;
}

.modal-tab {
  flex: 1;
  padding: 14px 20px;
  border: none;
  background: transparent;
  cursor: pointer;
  font-weight: 600;
  font-size: 0.95rem;
  color: #666;
  transition: all 0.2s;
  border-bottom: 3px solid transparent;
  margin-bottom: -2px;
}

.modal-tab:hover {
  background: #f3f4f6;
  color: #333;
}

.modal-tab.active {
  color: #0ea5e9;
  border-bottom-color: #0ea5e9;
}

.modal-tab-content {
  display: none;
  flex: 1;
  overflow: auto;
}

.modal-tab-content.active {
  display: block;
}

.modal-header {
  padding: 20px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px 12px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 20px;
}

.modal-close {
  background: rgba(255,255,255,0.2);
  border: none;
  color: white;
  font-size: 24px;
  cursor: pointer;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 16px;
  overflow-y: auto;
  background: #1e1e1e;
  color: #d4d4d4;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 1.5;
  flex: 1;
}

.modal-footer {
  padding: 16px 24px;
  background: #f9fafb;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  border-radius: 0 0 12px 12px;
}

.confirm-item {
  padding: 12px;
  background: #f0f9ff;
  border-left: 4px solid var(--primary);
  margin-bottom: 12px;
  border-radius: 4px;
}

.confirm-item-header {
  font-weight: 600;
  color: var(--gray-900);
  margin-bottom: 6px;
}

.confirm-item-tests {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

@media (max-width: 1400px) {
  .dislab-grid {
    grid-template-columns: 1fr;
  }
  
  .dislab-panel {
    max-height: 400px;
  }
}
</style>

<div style="max-width: 1800px; margin: 0 auto; padding: 24px 20px;">
  <div style="margin-bottom: 32px;">
    <h1 style="margin: 0 0 8px 0; font-size: 28px; font-weight: 700; color: var(--gray-900);">
      <i class="bi bi-send-fill"></i> Toplu Dışlab Gönderimi
    </h1>
    <p style="margin: 0; color: #666; font-size: 14px;">
      Birden fazla hastayı seçin, test paketi belirleyin ve dışlab sistemine gönderin
    </p>
  </div>

  <div class="dislab-grid">
    <!-- Sol: Hasta Listesi -->
    <div class="dislab-panel">
      <div class="panel-header">
        <h3>
          <i class="bi bi-people-fill"></i> 
          Tüm Hastalar 
          <span class="badge-count" id="selectedCount">0 Seçili</span>
        </h3>
      </div>
      <div class="panel-body">
        <?php if (empty($activePatients)): ?>
          <div class="empty-state">
            <i class="bi bi-inbox"></i>
            <p>Aktif hasta bulunamadı</p>
          </div>
        <?php else: ?>
          <div style="margin-bottom: 16px;">
            <input type="text" id="patientSearchInput" class="form-control" placeholder="Hasta adı veya TC ile ara..." style="width: 100%; padding: 12px 16px; font-size: 14px; margin-bottom: 12px; border: 2px solid #e5e7eb; border-radius: 8px;">
            <button type="button" onclick="selectAllPatients()" class="btn btn-secondary" style="width: 100%; padding: 12px 16px; font-size: 13px; font-weight: 600; border-radius: 8px;">
              <i class="bi bi-check2-all"></i> Tüm Hastaları Seç
            </button>
          </div>
          <?php foreach ($activePatients as $patient): ?>
            <div class="patient-list-item" data-patient-id="<?= $patient['id'] ?>" onclick="togglePatient(this)">
              <input type="checkbox" class="patient-checkbox" data-patient='<?= json_encode($patient) ?>'>
              <div class="patient-info">
                <div class="patient-name"><?= htmlspecialchars($patient['first_name'] . ' ' . $patient['last_name']) ?></div>
                <div class="patient-meta">
                  <?= $patient['national_id'] ? 'TC: ' . htmlspecialchars($patient['national_id']) : '' ?>
                  <?= $patient['phone'] ? ' | ' . htmlspecialchars($patient['phone']) : '' ?>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>

    <!-- Sağ: Test Paketi Seçimi -->
    <div class="dislab-panel">
      <div class="panel-header">
        <h3><i class="bi bi-box-seam-fill"></i> Test Paketi veya Manuel Seçim</h3>
      </div>
      <div class="panel-body">
        <div class="package-selector">
          <?php foreach ($packages as $pkg): ?>
            <div class="package-card" data-package-id="<?= $pkg['id'] ?>" onclick="selectPackage(this, <?= $pkg['id'] ?>)">
              <i class="bi bi-clipboard-data-fill"></i>
              <div class="name"><?= htmlspecialchars($pkg['name']) ?></div>
              <div class="desc"><?= htmlspecialchars($pkg['description']) ?></div>
            </div>
          <?php endforeach; ?>
        </div>

        <div style="margin-top: 20px; padding-top: 20px; border-top: 2px solid #e5e7eb;">
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
            <label style="font-weight: 600; margin: 0;">
              <i class="bi bi-pencil-fill"></i> Veya Manuel Test Seçimi
            </label>
            <button type="button" onclick="selectAllTests()" class="btn btn-secondary" style="padding: 6px 12px; font-size: 11px; width: auto;">
              <i class="bi bi-check-all"></i> Tümünü Seç
            </button>
          </div>
          <input type="text" id="testSearchInput" class="test-search-input" placeholder="Test adı veya kodu ile ara...">
          <div id="testList" class="test-list">
            <?php 
              $grouped = [];
              foreach ($manualTests as $test) {
                $cat = $test['category'] ?: 'Diğer';
                if (!isset($grouped[$cat])) $grouped[$cat] = [];
                $grouped[$cat][] = $test;
              }
              foreach ($grouped as $category => $tests): 
            ?>
              <div class="test-category-header" data-category="<?= htmlspecialchars($category) ?>">
                <?= htmlspecialchars($category) ?>
              </div>
              <?php foreach ($tests as $test): ?>
                <div class="test-list-item" data-test-code="<?= htmlspecialchars($test['code']) ?>" data-test-name="<?= htmlspecialchars($test['name']) ?>" data-category="<?= htmlspecialchars($category) ?>" onclick="toggleTest(this)">
                  <input type="checkbox" class="test-checkbox" data-test='<?= json_encode(['code' => $test['code'], 'name' => $test['name']]) ?>'>
                  <div class="test-item-info">
                    <div class="test-item-name"><?= htmlspecialchars($test['name']) ?></div>
                    <div class="test-item-code"><?= htmlspecialchars($test['code']) ?></div>
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endforeach; ?>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Seçilen Testler Paneli -->
  <div id="selectedTestsPanel" style="background: white; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 24px; margin-bottom: 30px; display: none;">
    <h3 style="margin: 0 0 16px 0; font-size: 16px; font-weight: 600;">
      <i class="bi bi-check2-circle"></i> Seçilen Testler
    </h3>
    <div id="selectedTestsList" style="display: flex; flex-wrap: wrap; gap: 12px; padding: 16px; background: #f9fafb; border-radius: 8px;">
      <!-- JavaScript tarafından doldurulacak -->
    </div>
  </div>

  <!-- Önizleme ve Gönderim -->
  <div style="background: white; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 24px; margin-bottom: 30px;">
    <h3 style="margin: 0 0 20px 0; font-size: 18px; font-weight: 600;">
      <i class="bi bi-eye-fill"></i> Önizleme & Gönderim Ayarları
    </h3>
    
    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 20px;">
      <div class="preview-summary" style="margin-bottom: 0;">
        <div class="preview-stat">
          <span class="label">Seçili Hasta:</span>
          <span class="value" id="previewPatientCount">0</span>
        </div>
      </div>
      <div class="preview-summary" style="margin-bottom: 0;">
        <div class="preview-stat">
          <span class="label">Seçili Test:</span>
          <span class="value" id="previewTestCount">0</span>
        </div>
      </div>
      <div class="preview-summary" style="margin-bottom: 0;">
        <div class="preview-stat">
          <span class="label">Toplam İşlem:</span>
          <span class="value" id="previewTotalCount">0</span>
        </div>
      </div>
      <div class="preview-summary" style="margin-bottom: 0; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
        <div class="preview-stat" style="border-color: rgba(255,255,255,0.2);">
          <span class="label" style="color: rgba(255,255,255,0.9);">Durum:</span>
          <span class="value" style="color: white;">Hazır</span>
        </div>
      </div>
    </div>

    <div style="display: grid; grid-template-columns: 1fr 1fr auto; gap: 20px; align-items: end;">
      <div class="form-group" style="margin-bottom: 0;">
        <label>Gönderim Tarihi</label>
        <input type="datetime-local" id="gelisTarihi" class="form-control">
      </div>

      <div class="form-group" style="margin-bottom: 0;">
        <label>Geliş Tipi</label>
        <select id="gelisTipi" class="form-control" onchange="onGelisTipiChange()">
          <option value="DiyalizGiris">Diyaliz Giriş</option>
          <option value="DiyalizCikis">Diyaliz Çıkış</option>
          <option value="KontrolTetkisi">Kontrol Tetkisi</option>
          <option value="DigerTetkiler">Diğer Tetkiler</option>
        </select>
      </div>

      <button type="button" class="btn btn-primary" id="btnPreview" onclick="showConfirmModal()" disabled style="width: auto; padding: 12px 40px;">
        <i class="bi bi-eye-fill"></i> Önizleme & Onayla
      </button>
    </div>
  </div>

  <!-- Gönderilen Kayıtlar -->
  <div style="background: white; border-radius: 12px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); padding: 24px; margin-top: 30px;">
    <h3 style="margin: 0 0 20px 0; font-size: 18px; font-weight: 600;">
      <i class="bi bi-table"></i> Son Gönderilen Kaydlar
    </h3>
    <?php if (empty($sentRecords)): ?>
      <div class="empty-state">
        <i class="bi bi-inbox"></i>
        <p>Henüz kayıt gönderilmemiş</p>
      </div>
    <?php else: ?>
      <table class="records-table">
        <thead>
          <tr>
            <th>Hasta Adı</th>
            <th>Referans ID</th>
            <th>Gönderim Tarihi</th>
            <th>Test Sayısı</th>
            <th>Durum</th>
            <th style="width: 140px;">İşlemler</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($sentRecords as $rec): ?>
            <tr>
              <td><strong><?= htmlspecialchars($rec['first_name'] . ' ' . $rec['last_name']) ?></strong></td>
              <td><code><?= htmlspecialchars($rec['referans_id'] ?? '-') ?></code></td>
              <td><?= date('d.m.Y H:i', strtotime($rec['created_at'])) ?></td>
              <td><span class="badge" style="background:#dbeafe;color:#1e40af;"><?= (int)$rec['test_count'] ?></span></td>
              <td>
                <?php 
                  $statusClass = $rec['status'] === 'sent' ? 'badge-sent' : ($rec['status'] === 'error' ? 'badge-error' : 'badge-pending');
                  $statusText = $rec['status'] === 'sent' ? 'Gönderildi' : ($rec['status'] === 'error' ? 'Hata' : 'Bekliyor');
                ?>
                <span class="badge <?= $statusClass ?>"><?= $statusText ?></span>
              </td>
              <td style="display: flex; gap: 6px;">
                <?php if ($rec['response_xml']): ?>
                  <button class="btn btn-sm btn-info" onclick="showXmlModal(<?= htmlspecialchars(json_encode(['record_id' => $rec['id'], 'response_xml' => $rec['response_xml']])) ?>)" style="padding: 6px 12px; font-size: 12px; flex: 1; background: #0ea5e9; color: white; border: none; border-radius: 6px; cursor: pointer;" title="SOAP XML göster">
                    <i class="bi bi-code"></i>
                  </button>
                <?php endif; ?>
                <?php if ($rec['referans_id']): ?>
                  <button class="btn btn-sm btn-success" onclick="showQueryResults('<?= htmlspecialchars($rec['referans_id']) ?>', '<?= htmlspecialchars($rec['first_name'] . ' ' . $rec['last_name']) ?>')" style="padding: 6px 12px; font-size: 12px; flex: 1; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer;" title="Sonuç sorgula">
                    <i class="bi bi-search"></i>
                  </button>
                <?php else: ?>
                  <span style="color: #999; font-size: 12px;">-</span>
                <?php endif; ?>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

<!-- XML Modal with Tabs -->
<div id="xmlModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h2><i class="bi bi-code"></i> SOAP XML Verisi</h2>
      <button class="modal-close" onclick="closeXmlModal()">&times;</button>
    </div>
    
    <div class="modal-tabs">
      <button class="modal-tab active" onclick="switchXmlTab('response')"><i class="bi bi-arrow-down-left"></i> Gelen (Response)</button>
      <button class="modal-tab" onclick="switchXmlTab('request')"><i class="bi bi-arrow-up-right"></i> Giden (Request)</button>
    </div>
    
    <div id="responseTab" class="modal-tab-content active">
      <div class="modal-body" id="xmlModalBody">
        <!-- Response XML buraya gelecek -->
      </div>
    </div>
    
    <div id="requestTab" class="modal-tab-content">
      <div class="modal-body" id="xmlModalBodyRequest">
        <!-- Request XML buraya gelecek -->
      </div>
    </div>
    
    <div class="modal-footer" style="padding: 12px 24px; border-top: 1px solid #e5e7eb; background: #f9fafb; display: flex; justify-content: flex-end; gap: 8px;">
      <button class="btn btn-secondary" onclick="closeXmlModal()" style="padding: 8px 16px;">Kapat</button>
      <button class="btn btn-primary" onclick="copyXmlToClipboard()" style="padding: 8px 16px; background: #0ea5e9; color: white; border: none; border-radius: 6px; cursor: pointer;">
        <i class="bi bi-clipboard"></i> Kopyala
      </button>
    </div>
  </div>
</div>

<!-- Sonuç Modal -->
<div id="queryResultsModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h2><i class="bi bi-search"></i> Test Sonuçları</h2>
      <button class="modal-close" onclick="closeQueryResultsModal()">&times;</button>
    </div>
    
    <div class="modal-body" id="queryResultsBody" style="padding: 0; overflow-y: auto; flex: 1;">
      <div style="padding: 16px; text-align: center;">
        <i class="bi bi-hourglass-split" style="font-size: 2rem; color: #0ea5e9;"></i>
        <p style="color: #666; margin-top: 12px;">Sonuçlar sorgulanıyor...</p>
      </div>
    </div>
    
    <div class="modal-footer" style="padding: 12px 24px; border-top: 1px solid #e5e7eb; background: #f9fafb; display: flex; justify-content: flex-end;">
      <button class="btn btn-secondary" onclick="closeQueryResultsModal()" style="padding: 8px 16px;">Kapat</button>
    </div>
  </div>
</div>

<!-- Onay Modalı -->
<div id="confirmModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h2><i class="bi bi-check-circle-fill"></i> Gönderim Onayı</h2>
      <button class="modal-close" onclick="closeConfirmModal()">&times;</button>
    </div>
    <div class="modal-body" id="confirmModalBody">
      <!-- Dinamik içerik buraya gelecek -->
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" onclick="closeConfirmModal()" style="width: auto;">
        <i class="bi bi-x-lg"></i> İptal
      </button>
      <button type="button" class="btn btn-success" onclick="confirmSend()" style="width: auto;">
        <i class="bi bi-send-fill"></i> Onayla & Gönder
      </button>
    </div>
  </div>
</div>

<script>
let selectedPatients = [];
let selectedTests = [];
let selectedPackageId = null;

// Tarihi ayarla
const now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
document.getElementById('gelisTarihi').value = now.toISOString().slice(0, 16);

// Hasta seçimi
function togglePatient(element) {
  const checkbox = element.querySelector('.patient-checkbox');
  checkbox.checked = !checkbox.checked;
  element.classList.toggle('selected', checkbox.checked);
  
  const patientData = JSON.parse(checkbox.dataset.patient);
  
  if (checkbox.checked) {
    selectedPatients.push(patientData);
  } else {
    selectedPatients = selectedPatients.filter(p => p.id !== patientData.id);
  }
  
  updatePreview();
}

// Geliş tipine göre otomatik paket seç
function onGelisTipiChange() {
  const gelisTipi = document.getElementById('gelisTipi').value;
  let targetPackageId = null;
  
  // Geliş tipine göre paket ID'sini belirle
  const packageMapping = {
    'DiyalizGiris': 4,  // Aylık Diyaliz Giriş
    'DiyalizCikis': 5   // Aylık Diyaliz Çıkış
  };
  
  targetPackageId = packageMapping[gelisTipi];
  
  if (targetPackageId) {
    // Önce tüm paketlerin seçimini kaldır
    document.querySelectorAll('.package-card').forEach(card => {
      card.classList.remove('selected');
    });
    
    // Hedef paketi seç ve testlerini yükle
    const targetCard = document.querySelector(`.package-card[onclick*="selectPackage(this, ${targetPackageId})"]`);
    if (targetCard) {
      targetCard.classList.add('selected');
      selectPackage(targetCard, targetPackageId).then(() => {
        // Paket yüklendikten sonra önizlemeyi güncelle
        updatePreview();
      });
    }
  } else {
    // Profil değiştiğinde mevcut seçimi koruyup önizlemeyi güncelle
    updatePreview();
  }
}

function selectAllPatients() {
  const checkboxes = document.querySelectorAll('.patient-checkbox');
  const allSelected = Array.from(checkboxes).every(cb => cb.checked);
  
  selectedPatients = [];
  checkboxes.forEach(cb => {
    cb.checked = !allSelected;
    cb.closest('.patient-list-item').classList.toggle('selected', cb.checked);
    
    if (cb.checked) {
      selectedPatients.push(JSON.parse(cb.dataset.patient));
    }
  });
  
  updatePreview();
}

// Paket seçimi
async function selectPackage(element, packageId) {
  document.querySelectorAll('.package-card').forEach(el => el.classList.remove('active'));
  element.classList.add('active');
  
  selectedPackageId = packageId;
  
  try {
    const res = await fetch(`?action=get_package_tests&package_id=${packageId}`);
    
    if (!res.ok) {
      console.error('AJAX Hata:', res.status, res.statusText);
      alert('Paket yüklenemedi: ' + res.statusText);
      return;
    }
    
    const packageTests = await res.json();
    console.log('=== PAKET TESTLERI ===');
    console.log('Paket ID:', packageId);
    console.log('Tests array:', packageTests);
    console.log('Tests sayısı:', packageTests.length);
    
    if (!Array.isArray(packageTests) || packageTests.length === 0) {
      console.error('Tests boş veya array değil!');
      alert('Bu paket için test bulunamadı');
      return;
    }
    
    // Önce TÜM testlerin işaretini kaldır
    document.querySelectorAll('.test-checkbox').forEach(cb => {
      cb.checked = false;
      cb.closest('.test-list-item').classList.remove('selected');
    });
    
    // Paket testlerini bul ve işaretle
    const checkboxes = document.querySelectorAll('.test-checkbox');
    console.log('Manuel testler sayısı:', checkboxes.length);
    
    let matchCount = 0;
    checkboxes.forEach(cb => {
      try {
        const testData = JSON.parse(cb.dataset.test);
        const manualCode = (testData.code || '').trim().toUpperCase();
        
        // Paket test'inde ara - DISLAB- prefix'ini de kontrol et
        for (let pkgTest of packageTests) {
          const pkgCode = (pkgTest.test_code || '').trim().toUpperCase();
          
          // 3 şekilde match kontrol et:
          // 1. Tam eşleş: HD02 === HD02
          // 2. Prefix'li: DISLAB-HD02 === HD02
          // 3. Ters: HD02 === DISLAB-HD02
          const isMatch = (
            manualCode === pkgCode ||
            manualCode === 'DISLAB-' + pkgCode ||
            'DISLAB-' + manualCode === pkgCode
          );
          
          if (isMatch) {
            console.log('✓ MATCH:', manualCode, '→', pkgCode);
            cb.checked = true;
            cb.closest('.test-list-item').classList.add('selected');
            matchCount++;
            break;
          }
        }
      } catch(e) {
        console.error('Parse hatası:', e);
      }
    });
    
    console.log('Eşleşen testler:', matchCount);
    console.log('===================');
    
    // updateSelectedTests çağır
    updateSelectedTests();
    
  } catch(err) {
    console.error('AJAX Hata:', err);
    alert('Paket testleri yüklenemedi: ' + err.message);
  }
}

// Test seçimi
function toggleTest(element) {
  const checkbox = element.querySelector('.test-checkbox');
  checkbox.checked = !checkbox.checked;
  element.classList.toggle('selected', checkbox.checked);
  
  // Paket seçimini kaldır
  if (checkbox.checked) {
    document.querySelectorAll('.package-card').forEach(el => el.classList.remove('active'));
    selectedPackageId = null;
  }
  
  // Seçili testleri güncelle
  updateSelectedTests();
}

function selectAllTests() {
  const checkboxes = document.querySelectorAll('.test-checkbox');
  const visibleCheckboxes = Array.from(checkboxes).filter(cb => cb.closest('.test-list-item').style.display !== 'none');
  const allSelected = visibleCheckboxes.every(cb => cb.checked);
  
  visibleCheckboxes.forEach(cb => {
    cb.checked = !allSelected;
    cb.closest('.test-list-item').classList.toggle('selected', cb.checked);
  });
  
  if (visibleCheckboxes.some(cb => cb.checked)) {
    document.querySelectorAll('.package-card').forEach(el => el.classList.remove('active'));
    selectedPackageId = null;
  }
  
  updateSelectedTests();
}

function updateSelectedTests() {
  const checkboxes = document.querySelectorAll('.test-checkbox:checked');
  selectedTests = Array.from(checkboxes).map(cb => JSON.parse(cb.dataset.test));
  updatePreview();
}

function removeSelectedTest(testCode) {
  // Test checkbox'ını bul ve kaldır
  const checkbox = document.querySelector(`.test-checkbox[data-test*='"code":"${testCode}"']`);
  if (checkbox) {
    checkbox.checked = false;
    checkbox.closest('.test-list-item').classList.remove('selected');
  }
  
  // Paket seçimini kaldır
  document.querySelectorAll('.package-card').forEach(el => el.classList.remove('selected'));
  selectedPackageId = null;
  
  updateSelectedTests();
}

function removeSelectedTest(testCode) {
  // Test checkbox'ını bul ve kaldır (loop ile güvenli bulma)
  const checkboxes = document.querySelectorAll('.test-checkbox');
  checkboxes.forEach(cb => {
    try {
      const testData = JSON.parse(cb.dataset.test);
      if (testData.code === testCode) {
        cb.checked = false;
        cb.closest('.test-list-item').classList.remove('selected');
      }
    } catch(e) {
      // JSON parse hatası durumunda devam et
    }
  });
  
  // Paket seçimini kaldır
  document.querySelectorAll('.package-card').forEach(el => el.classList.remove('selected'));
  selectedPackageId = null;
  
  updateSelectedTests();
}

// Hasta arama
if (document.getElementById('patientSearchInput')) {
  document.getElementById('patientSearchInput').addEventListener('input', function() {
    const query = this.value.toLowerCase();
    const patientItems = document.querySelectorAll('.patient-list-item');
    
    patientItems.forEach(item => {
      const name = item.querySelector('.patient-name')?.textContent?.toLowerCase() || '';
      const meta = item.querySelector('.patient-meta')?.textContent?.toLowerCase() || '';
      
      if (name.includes(query) || meta.includes(query)) {
        item.style.display = '';
      } else {
        item.style.display = 'none';
      }
    });
  });
}
// Hasta arama
if (document.getElementById('patientSearchInput')) {
  document.getElementById('patientSearchInput').addEventListener('input', function() {
    const query = this.value.toLowerCase();
    const patientItems = document.querySelectorAll('.patient-list-item');
    
    patientItems.forEach(item => {
      const name = item.querySelector('.patient-name')?.textContent?.toLowerCase() || '';
      const meta = item.querySelector('.patient-meta')?.textContent?.toLowerCase() || '';
      
      if (name.includes(query) || meta.includes(query)) {
        item.style.display = '';
      } else {
        item.style.display = 'none';
      }
    });
  });
}
document.getElementById('testSearchInput').addEventListener('input', function() {
  const query = this.value.toLowerCase();
  const testItems = document.querySelectorAll('.test-list-item');
  const categories = document.querySelectorAll('.test-category-header');
  
  // Kategorileri sakla
  const categoryVisibility = {};
  
  testItems.forEach(item => {
    const name = item.dataset.testName.toLowerCase();
    const code = item.dataset.testCode.toLowerCase();
    const category = item.dataset.category;
    
    if (name.includes(query) || code.includes(query)) {
      item.style.display = '';
      categoryVisibility[category] = true;
    } else {
      item.style.display = 'none';
    }
  });
  
  // Kategorileri göster/gizle
  categories.forEach(cat => {
    const category = cat.dataset.category;
    cat.style.display = categoryVisibility[category] ? '' : 'none';
  });
});

// Önizleme güncelle
function updatePreview() {
  document.getElementById('previewPatientCount').textContent = selectedPatients.length;
  document.getElementById('previewTestCount').textContent = selectedTests.length;
  document.getElementById('previewTotalCount').textContent = selectedPatients.length * selectedTests.length;
  
  const canProceed = selectedPatients.length > 0 && selectedTests.length > 0;
  document.getElementById('btnPreview').disabled = !canProceed;
  
  // Seçilen testler panelini güncelle
  const panel = document.getElementById('selectedTestsPanel');
  const list = document.getElementById('selectedTestsList');
  
  if (selectedTests.length > 0) {
    panel.style.display = 'block';
    list.innerHTML = selectedTests.map(test => `
      <div class="selected-test-tag">
        <i class="bi bi-flask-fill" style="font-size: 16px;"></i>
        <span class="test-name">${test.name}</span>
        <span class="test-code">${test.code}</span>
        <button type="button" class="remove-btn" title="Kaldır" onclick="removeSelectedTest('${test.code}')">
          <i class="bi bi-x-lg"></i>
        </button>
      </div>
    `).join('');
  } else {
    panel.style.display = 'none';
    list.innerHTML = '';
  }
}

// Seçilen testi kaldır
function removeSelectedTest(testCode) {
  // Test checkbox'ını bul ve kaldır
  const checkbox = document.querySelector(`.test-checkbox[data-test*='"code":"${testCode}"']`);
  if (checkbox) {
    checkbox.checked = false;
    checkbox.closest('.test-list-item').classList.remove('selected');
  }
  
  // Paket seçimini kaldır
  document.querySelectorAll('.package-card').forEach(el => el.classList.remove('selected'));
  selectedPackageId = null;
  
  updateSelectedTests();
}

// Onay modalı göster
function showConfirmModal() {
  if (selectedPatients.length === 0 || selectedTests.length === 0) {
    alert('Lütfen en az bir hasta ve bir test seçiniz');
    return;
  }
  
  const modal = document.getElementById('confirmModal');
  const body = document.getElementById('confirmModalBody');
  
  let html = '<div style="margin-bottom: 16px; padding: 12px; background: #fef3c7; border-radius: 6px; color: #92400e;">';
  html += '<i class="bi bi-exclamation-triangle-fill"></i> ';
  html += `<strong>${selectedPatients.length} hastaya ${selectedTests.length} test</strong> gönderilecektir. Toplam <strong>${selectedPatients.length * selectedTests.length} işlem</strong> yapılacak.`;
  html += '</div>';
  
  html += '<div style="margin-bottom: 20px;"><strong>Seçilen Testler:</strong><br>';
  html += '<div style="display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px;">';
  selectedTests.forEach(test => {
    html += `<span class="test-badge">${test.name}</span>`;
  });
  html += '</div></div>';
  
  html += '<div><strong>Gönderilecek Hastalar:</strong></div>';
  selectedPatients.forEach(patient => {
    html += '<div class="confirm-item">';
    html += `<div class="confirm-item-header">${patient.first_name} ${patient.last_name}</div>`;
    html += '<div class="confirm-item-tests">';
    selectedTests.forEach(test => {
      html += `<span class="test-badge">${test.name}</span>`;
    });
    html += '</div></div>';
  });
  
  body.innerHTML = html;
  modal.style.display = 'flex';
}

function closeConfirmModal() {
  document.getElementById('confirmModal').style.display = 'none';
}

// Toplu gönderim
async function confirmSend() {
  const gelisTarihi = document.getElementById('gelisTarihi').value;
  const gelisTipi = document.getElementById('gelisTipi').value;
  
  if (!gelisTarihi) {
    alert('Lütfen gönderim tarihini seçiniz');
    return;
  }
  
  closeConfirmModal();
  
  const btn = document.getElementById('btnPreview');
  btn.disabled = true;
  btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Gönderiliyor...';
  
  let successCount = 0;
  let errorCount = 0;
  const errors = [];
  
  for (const patient of selectedPatients) {
    try {
      const res = await fetch('/HastaModulu/dislabIzle.php?action=kaydet', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          patient_id: patient.id,
          first_name: patient.first_name,
          last_name: patient.last_name,
          national_id: patient.national_id || '',
          birth_date: patient.birth_date || '',
          gender: patient.gender || 'Erkek',
          dosya_no: patient.id,
          gelis_tarihi: gelisTarihi,
          gelis_tipi: gelisTipi,
          tests: selectedTests  // {code, name} objesi ile gönder
        })
      });
      
      const data = await res.json();
      
      if (data.success) {
        successCount++;
      } else {
        errorCount++;
        errors.push(`${patient.first_name} ${patient.last_name}: ${data.error}`);
      }
    } catch(err) {
      errorCount++;
      errors.push(`${patient.first_name} ${patient.last_name}: ${err.message}`);
    }
  }
  
  btn.disabled = false;
  btn.innerHTML = '<i class="bi bi-eye-fill"></i> Önizleme & Onayla';
  
  let message = `Gönderim tamamlandı!\n\n`;
  message += `✓ Başarılı: ${successCount}\n`;
  if (errorCount > 0) {
    message += `✗ Hatalı: ${errorCount}\n\n`;
    message += 'Hatalar:\n' + errors.join('\n');
  }
  
  alert(message);
  
  if (successCount > 0) {
    setTimeout(() => location.reload(), 2000);
  }
}

// XML Modal Fonksiyonları
let currentXmlContent = '';
let currentRequestXml = '';

function prettyPrintXml(xmlString) {
  try {
    const xmlDoc = new DOMParser().parseFromString(xmlString, 'text/xml');
    if (xmlDoc.parseError) {
      return xmlString;
    }
    const serializer = new XMLSerializer();
    let prettyXml = serializer.serializeToString(xmlDoc);
    // Basit pretty print
    prettyXml = prettyXml.replace(/></g, '>\n<').replace(/><([^/])/g, '>\n<$1');
    return prettyXml;
  } catch(e) {
    return xmlString;
  }
}

function showXmlModal(data) {
  const modal = document.getElementById('xmlModal');
  const responseBody = document.getElementById('xmlModalBody');
  const requestBody = document.getElementById('xmlModalBodyRequest');
  
  currentXmlContent = data.response_xml || '';
  // Extract request XML from response if available, or show placeholder
  currentRequestXml = data.request_xml || '(Giden XML kaydedilmedi)';
  
  // Pretty print both XMLs
  responseBody.textContent = prettyPrintXml(currentXmlContent);
  requestBody.textContent = prettyPrintXml(currentRequestXml);
  
  // Show response tab by default
  switchXmlTab('response');
  
  modal.style.display = 'flex';
}

function switchXmlTab(tabName) {
  // Hide all tabs
  document.getElementById('responseTab').classList.remove('active');
  document.getElementById('requestTab').classList.remove('active');
  
  // Remove active class from all buttons
  document.querySelectorAll('.modal-tab').forEach(btn => btn.classList.remove('active'));
  
  // Show selected tab
  if (tabName === 'response') {
    document.getElementById('responseTab').classList.add('active');
    document.querySelectorAll('.modal-tab')[0].classList.add('active');
  } else {
    document.getElementById('requestTab').classList.add('active');
    document.querySelectorAll('.modal-tab')[1].classList.add('active');
  }
}

function closeXmlModal() {
  document.getElementById('xmlModal').style.display = 'none';
}

function copyXmlToClipboard() {
  const activeTab = document.getElementById('responseTab').classList.contains('active') ? 'response' : 'request';
  const xmlToCopy = activeTab === 'response' ? currentXmlContent : currentRequestXml;
  
  navigator.clipboard.writeText(xmlToCopy).then(() => {
    alert(activeTab === 'response' ? 'Gelen XML kopyalandı!' : 'Giden XML kopyalandı!');
  }).catch(err => {
    console.error('Kopyala başarısız:', err);
  });
}

// Sonuç sorgulama fonksiyonu
function showQueryResults(referansId, patientName) {
  const modal = document.getElementById('queryResultsModal');
  const body = document.getElementById('queryResultsBody');
  
  modal.style.display = 'flex';
  
  // AJAX ile sonuçları sor
  fetch('/HastaModulu/dislabIzle.php?action=sorgu_sonuc&referans_id=' + encodeURIComponent(referansId))
    .then(response => response.json())
    .then(data => {
      if (!data.success) {
        body.innerHTML = `
          <div style="padding: 24px; text-align: center;">
            <div style="color: #dc2626; font-size: 14px; margin-bottom: 12px;">
              <i class="bi bi-exclamation-circle" style="font-size: 1.5rem;"></i>
            </div>
            <p style="color: #991b1b; font-weight: 600;">${data.error || 'Sonuçlar sorgulanamadı'}</p>
            <p style="color: #999; font-size: 13px; margin-top: 8px;">Referans ID: <code>${referansId}</code></p>
          </div>
        `;
        return;
      }
      
      const results = data.data || [];
      const ornekNo = data.ornek_no || '';
      
      if (results.length === 0) {
        body.innerHTML = `
          <div style="padding: 24px; text-align: center;">
            <p style="color: #666;">Henüz sonuç bulunamadı</p>
            <p style="color: #999; font-size: 13px; margin-top: 8px;">Referans ID: <code>${referansId}</code></p>
          </div>
        `;
        return;
      }
      
      let html = `<div style="padding: 16px;">`;
      html += `<div style="margin-bottom: 16px; padding: 12px; background: #f0fdf4; border-left: 4px solid #10b981; border-radius: 4px;">`;
      html += `<strong style="color: #065f46;">${patientName}</strong><br>`;
      html += `<small style="color: #6b7280;">Referans: ${referansId}</small>`;
      if (ornekNo) {
        html += `<br><small style="color: #6b7280;">Örnek No: ${ornekNo}</small>`;
      }
      html += `</div>`;
      
      results.forEach((result, idx) => {
        const testAdi = result.TetkiAdi || result.TetkiKodu || '-';
        const sonuc = result.Sonuc || '-';
        const birim = result.BirimAdi || result.Birim || '';
        const refMin = result.RefMin || '-';
        const refMax = result.RefMax || '-';
        const durum = result.Durum || '-';
        
        const bgColor = durum === 'Normal' ? '#f0fdf4' : durum === 'Yüksek' ? '#fef2f2' : durum === 'Düşük' ? '#fef3c7' : '#f3f4f6';
        const borderColor = durum === 'Normal' ? '#10b981' : durum === 'Yüksek' ? '#ef4444' : durum === 'Düşük' ? '#f59e0b' : '#9ca3af';
        
        html += `<div style="margin-bottom: 12px; padding: 12px; background: ${bgColor}; border-left: 4px solid ${borderColor}; border-radius: 4px;">`;
        html += `<div style="font-weight: 600; margin-bottom: 6px;">${testAdi}</div>`;
        html += `<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 13px; color: #555;">`;
        html += `<div><span style="color: #666;">Sonuç:</span> <strong>${sonuc}</strong> ${birim}</div>`;
        html += `<div><span style="color: #666;">Aralık:</span> ${refMin} - ${refMax}</div>`;
        html += `</div>`;
        if (durum && durum !== 'Normal') {
          html += `<div style="margin-top: 8px; padding: 6px 8px; background: rgba(0,0,0,0.05); border-radius: 3px; font-size: 12px; color: #666;">⚠️ Durum: <strong>${durum}</strong></div>`;
        }
        html += `</div>`;
      });
      
      html += `</div>`;
      body.innerHTML = html;
      
      // Modal footer'ı güncelle - butonları göster
      updateQueryResultsFooter(referansId, ornekNo);
    })
    .catch(err => {
      body.innerHTML = `
        <div style="padding: 24px; text-align: center;">
          <div style="color: #dc2626; font-size: 14px; margin-bottom: 12px;">
            <i class="bi bi-exclamation-circle" style="font-size: 1.5rem;"></i>
          </div>
          <p style="color: #991b1b; font-weight: 600;">Hata: ${err.message}</p>
        </div>
      `;
    });
}

function closeQueryResultsModal() {
  document.getElementById('queryResultsModal').style.display = 'none';
}

// Modal footer'ını butonlarla güncelle
function updateQueryResultsFooter(referansId, ornekNo) {
  const footer = document.querySelector('#queryResultsModal .modal-footer');
  const escapedOrnekNo = ornekNo ? ornekNo.replace(/'/g, "\\'") : '';
  const escapedReferansId = referansId ? referansId.replace(/'/g, "\\'") : '';
  
  let html = `
    <div style="display: flex; gap: 8px; justify-content: flex-end;">
      <button id="btnKaydet" class="btn btn-success" onclick="kaydetHastaSonuc(this, '${escapedOrnekNo}', '${escapedReferansId}')" style="padding: 8px 16px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; display: flex; align-items: center; gap: 6px;">
        <i class="bi bi-download"></i> Lokale Kaydet
      </button>
      <button id="btnRapor" class="btn btn-info" onclick="indir_rapor('${escapedOrnekNo}')" style="padding: 8px 16px; background: #0ea5e9; color: white; border: none; border-radius: 6px; cursor: pointer; display: flex; align-items: center; gap: 6px;">
        <i class="bi bi-file-pdf"></i> Raporu İndir
      </button>
      <button class="btn btn-secondary" onclick="closeQueryResultsModal()" style="padding: 8px 16px;">Kapat</button>
    </div>
  `;
  footer.innerHTML = html;
}

// Hasta sonuçlarını lokale kaydet
function kaydetHastaSonuc(btn, ornekNo, referansId) {
  if (!ornekNo) {
    alert('Örnek numarası bulunamadı!');
    return;
  }
  
  const originalText = btn.innerHTML;
  btn.disabled = true;
  btn.innerHTML = '<i class="bi bi-hourglass-split"></i> Kaydediliyor...';
  
  fetch('/HastaModulu/dislabIzle.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: 'action=kaydet_hasta_sonuc&ornek_no=' + encodeURIComponent(ornekNo) + '&referan_id=' + encodeURIComponent(referansId)
  })
    .then(r => r.json())
    .then(data => {
      btn.disabled = false;
      btn.innerHTML = originalText;
      
      if (data.success) {
        alert('✓ ' + data.message);
        closeQueryResultsModal();
      } else {
        alert('✗ ' + (data.error || 'Kaydedilemedi'));
      }
    })
    .catch(err => {
      btn.disabled = false;
      btn.innerHTML = originalText;
      alert('Hata: ' + err.message);
    });
}

// Rapor PDF'ini indir
function indir_rapor(ornekNo) {
  if (!ornekNo) {
    alert('Örnek numarası bulunamadı!');
    return;
  }
  
  window.location.href = '/HastaModulu/dislabIzle.php?action=download_rapor&ornek_no=' + encodeURIComponent(ornekNo);
}

// Veri ile sonuçları göster (manuel sorgulama için)
function showQueryResultsWithData(results, referansId, patientName) {
  const modal = document.getElementById('queryResultsModal');
  const body = document.getElementById('queryResultsBody');
  
  modal.style.display = 'flex';
  
  if (!results || results.length === 0) {
    body.innerHTML = `
      <div style="padding: 24px; text-align: center;">
        <p style="color: #666;">Henüz sonuç bulunamadı</p>
        <p style="color: #999; font-size: 13px; margin-top: 8px;">Referans ID: <code>${referansId}</code></p>
      </div>
    `;
    return;
  }
  
  let html = `<div style="padding: 16px;">`;
  html += `<div style="margin-bottom: 16px; padding: 12px; background: #f0fdf4; border-left: 4px solid #10b981; border-radius: 4px;">`;
  html += `<strong style="color: #065f46;">${patientName}</strong><br>`;
  html += `<small style="color: #6b7280;">Referans: ${referansId}</small>`;
  html += `</div>`;
  
  results.forEach((result, idx) => {
    const testAdi = result.TetkiAdi || result.TetkiKodu || '-';
    const sonuc = result.Sonuc || '-';
    const birim = result.BirimAdi || result.Birim || '';
    const refMin = result.RefMin || '-';
    const refMax = result.RefMax || '-';
    const durum = result.Durum || '-';
    
    const bgColor = durum === 'Normal' ? '#f0fdf4' : durum === 'Yüksek' ? '#fef2f2' : durum === 'Düşük' ? '#fef3c7' : '#f3f4f6';
    const borderColor = durum === 'Normal' ? '#10b981' : durum === 'Yüksek' ? '#ef4444' : durum === 'Düşük' ? '#f59e0b' : '#9ca3af';
    
    html += `<div style="margin-bottom: 12px; padding: 12px; background: ${bgColor}; border-left: 4px solid ${borderColor}; border-radius: 4px;">`;
    html += `<div style="font-weight: 600; margin-bottom: 6px;">${testAdi}</div>`;
    html += `<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; font-size: 13px; color: #555;">`;
    html += `<div><span style="color: #666;">Sonuç:</span> <strong>${sonuc}</strong> ${birim}</div>`;
    html += `<div><span style="color: #666;">Aralık:</span> ${refMin} - ${refMax}</div>`;
    html += `</div>`;
    if (durum && durum !== 'Normal') {
      html += `<div style="margin-top: 8px; padding: 6px 8px; background: rgba(0,0,0,0.05); border-radius: 3px; font-size: 12px; color: #666;">⚠️ Durum: <strong>${durum}</strong></div>`;
    }
    html += `</div>`;
  });
  
  html += `</div>`;
  body.innerHTML = html;
}

// Modal dışına tıklanınca kapat
window.onclick = function(event) {
  const modal = document.getElementById('confirmModal');
  if (event.target === modal) {
    closeConfirmModal();
  }
}
</script>

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