<?php
session_start();
require_once __DIR__ . '/../../vendor/autoload.php';
$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_lab') {
        $name = trim($_POST['name'] ?? '');
        $api_url = trim($_POST['api_url'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $api_key = trim($_POST['api_key'] ?? '');
        $api_password = trim($_POST['api_password'] ?? '');
        $description = trim($_POST['description'] ?? '');
        
        if (!$name) $errors[] = 'Laboratuvar adı gerekli';
        if (!$api_url) $errors[] = 'Web servis adresi gerekli';
        if (!$username) $errors[] = 'Kullanıcı adı gerekli';
        if (!$api_key) $errors[] = 'API Key gerekli';
        if (!$api_password) $errors[] = 'API Şifresi gerekli';
        
        if (empty($errors)) {
          $st = $pdo->prepare('INSERT INTO external_laboratories (name, api_url, username, api_key, api_password, description, status) VALUES (:name,:url,:user,:key,:pass,:desc,:status)');
          $st->execute([
            ':name' => $name,
            ':url' => $api_url,
            ':user' => $username,
            ':key' => $api_key,
            ':pass' => $api_password,
            ':desc' => $description ?: null,
            ':status' => 'active'
          ]);
          $info = 'Laboratuvar başarıyla eklendi';
        }
      } elseif ($action === 'update_lab') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $api_url = trim($_POST['api_url'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $api_key = trim($_POST['api_key'] ?? '');
        $api_password = trim($_POST['api_password'] ?? '');
        $description = trim($_POST['description'] ?? '');
        
        if (!$id) $errors[] = 'Geçersiz laboratuvar';
        if (!$name) $errors[] = 'Laboratuvar adı gerekli';
        if (!$api_url) $errors[] = 'Web servis adresi gerekli';
        if (!$username) $errors[] = 'Kullanıcı adı gerekli';
        if (!$api_key) $errors[] = 'API Key gerekli';
        if (!$api_password) $errors[] = 'API Şifresi gerekli';
        
        if (empty($errors)) {
          $upd = $pdo->prepare('UPDATE external_laboratories SET name=:name, api_url=:url, username=:user, api_key=:key, api_password=:pass, description=:desc WHERE id=:id');
          $upd->execute([
            ':id' => $id,
            ':name' => $name,
            ':url' => $api_url,
            ':user' => $username,
            ':key' => $api_key,
            ':pass' => $api_password,
            ':desc' => $description ?: null
          ]);
          $info = 'Laboratuvar başarıyla güncellendi';
        }
      } elseif ($action === 'delete_lab') {
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) {
          $errors[] = 'Geçersiz laboratuvar';
        } else {
          $del = $pdo->prepare('DELETE FROM external_laboratories WHERE id=:id');
          $del->execute([':id' => $id]);
          $info = 'Laboratuvar başarıyla silindi';
        }
      } elseif ($action === 'test_connection') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id) {
          $st = $pdo->prepare('SELECT api_url, username, api_key, api_password FROM external_laboratories WHERE id=:id');
          $st->execute([':id' => $id]);
          $lab = $st->fetch();
          
          if ($lab) {
            $test_result = testLabServiceConnection($lab['api_url'], $lab['username'], $lab['api_key'], $lab['api_password']);
            if ($test_result['success']) {
              $info = 'Bağlantı başarılı! Web servis erişilebilir.';
            } else {
              $errors[] = 'Bağlantı başarısız: ' . $test_result['error'];
            }
          }
        }
      } elseif ($action === 'toggle_status') {
        $id = (int)($_POST['id'] ?? 0);
        if (!$id) {
          $errors[] = 'Geçersiz laboratuvar';
        } else {
          $st = $pdo->prepare('SELECT status FROM external_laboratories WHERE id=:id');
          $st->execute([':id' => $id]);
          $lab = $st->fetch();
          
          if ($lab) {
            $new_status = ($lab['status'] === 'active') ? 'inactive' : 'active';
            $upd = $pdo->prepare('UPDATE external_laboratories SET status=:status WHERE id=:id');
            $upd->execute([':status' => $new_status, ':id' => $id]);
            $info = 'Laboratuvar durumu güncellendi';
          }
        }
      }
    } catch (\Throwable $e) {
      $errors[] = 'İşlem başarısız: ' . $e->getMessage();
    }
  }
}

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

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

// Get all external laboratories or filtered
if ($search) {
  $sql = "SELECT id, name, api_url, username, api_key, description, status, created_at 
          FROM external_laboratories 
          WHERE name LIKE :q OR description LIKE :q OR api_url LIKE :q
          ORDER BY status DESC, name ASC";
  $stmt = $pdo->prepare($sql);
  $stmt->execute([':q' => "%{$search}%"]);
  $laboratories = $stmt->fetchAll();
} else {
  $sql = "SELECT id, name, api_url, username, api_key, description, status, created_at 
          FROM external_laboratories 
          ORDER BY status DESC, name ASC";
  $laboratories = $pdo->query($sql)->fetchAll();
}

include __DIR__ . '/../header.php';
?>
<style>
/* ✅ Full Width */
.container,
.container-sm,
.container-md,
.container-lg,
.container-xl,
.container-xxl {
  max-width: 100% !important;
  width: 100% !important;
}

main,
#app,
#content,
.content,
.page,
.wrapper {
  max-width: 100% !important;
}

:root {
  --primary: #4f46e5;
  --primary-dark: #4338ca;
  --primary-light: #e0e7ff;
  --secondary: #7c3aed;
  --success: #10b981;
  --danger: #ef4444;
  --warning: #f59e0b;
  --info: #06b6d4;
  --light: #f8fafc;
  --dark: #0f172a;
  --gray-50: #f8fafc;
  --gray-100: #f1f5f9;
  --gray-200: #e2e8f0;
  --gray-300: #cbd5e1;
  --gray-400: #94a3b8;
  --gray-500: #64748b;
  --gray-600: #475569;
  --gray-700: #334155;
  --gray-800: #1e293b;
  --gray-900: #0f172a;
  --border-radius: 12px;
  --border-radius-lg: 16px;
  --border-radius-xl: 20px;
  --shadow-sm: 0 1px 3px rgba(0,0,0,0.08);
  --shadow: 0 4px 20px rgba(0,0,0,0.06);
  --shadow-lg: 0 12px 32px rgba(0,0,0,0.10);
  --shadow-xl: 0 20px 50px rgba(0,0,0,0.15);
  --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: var(--gray-800);
  line-height: 1.6;
  min-height: 100vh;
}

.page-container {
  max-width: 100% !important;
  width: 100% !important;
  margin: 0 !important;
  padding: 20px 24px;
}

@media (max-width: 768px) {
  .page-container {
    padding: 14px;
  }
}

.page-header {
  background: white;
  color: var(--gray-900);
  padding: 32px;
  margin-bottom: 32px;
  position: relative;
  overflow: hidden;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow);
  border-left: 6px solid var(--primary);
}

.page-header::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 300px;
  height: 300px;
  background: linear-gradient(135deg, var(--primary-light) 0%, transparent 70%);
  border-radius: 50%;
  opacity: 0.3;
  pointer-events: none;
}

.page-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background: linear-gradient(90deg, transparent, var(--gray-200), transparent);
}

.page-title-wrapper {
  position: relative;
  z-index: 2;
  max-width: 100%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: nowrap;
  gap: 24px;
}

@media (max-width: 900px) {
  .page-title-wrapper {
    flex-wrap: wrap;
  }
}

.page-title h1 {
  font-weight: 800;
  font-size: 36px;
  color: var(--gray-900);
  margin-bottom: 8px;
  letter-spacing: -0.5px;
}

.page-title p {
  color: var(--gray-600);
  font-size: 16px;
  font-weight: 400;
}

.btn {
  padding: 14px 28px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  transition: var(--transition);
  text-decoration: none;
  position: relative;
  overflow: hidden;
  letter-spacing: 0.3px;
  text-transform: uppercase;
  font-family: 'Inter', sans-serif;
}

.btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.6s ease;
}

.btn:hover::before {
  left: 100%;
}

.btn-primary {
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(79, 70, 229, 0.25);
}

.btn-primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(79, 70, 229, 0.35);
}

.filter-section {
  background: white;
  padding: 28px;
  border-radius: var(--border-radius-lg);
  margin-bottom: 28px;
  box-shadow: var(--shadow);
  border: 1px solid var(--gray-200);
}

.filter-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.filter-header h3 {
  font-size: 18px;
  font-weight: 700;
  color: var(--gray-900);
  margin: 0;
}

.filter-header i {
  color: var(--primary);
  font-size: 24px;
}

.filter-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

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

.form-label {
  font-weight: 600;
  font-size: 14px;
  color: var(--gray-700);
  margin-bottom: 10px;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.form-control,
.form-select {
  padding: 12px 16px;
  border: 1px solid var(--gray-300);
  border-radius: 10px;
  font-size: 14px;
  font-family: 'Inter', sans-serif;
  background: white;
  color: var(--gray-900);
  transition: var(--transition);
}

.form-control:focus,
.form-select:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
  background: white;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.alert {
  padding: 16px 20px;
  border-radius: 12px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
  animation: slideDown 0.4s ease;
  border-left: 4px solid;
}

.alert i {
  font-size: 20px;
  flex-shrink: 0;
  margin-top: 2px;
}

.alert-success {
  background: linear-gradient(135deg, rgba(16, 185, 129, 0.1) 0%, rgba(5, 150, 105, 0.08) 100%);
  color: #065f46;
  border-left-color: var(--success);
}

.alert-danger {
  background: linear-gradient(135deg, rgba(239, 68, 68, 0.1) 0%, rgba(220, 38, 38, 0.08) 100%);
  color: #7f1d1d;
  border-left-color: var(--danger);
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.table-container {
  background: white;
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow);
  border: 1px solid var(--gray-200);
}

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

.table thead {
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: white;
}

.table th {
  padding: 16px 20px;
  text-align: left;
  font-weight: 700;
  font-size: 13px;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  border-bottom: 2px solid rgba(255, 255, 255, 0.1);
}

.table td {
  padding: 16px 20px;
  border-bottom: 1px solid var(--gray-200);
  vertical-align: middle;
}

.table tbody tr {
  transition: var(--transition);
}

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

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

.badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 8px;
  font-weight: 600;
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.badge-success {
  background: linear-gradient(135deg, var(--success) 0%, #059669 100%);
  color: white;
}

.badge-danger {
  background: linear-gradient(135deg, var(--danger) 0%, #dc2626 100%);
  color: white;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.btn-sm {
  padding: 8px 14px;
  font-size: 12px;
  border-radius: 8px;
  border: none;
  cursor: pointer;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  transition: var(--transition);
  text-decoration: none;
  text-transform: uppercase;
  letter-spacing: 0.3px;
}

.btn-sm-primary {
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.btn-sm-primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.btn-sm-warning {
  background: linear-gradient(135deg, var(--warning) 0%, #d97706 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.2);
}

.btn-sm-warning:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(245, 158, 11, 0.3);
}

.btn-sm-danger {
  background: linear-gradient(135deg, var(--danger) 0%, #dc2626 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);
}

.btn-sm-danger:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(239, 68, 68, 0.3);
}

.btn-sm-success {
  background: linear-gradient(135deg, var(--success) 0%, #059669 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
}

.btn-sm-success:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(16, 185, 129, 0.3);
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--gray-500);
}

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

.empty-state p {
  font-size: 16px;
  margin: 0;
}

.add-lab-card {
  background: white;
  padding: 28px;
  border-radius: var(--border-radius-lg);
  margin-bottom: 28px;
  box-shadow: var(--shadow);
  border: 1px solid var(--gray-200);
}

.add-lab-card h5 {
  font-size: 18px;
  font-weight: 700;
  color: var(--gray-900);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.add-lab-card i {
  color: var(--primary);
  font-size: 24px;
}

.add-lab-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  align-items: flex-end;
}

.modal-dialog {
  max-width: 600px;
}

.modal-content {
  border: none;
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-xl);
  overflow: hidden;
}

.modal-header {
  background: linear-gradient(135deg, var(--primary) 0%, var(--secondary) 100%);
  color: white;
  border: none;
  padding: 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.modal-header .btn-close {
  filter: brightness(0) invert(1);
  opacity: 0.7;
  margin: 0;
  padding: 0;
  width: auto;
  height: auto;
}

.modal-header .btn-close:hover,
.modal-header .btn-close:focus {
  opacity: 1;
  box-shadow: none;
}

.modal-title {
  font-weight: 700;
  font-size: 18px;
  letter-spacing: -0.3px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
}

.modal-body {
  padding: 24px;
  background: white;
}

.modal-footer {
  padding: 24px;
  border-top: 1px solid var(--gray-200);
  background: var(--gray-50);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 768px) {
  .add-lab-grid {
    grid-template-columns: 1fr;
  }

  .page-title h1 {
    font-size: 24px;
  }

  .filter-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-direction: column;
  }

  .btn-sm {
    width: 100%;
    justify-content: center;
  }
}
</style>

<!-- Navigation Links -->
<div style="margin-bottom: 20px; display: flex; gap: 10px; justify-content: center;">
  <a href="/SistemModulu/kurum-tanimlari.php" class="btn btn-secondary" style="background: transparent; color: #4f46e5; border: 1px solid #4f46e5; text-decoration: none; padding: 10px 16px; border-radius: 6px; font-size: 14px; font-weight: 600;">
    <i class="bi bi-building" style="margin-right: 6px;"></i>
    Kurum Tanımlamaları
  </a>
  <a href="/SistemModulu/dislab-tanimlari.php" class="btn btn-primary" style="background: linear-gradient(135deg, #4f46e5 0%, #7c3aed 100%); color: white; text-decoration: none; padding: 10px 16px; border-radius: 6px; font-size: 14px; font-weight: 600;">
    <i class="bi bi-flask-fill" style="margin-right: 6px;"></i>
    Dış Laboratuvar Tanımlamaları
  </a>
  <a href="/SistemModulu/kurum-lab-iliskilendirme.php" class="btn btn-secondary" style="background: transparent; color: #4f46e5; border: 1px solid #4f46e5; text-decoration: none; padding: 10px 16px; border-radius: 6px; font-size: 14px; font-weight: 600;">
    <i class="bi bi-diagram-3" style="margin-right: 6px;"></i>
    Kurum-Lab İlişkilendirmesi
  </a>
</div>

<div class="page-container">
  <div class="main-content">
    <!-- Page Header -->
    <div class="page-header">
      <div class="page-title-wrapper">
        <div class="page-title">
          <h1>
            <i class="bi bi-flask-fill" style="margin-right: 12px; color: var(--primary);"></i>
            Dış Laboratuvar Tanımlamaları
          </h1>
          <p>Bağımsız laboratuvar tanımlarını yönetin ve API bağlantılarını test edin</p>
        </div>
        <div style="flex-shrink: 0; display: flex; align-items: center; gap: 12px;">
          <form method="GET" style="display: flex; gap: 8px; align-items: center;">
            <input type="text" name="q" class="form-control" placeholder="Laboratuvar ara..." 
                   value="<?= htmlspecialchars($search) ?>" style="width: 250px;">
            <button type="submit" class="btn btn-outline-primary">
              <i class="bi bi-search"></i>
            </button>
            <?php if ($search): ?>
              <a href="?" class="btn btn-outline-secondary">
                <i class="bi bi-x-lg"></i>
              </a>
            <?php endif; ?>
          </form>
          <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addLabModal">
            <i class="bi bi-plus-lg"></i>
            YENİ LABORATUVAR EKLE
          </button>
        </div>
      </div>
    </div>

    <!-- Alerts -->
    <?php if($info): ?>
      <div class="alert alert-success">
        <i class="bi bi-check-circle-fill"></i>
        <div><?= htmlspecialchars($info) ?></div>
      </div>
    <?php endif; ?>

    <?php if($errors): ?>
      <div class="alert alert-danger">
        <i class="bi bi-exclamation-circle-fill"></i>
        <div>
          <?php foreach($errors as $e): ?>
            <div><?= htmlspecialchars($e) ?></div>
          <?php endforeach; ?>
        </div>
      </div>
    <?php endif; ?>

    <!-- Laboratories Table -->
    <div class="table-container">
      <table class="table">
        <thead>
          <tr>
            <th>LABORATUVAR ADI</th>
            <th>API ADRESI</th>
            <th>KULLANICI ADI</th>
            <th>DURUM</th>
            <th>KAYIT TARİHİ</th>
            <th>İŞLEMLER</th>
          </tr>
        </thead>
        <tbody>
          <?php if(empty($laboratories)): ?>
            <tr>
              <td colspan="6">
                <div class="empty-state">
                  <i class="bi bi-inbox"></i>
                  <p>
                    <?php if ($search): ?>
                      "<?= htmlspecialchars($search) ?>" i\u00e7in laboratuvar bulunamad\u0131
                    <?php else: ?>
                      Hen\u00fcz laboratuvar tan\u0131mlanmam\u0131\u015ft\u0131r
                    <?php endif; ?>
                  </p>
                </div>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach($laboratories as $lab): ?>
              <tr>
                <td>
                  <div style="display: flex; align-items: center; gap: 10px;">
                    <i class="bi bi-flask" style="color: var(--primary); font-size: 20px;"></i>
                    <div style="font-weight: 600; color: var(--gray-900);">
                      <?= htmlspecialchars($lab['name']) ?>
                    </div>
                  </div>
                </td>
                <td style="font-size: 13px; color: var(--gray-600); font-family: 'Courier New', monospace;">
                  <?= htmlspecialchars(substr($lab['api_url'], 0, 35) . (strlen($lab['api_url']) > 35 ? '...' : '')) ?>
                </td>
                <td style="font-size: 13px; color: var(--gray-600); font-weight: 500;">
                  <?= htmlspecialchars($lab['username'] ?? '-') ?>
                </td>
                <td>
                  <span class="badge <?= $lab['status'] === 'active' ? 'badge-success' : 'badge-danger' ?>">
                    <i class="bi <?= $lab['status'] === 'active' ? 'bi-check-circle-fill' : 'bi-x-circle-fill' ?>"></i>
                    <?= $lab['status'] === 'active' ? 'AKTİF' : 'PASİF' ?>
                  </span>
                </td>
                <td style="color: var(--gray-600); font-size: 13px;">
                  <?= date('d.m.Y', strtotime($lab['created_at'])) ?>
                </td>
                <td>
                  <div class="action-buttons">
                    <form method="POST" style="display: inline;">
                      <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                      <input type="hidden" name="action" value="test_connection">
                      <input type="hidden" name="id" value="<?= $lab['id'] ?>">
                      <button type="submit" class="btn-sm btn-sm-warning" title="Bağlantı Test Et">
                        <i class="bi bi-arrow-repeat"></i> TEST
                      </button>
                    </form>

                    <button class="btn-sm btn-sm-primary" data-bs-toggle="modal" data-bs-target="#editLabModal<?= $lab['id'] ?>" title="Düzenle">
                      <i class="bi bi-pencil-square"></i> DÜZENLE
                    </button>

                    <form method="POST" style="display: inline;">
                      <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                      <input type="hidden" name="action" value="toggle_status">
                      <input type="hidden" name="id" value="<?= $lab['id'] ?>">
                      <button type="submit" class="btn-sm <?= $lab['status'] === 'active' ? 'btn-sm-danger' : 'btn-sm-success' ?>">
                        <?php if($lab['status'] === 'active'): ?>
                          <i class="bi bi-x-circle"></i> PASİFLEŞTİR
                        <?php else: ?>
                          <i class="bi bi-check-circle"></i> AKTİFLEŞTİR
                        <?php endif; ?>
                      </button>
                    </form>

                    <form method="POST" style="display: inline;" onsubmit="return confirm('Bu laboratuvarı silmek istediğinize emin misiniz?');">
                      <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
                      <input type="hidden" name="action" value="delete_lab">
                      <input type="hidden" name="id" value="<?= $lab['id'] ?>">
                      <button type="submit" class="btn-sm btn-sm-danger" title="Sil">
                        <i class="bi bi-trash"></i> SİL
                      </button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- Add Laboratory Modal -->
<div class="modal fade" id="addLabModal" tabindex="-1" aria-labelledby="addLabModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addLabModalLabel">
          <i class="bi bi-plus-circle" style="margin-right: 8px;"></i> Yeni Laboratuvar Ekle
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form method="POST">
        <div class="modal-body">
          <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
          <input type="hidden" name="action" value="add_lab">

          <div class="mb-3">
            <label class="form-label">Laboratuvar Adı *</label>
            <input type="text" name="name" class="form-control" placeholder="Örn: Lims Sistemi, Labcore vb." required>
          </div>

          <div class="mb-3">
            <label class="form-label">API Adresi (URL) *</label>
            <input type="url" name="api_url" class="form-control" placeholder="Örn: https://api.laboraturvar.com/v1" required>
          </div>

          <div class="mb-3">
            <label class="form-label">Kullanıcı Adı *</label>
            <input type="text" name="username" class="form-control" placeholder="API kullanıcı adı" required>
          </div>

          <div class="row">
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">API Key *</label>
                <input type="text" name="api_key" class="form-control" placeholder="API anahtarı" required>
              </div>
            </div>
            <div class="col-md-6">
              <div class="mb-3">
                <label class="form-label">API Şifresi *</label>
                <input type="password" name="api_password" class="form-control" placeholder="API şifresi" required>
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label">Açıklama</label>
            <textarea name="description" class="form-control" rows="3" placeholder="Laboratuvar hakkında açıklama..."></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-check-circle" style="margin-right: 6px;"></i> Ekle
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Edit Laboratory Modals -->
<?php foreach($laboratories as $lab): ?>
  <div class="modal fade" id="editLabModal<?= $lab['id'] ?>" tabindex="-1" aria-labelledby="editLabModalLabel<?= $lab['id'] ?>" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="editLabModalLabel<?= $lab['id'] ?>">
            <i class="bi bi-pencil-square" style="margin-right: 8px;"></i> Laboratuvarı Düzenle
          </h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <form method="POST">
          <div class="modal-body">
            <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">
            <input type="hidden" name="action" value="update_lab">
            <input type="hidden" name="id" value="<?= $lab['id'] ?>">

            <div class="mb-3">
              <label class="form-label">Laboratuvar Adı *</label>
              <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($lab['name']) ?>" required>
            </div>

            <div class="mb-3">
              <label class="form-label">API Adresi (URL) *</label>
              <input type="url" name="api_url" class="form-control" value="<?= htmlspecialchars($lab['api_url']) ?>" required>
            </div>

            <div class="mb-3">
              <label class="form-label">Kullanıcı Adı *</label>
              <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($lab['username'] ?? '') ?>" required>
            </div>

            <div class="row">
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="form-label">API Key *</label>
                  <input type="text" name="api_key" class="form-control" value="<?= htmlspecialchars($lab['api_key']) ?>" required>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="form-label">API Şifresi *</label>
                  <input type="password" name="api_password" class="form-control" placeholder="Boş bırakırsanız eski şifre korunur">
                </div>
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label">Açıklama</label>
              <textarea name="description" class="form-control" rows="3" placeholder="Laboratuvar hakkında açıklama..."><?= htmlspecialchars($lab['description'] ?? '') ?></textarea>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
            <button type="submit" class="btn btn-primary">
              <i class="bi bi-check-circle" style="margin-right: 6px;"></i> Güncelle
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
<?php endforeach; ?>

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

<?php
// Test connection function
function testLabServiceConnection($api_url, $username, $api_key, $api_password) {
  $ch = curl_init();
  curl_setopt_array($ch, [
    CURLOPT_URL => $api_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
    CURLOPT_CONNECTTIMEOUT => 5,
    CURLOPT_USERPWD => $username . ':' . $api_password,
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
    CURLOPT_HTTPHEADER => ['Authorization: Basic ' . base64_encode($username . ':' . $api_password)],
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false
  ]);

  $response = curl_exec($ch);
  $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $curl_error = curl_error($ch);
  curl_close($ch);

  if (!empty($curl_error)) {
    return [
      'success' => false,
      'error' => 'CURL Hatası: ' . $curl_error
    ];
  }

  if ($http_code >= 200 && $http_code <= 299) {
    return [
      'success' => true,
      'error' => null,
      'status_code' => $http_code
    ];
  } elseif ($http_code === 401 || $http_code === 403) {
    return [
      'success' => false,
      'error' => 'Kimlik doğrulama hatası (HTTP ' . $http_code . '). API Key veya Şifre yanlış olabilir.'
    ];
  } elseif ($http_code === 404) {
    return [
      'success' => false,
      'error' => 'Sunucu bulunamadı (HTTP 404). API Adresi yanlış olabilir.'
    ];
  } elseif ($http_code === 0) {
    return [
      'success' => false,
      'error' => 'Bağlantı kurulamıyor. API adresi erişilebilir durumda değil.'
    ];
  } else {
    return [
      'success' => false,
      'error' => 'Sunucu hatası: HTTP ' . $http_code
    ];
  }
}
?>
