<?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 === 'add_test') {
        $code = trim($_POST['code'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $category = trim($_POST['category'] ?? '');
        $unit = trim($_POST['unit'] ?? '');
        $minRef = trim($_POST['min_ref'] ?? '');
        $maxRef = trim($_POST['max_ref'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        
        if (!$code || !$name) {
          $errors[] = 'Test kodu ve adı gerekli';
        } else {
          try {
            $stmt = $pdo->prepare('
              INSERT INTO local_test_definitions 
              (code, name, category, unit, min_ref, max_ref, description, is_active)
              VALUES (:code, :name, :cat, :unit, :min, :max, :desc, 1)
            ');
            $stmt->execute([
              ':code' => $code,
              ':name' => $name,
              ':cat' => $category ?: null,
              ':unit' => $unit ?: null,
              ':min' => $minRef ?: null,
              ':max' => $maxRef ?: null,
              ':desc' => $desc ?: null
            ]);
            $info = "Test '{$name}' başarıyla eklendi";
          } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
              $errors[] = "Test kodu '{$code}' zaten kullanılıyor";
            } else {
              $errors[] = 'Veri tabanı hatası: ' . $e->getMessage();
            }
          }
        }
      } elseif ($action === 'update_test') {
        $id = (int)($_POST['id'] ?? 0);
        $code = trim($_POST['code'] ?? '');
        $name = trim($_POST['name'] ?? '');
        $category = trim($_POST['category'] ?? '');
        $unit = trim($_POST['unit'] ?? '');
        $minRef = trim($_POST['min_ref'] ?? '');
        $maxRef = trim($_POST['max_ref'] ?? '');
        $desc = trim($_POST['description'] ?? '');
        $active = isset($_POST['is_active']) ? 1 : 0;
        
        if (!$id) {
          $errors[] = 'Geçersiz test';
        } elseif (!$code || !$name) {
          $errors[] = 'Test kodu ve adı gerekli';
        } else {
          $stmt = $pdo->prepare('
            UPDATE local_test_definitions 
            SET code=:code, name=:name, category=:cat, unit=:unit, 
                min_ref=:min, max_ref=:max, description=:desc, is_active=:active
            WHERE id=:id
          ');
          $stmt->execute([
            ':id' => $id,
            ':code' => $code,
            ':name' => $name,
            ':cat' => $category ?: null,
            ':unit' => $unit ?: null,
            ':min' => $minRef ?: null,
            ':max' => $maxRef ?: null,
            ':desc' => $desc ?: null,
            ':active' => $active
          ]);
          $info = "Test '{$name}' başarıyla güncellendi";
        }
      } elseif ($action === 'delete_test') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
          $pdo->prepare('DELETE FROM local_test_definitions WHERE id=:id')->execute([':id' => $id]);
          $info = 'Test silindi';
        }
      }
    } catch (\Throwable $e) {
      $errors[] = 'İşlem başarısız: ' . $e->getMessage();
    }
  }
}

// Get search query
$search = trim($_GET['q'] ?? '');

// Get all tests or filtered
if ($search) {
  $stmt = $pdo->prepare('
    SELECT * FROM local_test_definitions 
    WHERE code LIKE :q OR name LIKE :q OR category LIKE :q
    ORDER BY code
  ');
  $stmt->execute([':q' => "%{$search}%"]);
  $tests = $stmt->fetchAll(PDO::FETCH_ASSOC);
} else {
  $tests = $pdo->query('SELECT * FROM local_test_definitions ORDER BY code')->fetchAll(PDO::FETCH_ASSOC);
}
$csrf = App\Csrf::token();

include __DIR__ . '/../header.php';
$full_width = true;
?>
<style>
:root {
  --primary: #2563eb;
  --primary-hover: #1d4ed8;
  --success: #059669;
  --danger: #dc2626;
  --gray-50: #f9fafb;
  --gray-100: #f3f4f6;
  --gray-200: #e5e7eb;
  --gray-600: #4b5563;
  --gray-700: #374151;
  --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;
  font-size: 0.95rem;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

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

.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-danger { 
  background: var(--danger);
  color: white;
}

.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: 14px 16px;
  border-bottom: 1px solid var(--gray-100);
  font-size: 0.95rem;
  vertical-align: middle;
}

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

.nl-table code {
  background: var(--gray-100);
  padding: 2px 8px;
  border-radius: 4px;
  color: var(--danger);
  font-size: 0.85rem;
}

.nl-form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.nl-form-group {
  display: flex;
  flex-direction: column;
}

.nl-form-group label {
  margin-bottom: 6px;
  font-weight: 600;
  font-size: 0.9rem;
  color: var(--gray-700);
}

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

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

.nl-input-small {
  font-size: 0.85rem;
  padding: 8px 12px;
}

.alert {
  padding: 14px 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;
}

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

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

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

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

.modal.active {
  display: flex;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 32px;
  max-width: 600px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  font-size: 1.5rem;
  font-weight: 700;
  margin-bottom: 20px;
  color: var(--gray-900);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--gray-600);
}

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

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

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

<div class="nl-container">
  <div class="nl-header">
    <div class="nl-header-content">
      <h1 class="nl-title"><i class="bi bi-beaker"></i> Test Tanımları</h1>
      <p class="nl-subtitle">Yerel test kodlarınızı tanımlayın ve yönetin</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 style="display: flex; justify-content: space-between; align-items: center; gap: 20px; margin-bottom: 24px; flex-wrap: wrap;">
        <h2 style="margin: 0; font-size: 1.25rem; color: var(--gray-900);">Tanımlı Testler</h2>
        <div style="display: flex; gap: 12px; flex: 1; max-width: 400px;">
          <form method="GET" style="display: flex; width: 100%; gap: 8px;">
            <input type="text" name="q" class="nl-input" placeholder="Testlerde ara (kod, ad, kategori)..." 
                   value="<?= htmlspecialchars($search) ?>" style="flex: 1; margin: 0;">
            <button type="submit" class="nl-btn nl-btn-primary"><i class="bi bi-search"></i></button>
            <?php if ($search): ?>
              <a href="?" class="nl-btn" style="background: var(--gray-100); color: var(--gray-700); text-decoration: none;">
                <i class="bi bi-x-lg"></i>
              </a>
            <?php endif; ?>
          </form>
        </div>
        <button class="nl-btn nl-btn-primary" onclick="openModal('addTestModal')">>
          <i class="bi bi-plus-lg"></i> Yeni Test Ekle
        </button>
      </div>

      <?php if (empty($tests)): ?>
        <div style="text-align: center; padding: 40px 20px; color: var(--gray-600);">
          <i class="bi bi-inbox" style="font-size: 3rem; display: block; margin-bottom: 16px; opacity: 0.5;"></i>
          <p style="font-size: 1.05rem; margin: 0;">
            <?php if ($search): ?>
              "<?= htmlspecialchars($search) ?>" için test bulunamadı
            <?php else: ?>
              Henüz test tanımlaması yapılmamış
            <?php endif; ?>
          </p>
          <p style="font-size: 0.95rem; margin: 10px 0 0 0; opacity: 0.7;">
            Başlamak için "Yeni Test Ekle" butonuna tıklayın
          </p>
        </div>
      <?php else: ?>
        <div class="nl-table-wrapper">
          <table class="nl-table">
            <thead>
              <tr>
                <th>Test Kodu</th>
                <th>Test Adı</th>
                <th>Kategori</th>
                <th>Birim</th>
                <th>Referans (Min-Max)</th>
                <th>Durum</th>
                <th>İşlem</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($tests as $test): ?>
                <tr>
                  <td><code><?= htmlspecialchars($test['code']) ?></code></td>
                  <td><strong><?= htmlspecialchars($test['name']) ?></strong></td>
                  <td><?= htmlspecialchars($test['category'] ?: '-') ?></td>
                  <td><?= htmlspecialchars($test['unit'] ?: '-') ?></td>
                  <td>
                    <?php if ($test['min_ref'] || $test['max_ref']): ?>
                      <?= htmlspecialchars($test['min_ref'] ?: '-') ?> - <?= htmlspecialchars($test['max_ref'] ?: '-') ?>
                    <?php else: ?>
                      -
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php if ($test['is_active']): ?>
                      <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 12px; border-radius: 6px; background: #d1fae5; color: #065f46; font-size: 0.75rem; font-weight: 600;">
                        <i class="bi bi-check-circle"></i> Aktif
                      </span>
                    <?php else: ?>
                      <span style="display: inline-flex; align-items: center; gap: 4px; padding: 4px 12px; border-radius: 6px; background: #fee2e2; color: #991b1b; font-size: 0.75rem; font-weight: 600;">
                        <i class="bi bi-x-circle"></i> İnaktif
                      </span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <div style="display: flex; gap: 6px;">
                      <button class="btn-icon btn-success" onclick="editTest(<?= $test['id'] ?>, <?= htmlspecialchars(json_encode($test)) ?>)" title="Düzenle">
                        <i class="bi bi-pencil"></i>
                      </button>
                      <form method="POST" style="display: inline;" onsubmit="return confirm('Testi silmek istediğinizden emin misiniz?')">
                        <input type="hidden" name="_csrf" value="<?= $csrf ?>">
                        <input type="hidden" name="action" value="delete_test">
                        <input type="hidden" name="id" value="<?= $test['id'] ?>">
                        <button type="submit" class="btn-icon btn-danger" title="Sil">
                          <i class="bi bi-trash"></i>
                        </button>
                      </form>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<!-- Add Test Modal -->
<div id="addTestModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span>Yeni Test Ekle</span>
      <button class="modal-close" onclick="closeModal('addTestModal')">&times;</button>
    </div>
    <form method="POST" class="modal-body">
      <input type="hidden" name="_csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="add_test">
      
      <div class="nl-form-grid">
        <div class="nl-form-group">
          <label>Test Kodu *</label>
          <input type="text" name="code" class="nl-input" placeholder="örn: TSH" required>
        </div>
        <div class="nl-form-group">
          <label>Test Adı *</label>
          <input type="text" name="name" class="nl-input" placeholder="örn: Tiroid Stimüle Hormonu" required>
        </div>
        <div class="nl-form-group">
          <label>Kategori</label>
          <input type="text" name="category" class="nl-input" placeholder="örn: Endokrinoloji">
        </div>
        <div class="nl-form-group">
          <label>Ölçü Birimi</label>
          <input type="text" name="unit" class="nl-input" placeholder="örn: mIU/mL">
        </div>
        <div class="nl-form-group">
          <label>Min Referans</label>
          <input type="text" name="min_ref" class="nl-input nl-input-small" placeholder="örn: 0.4">
        </div>
        <div class="nl-form-group">
          <label>Max Referans</label>
          <input type="text" name="max_ref" class="nl-input nl-input-small" placeholder="örn: 4.0">
        </div>
      </div>
      
      <div class="nl-form-group">
        <label>Açıklama</label>
        <textarea name="description" class="nl-input" placeholder="Test hakkında notlar..." rows="3" style="resize: vertical;"></textarea>
      </div>

      <div class="modal-footer">
        <button type="button" class="nl-btn" onclick="closeModal('addTestModal')" style="background: var(--gray-100); color: var(--gray-700);">İptal</button>
        <button type="submit" class="nl-btn nl-btn-primary">Ekle</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Test Modal -->
<div id="editTestModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <span>Testi Düzenle</span>
      <button class="modal-close" onclick="closeModal('editTestModal')">&times;</button>
    </div>
    <form method="POST" class="modal-body">
      <input type="hidden" name="_csrf" value="<?= $csrf ?>">
      <input type="hidden" name="action" value="update_test">
      <input type="hidden" name="id" id="editTestId">
      
      <div class="nl-form-grid">
        <div class="nl-form-group">
          <label>Test Kodu *</label>
          <input type="text" name="code" id="editCode" class="nl-input" required>
        </div>
        <div class="nl-form-group">
          <label>Test Adı *</label>
          <input type="text" name="name" id="editName" class="nl-input" required>
        </div>
        <div class="nl-form-group">
          <label>Kategori</label>
          <input type="text" name="category" id="editCategory" class="nl-input">
        </div>
        <div class="nl-form-group">
          <label>Ölçü Birimi</label>
          <input type="text" name="unit" id="editUnit" class="nl-input">
        </div>
        <div class="nl-form-group">
          <label>Min Referans</label>
          <input type="text" name="min_ref" id="editMinRef" class="nl-input nl-input-small">
        </div>
        <div class="nl-form-group">
          <label>Max Referans</label>
          <input type="text" name="max_ref" id="editMaxRef" class="nl-input nl-input-small">
        </div>
      </div>
      
      <div class="nl-form-group">
        <label>Açıklama</label>
        <textarea name="description" id="editDescription" class="nl-input" rows="3" style="resize: vertical;"></textarea>
      </div>

      <div style="margin-bottom: 20px; padding: 16px; background: var(--gray-50); border-radius: 8px;">
        <label style="display: flex; align-items: center; gap: 10px; margin: 0; cursor: pointer; font-weight: 500;">
          <input type="checkbox" name="is_active" id="editActive" style="width: 18px; height: 18px; cursor: pointer;">
          <span>Aktif tut</span>
        </label>
      </div>

      <div class="modal-footer">
        <button type="button" class="nl-btn" onclick="closeModal('editTestModal')" style="background: var(--gray-100); color: var(--gray-700);">İptal</button>
        <button type="submit" class="nl-btn nl-btn-primary">Güncelle</button>
      </div>
    </form>
  </div>
</div>

<script>
function openModal(id) {
  document.getElementById(id).classList.add('active');
}

function closeModal(id) {
  document.getElementById(id).classList.remove('active');
}

function editTest(id, test) {
  document.getElementById('editTestId').value = test.id;
  document.getElementById('editCode').value = test.code;
  document.getElementById('editName').value = test.name;
  document.getElementById('editCategory').value = test.category || '';
  document.getElementById('editUnit').value = test.unit || '';
  document.getElementById('editMinRef').value = test.min_ref || '';
  document.getElementById('editMaxRef').value = test.max_ref || '';
  document.getElementById('editDescription').value = test.description || '';
  document.getElementById('editActive').checked = test.is_active == 1;
  openModal('editTestModal');
}

// Close modal when clicking outside
document.querySelectorAll('.modal').forEach(modal => {
  modal.addEventListener('click', e => {
    if (e.target === modal) closeModal(modal.id);
  });
});
</script>

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