<?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']);
$pdo = Database::getConnection();

$result = null;
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    try {
      if ($action === 'import_xml') {
        $xmlData = trim($_POST['xml_data'] ?? '');
        if (!$xmlData) {
          $errors[] = 'XML verisi gerekli';
        } else {
          // XML'i parse et
          libxml_use_internal_errors(true);
          $xml = simplexml_load_string($xmlData);
          
          if (!$xml) {
            $errors[] = 'Geçersiz XML formatı';
          } else {
            $insertedTests = [];
            $mappedTests = [];

            foreach ($xml->Tetkikler->TestSonuc as $test) {
              $externalCode = (string)$test->Kodu;
              $testName = (string)$test->Adi;
              $minRef = (string)$test->ReferansMin ?: null;
              $maxRef = (string)$test->ReferansMax ?: null;
              $unit = (string)$test->Birim ?: null;

              $localCode = 'DISLAB-' . $externalCode;

              // Lokal test ekle
              $stmt = $pdo->prepare('
                INSERT INTO local_test_definitions 
                (code, name, unit, min_ref, max_ref, category, is_active)
                VALUES (:code, :name, :unit, :min, :max, :cat, 1)
                ON DUPLICATE KEY UPDATE 
                name=VALUES(name), unit=VALUES(unit), min_ref=VALUES(min_ref), max_ref=VALUES(max_ref)
              ');
              
              $stmt->execute([
                ':code' => $localCode,
                ':name' => $testName,
                ':unit' => $unit,
                ':min' => $minRef,
                ':max' => $maxRef,
                ':cat' => 'Dışlab'
              ]);

              $insertedTests[] = $localCode;

              // Dışlab servisini bul ve eşleştir
              $serviceStmt = $pdo->prepare('
                SELECT id FROM external_lab_services 
                WHERE service_code = :code LIMIT 1
              ');
              $serviceStmt->execute([':code' => $externalCode]);
              $service = $serviceStmt->fetch(PDO::FETCH_ASSOC);

              if ($service) {
                $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)
                ');
                $mapStmt->execute([
                  ':sid' => $service['id'],
                  ':code' => $localCode,
                  ':name' => $testName
                ]);
                $mappedTests[] = $externalCode;
              }
            }

            $result = [
              'success' => true,
              'inserted' => count($insertedTests),
              'mapped' => count($mappedTests),
              'total' => count($xml->Tetkikler->TestSonuc)
            ];
          }
        }
      }
    } catch (\Throwable $e) {
      $errors[] = 'İşlem hatası: ' . $e->getMessage();
    }
  }
}

$csrf = App\Csrf::token();
include __DIR__ . '/../header.php';
$full_width = true;
?>
<style>
:root {
  --primary: #2563eb;
  --success: #059669;
  --danger: #dc2626;
  --gray-50: #f9fafb;
  --gray-100: #f3f4f6;
  --gray-200: #e5e7eb;
  --gray-900: #111827;
  --border: #e2e8f0;
}

body { background: #f8fafc; }

.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-subtitle { 
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-size: 1.05rem;
}

.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);
  padding: 28px 32px;
  margin-bottom: 24px;
}

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

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

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

.nl-form-group {
  margin-bottom: 20px;
}

.nl-form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: var(--gray-900);
}

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

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

.nl-textarea {
  resize: vertical;
  min-height: 300px;
  font-family: 'Monaco', 'Courier New', monospace;
  font-size: 0.9rem;
}

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

.alert-success {
  background: #d1fae5;
  color: #065f46;
  border: 1px solid #a7f3d0;
}

.alert-danger {
  background: #fee2e2;
  color: #991b1b;
  border: 1px solid #fecaca;
}

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

.result-box {
  background: var(--gray-50);
  border: 2px solid var(--primary);
  border-radius: 12px;
  padding: 20px;
  margin: 20px 0;
}

.result-stat {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin: 16px 0;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border: 1px solid var(--border);
}

.stat-number {
  font-size: 2.5rem;
  font-weight: 700;
  color: var(--primary);
}

.stat-label {
  font-size: 0.9rem;
  color: var(--gray-600);
  margin-top: 8px;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

@media (max-width: 768px) {
  .nl-header, .nl-body {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .nl-title {
    font-size: 1.5rem;
  }
}
</style>

<div class="nl-container">
  <div class="nl-header">
    <div class="nl-header-content">
      <h1 class="nl-title"><i class="bi bi-upload"></i> XML'den Test İçe Aktar</h1>
      <p class="nl-subtitle">Dışlab XML'sinden test kodlarını parse edip lokal testlere ekle</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 ($result && $result['success']): ?>
      <div class="alert alert-success">
        ✓ İçe aktarma başarıyla tamamlandı!
      </div>
      <div class="result-box">
        <div class="result-stat">
          <div class="stat-item">
            <div class="stat-number"><?= $result['inserted'] ?></div>
            <div class="stat-label">Eklenen Test</div>
          </div>
          <div class="stat-item">
            <div class="stat-number"><?= $result['mapped'] ?></div>
            <div class="stat-label">Otomatik Eşleşti</div>
          </div>
          <div class="stat-item">
            <div class="stat-number"><?= $result['total'] ?></div>
            <div class="stat-label">Toplam Test</div>
          </div>
        </div>
        <p style="margin: 16px 0 0 0; padding-top: 16px; border-top: 1px solid #e5e7eb; color: #475569;">
          <i class="bi bi-info-circle me-2"></i>
          Lokal testler <strong>DISLAB-</strong> ön ekiyle oluşturuldu. 
          <a href="test-tanimlari.php" style="color: var(--primary); text-decoration: none; font-weight: 600;">Test Tanımları</a> 
          sayfasından görüntüleyebilirsiniz.
        </p>
      </div>
    <?php endif; ?>

    <div class="nl-card">
      <h2 style="margin: 0 0 20px 0; font-size: 1.25rem; color: var(--gray-900);">
        <i class="bi bi-file-xml me-2"></i> XML Verilerini Yapıştır
      </h2>

      <div class="alert alert-info">
        <strong>Nasıl yapılır:</strong>
        <ul style="margin: 10px 0 0 0; padding-left: 20px;">
          <li>Dışlab XML çıktısını aşağıya yapıştırın</li>
          <li>System otomatik olarak TestSonuc'ları parse edecek</li>
          <li>Her test için "DISLAB-" ön ekli lokal test oluşturacak</li>
          <li>Dışlab servislerinde matching kodlar varsa otomatik eşleştirecek</li>
        </ul>
      </div>

      <form method="POST">
        <input type="hidden" name="_csrf" value="<?= $csrf ?>">
        <input type="hidden" name="action" value="import_xml">

        <div class="nl-form-group">
          <label for="xmlData">
            <i class="bi bi-file-code me-2"></i> XML Verisi
          </label>
          <textarea 
            name="xml_data" 
            id="xmlData" 
            class="nl-textarea" 
            placeholder="<?xml version=&quot;1.0&quot;?>&#10;<HastaSorguCevapReferans>&#10;  <Tetkikler>&#10;    <TestSonuc>..."
            required></textarea>
        </div>

        <div style="display: flex; gap: 12px;">
          <button type="submit" class="nl-btn nl-btn-primary">
            <i class="bi bi-cloud-upload"></i> İçe Aktar
          </button>
          <button type="reset" class="nl-btn" style="background: var(--gray-100); color: var(--gray-900);">
            <i class="bi bi-arrow-clockwise"></i> Temizle
          </button>
        </div>
      </form>
    </div>

    <div class="nl-card">
      <h3 style="margin: 0 0 16px 0; font-size: 1.1rem;">📋 Örnek XML Yapısı</h3>
      <p style="color: var(--gray-600); margin: 0 0 12px 0; font-size: 0.95rem;">
        XML'de en az bu alanlar bulunmalıdır:
      </p>
      <pre style="background: var(--gray-50); padding: 16px; border-radius: 8px; overflow-x: auto; font-size: 0.85rem;"><code>&lt;?xml version="1.0"?&gt;
&lt;HastaSorguCevapReferans&gt;
  &lt;Tetkikler&gt;
    &lt;TestSonuc&gt;
      &lt;Adi&gt;LÖKOSİT&lt;/Adi&gt;
      &lt;Kodu&gt;C01&lt;/Kodu&gt;
      &lt;ReferansMin&gt;4.0&lt;/ReferansMin&gt;
      &lt;ReferansMax&gt;10.0&lt;/ReferansMax&gt;
      &lt;Birim&gt;x10^3/uL&lt;/Birim&gt;
    &lt;/TestSonuc&gt;
    ...
  &lt;/Tetkikler&gt;
&lt;/HastaSorguCevapReferans&gt;</code></pre>
    </div>

    <div class="nl-card" style="background: #f0f9ff; border: 2px solid #bfdbfe;">
      <h3 style="margin: 0 0 12px 0; color: var(--primary);">💡 İpuçları</h3>
      <ul style="margin: 0; padding-left: 20px; color: var(--gray-700);">
        <li><strong>Otomatik Eşleştirme:</strong> XML'deki test kodları (C01, B1098 vb.) dışlab servisinde de varsa otomatik eşleştirilir</li>
        <li><strong>Manuel Eşleştirme:</strong> Eşleşmeyen testler <a href="dislab-testler.php" style="color: var(--primary); font-weight: 600;">Dışlab Test Eşleştirme</a> sayfasında manuel olarak eşleştirilebilir</li>
        <li><strong>Test Yönetimi:</strong> Tüm lokal testler <a href="test-tanimlari.php" style="color: var(--primary); font-weight: 600;">Test Tanımları</a> sayfasından düzenlenebilir</li>
      </ul>
    </div>
  </div>
</div>

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