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

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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
  http_response_code(400);
  echo 'Geçersiz hasta';
  exit;
}

$errors = [];
$info = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF';
  } else {
    $national_id = trim($_POST['national_id'] ?? '');
    $first_name  = trim($_POST['first_name'] ?? '');
    $last_name   = trim($_POST['last_name'] ?? '');
    $birth_date  = $_POST['birth_date'] ?? null;
    $gender      = $_POST['gender'] ?? null;
    $blood_type  = $_POST['blood_type'] ?? null;
    $phone       = trim($_POST['phone'] ?? '');
    $email       = trim($_POST['email'] ?? '');
    $address     = trim($_POST['address'] ?? '');
    $city        = trim($_POST['city'] ?? '');
    $district    = trim($_POST['district'] ?? '');
    $notes       = trim($_POST['notes'] ?? '');
    $service_needed = isset($_POST['service_needed']) ? (int)$_POST['service_needed'] : 0;

    $doctor_id = !empty($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : null;
    $institution_id = !empty($_POST['institution_id']) ? (int)$_POST['institution_id'] : null;
    $referral_reason = trim($_POST['referral_reason'] ?? '');
    $referral_date = $_POST['referral_date'] ?? null;

    if (!$first_name) $errors[] = 'Ad gerekli';
    if (!$last_name)  $errors[] = 'Soyad gerekli';

    if (empty($errors)) {
      try {
        $pdo->beginTransaction();
        $upd = $pdo->prepare('UPDATE patients SET national_id=:national_id, first_name=:first_name, last_name=:last_name, birth_date=:birth_date, gender=:gender, blood_type=:blood_type, phone=:phone, email=:email, address=:address, city=:city, district=:district, service_needed=:service_needed, notes=:notes WHERE id=:id');
        $upd->execute([
          ':id' => $id,
          ':national_id' => $national_id ?: null,
          ':first_name' => $first_name,
          ':last_name' => $last_name,
          ':birth_date' => $birth_date ?: null,
          ':gender' => $gender ?: null,
          ':blood_type' => $blood_type ?: null,
          ':phone' => $phone ?: null,
          ':email' => $email ?: null,
          ':address' => $address ?: null,
          ':city' => $city ?: null,
          ':district' => $district ?: null,
          ':service_needed' => $service_needed,
          ':notes' => $notes ?: null,
        ]);

        // Upsert referral
        if ($doctor_id || $institution_id || $referral_reason || $referral_date) {
          $check = $pdo->prepare('SELECT patient_id FROM patient_referrals WHERE patient_id = :id');
          $check->execute([':id' => $id]);
          if ($check->fetchColumn()) {
            $rUpd = $pdo->prepare('UPDATE patient_referrals SET doctor_id=:doctor_id, institution_id=:institution_id, referral_reason=:referral_reason, referral_date=:referral_date WHERE patient_id=:patient_id');
            $rUpd->execute([
              ':patient_id' => $id,
              ':doctor_id' => $doctor_id ?: null,
              ':institution_id' => $institution_id ?: null,
              ':referral_reason' => $referral_reason ?: null,
              ':referral_date' => $referral_date ?: null,
            ]);
          } else {
            $rIns = $pdo->prepare('INSERT INTO patient_referrals (patient_id, doctor_id, institution_id, referral_reason, referral_date) VALUES (:patient_id,:doctor_id,:institution_id,:referral_reason,:referral_date)');
            $rIns->execute([
              ':patient_id' => $id,
              ':doctor_id' => $doctor_id ?: null,
              ':institution_id' => $institution_id ?: null,
              ':referral_reason' => $referral_reason ?: null,
              ':referral_date' => $referral_date ?: null,
            ]);
          }
        }

        // Update relatives
        $pdo->prepare('DELETE FROM patient_relatives WHERE patient_id = :id')->execute([':id' => $id]);
        $rel_count = isset($_POST['relative_count']) ? (int)$_POST['relative_count'] : 0;
        
        for ($i = 0; $i < $rel_count; $i++) {
          $relation = trim($_POST["relative_relation_$i"] ?? '');
          $full_name = trim($_POST["relative_name_$i"] ?? '');
          $rel_phone = trim($_POST["relative_phone_$i"] ?? '');
          $rel_email = trim($_POST["relative_email_$i"] ?? '');
          $rel_address = trim($_POST["relative_address_$i"] ?? '');
          
          if ($full_name) {
            $rIns = $pdo->prepare('INSERT INTO patient_relatives (patient_id, relation, full_name, phone, email, address) VALUES (:patient_id, :relation, :full_name, :phone, :email, :address)');
            $rIns->execute([
              ':patient_id' => $id,
              ':relation' => $relation ?: null,
              ':full_name' => $full_name,
              ':phone' => $rel_phone ?: null,
              ':email' => $rel_email ?: null,
              ':address' => $rel_address ?: null,
            ]);
          }
        }

        // Update notes
        $pdo->prepare('DELETE FROM patient_notes WHERE patient_id = :id')->execute([':id' => $id]);
        $note_count = isset($_POST['note_count']) ? (int)$_POST['note_count'] : 0;
        for ($i = 0; $i < $note_count; $i++) {
          $note_type = trim($_POST["note_type_$i"] ?? 'genel');
          $note_content = trim($_POST["note_content_$i"] ?? '');
          
          if ($note_content) {
            $nIns = $pdo->prepare('INSERT INTO patient_notes (patient_id, note_type, content, created_at) VALUES (:patient_id, :note_type, :content, NOW())');
            $nIns->execute([
              ':patient_id' => $id,
              ':note_type' => $note_type,
              ':content' => $note_content,
            ]);
          }
        }

        $pdo->commit();
        $info = 'Hasta bilgileri güncellendi.';
      } catch (\Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $errors[] = 'Güncelleme başarısız: ' . $e->getMessage();
      }
    }
  }
}

$csrf = Csrf::token();

$st = $pdo->prepare('SELECT p.*, r.doctor_id, r.institution_id, r.referral_reason, r.referral_date FROM patients p LEFT JOIN patient_referrals r ON r.patient_id = p.id WHERE p.id = :id');
$st->execute([':id' => $id]);
$p = $st->fetch();
if (!$p) { echo 'Hasta bulunamadı'; exit; }

$doctors = $pdo->query("SELECT id, full_name FROM doctors WHERE status = 'active' ORDER BY full_name")->fetchAll();
$institutions = $pdo->query("SELECT id, name FROM institutions WHERE status = 'active' ORDER BY name")->fetchAll();

$rels = $pdo->prepare('SELECT relation, full_name, phone, email, address FROM patient_relatives WHERE patient_id = :id');
$rels->execute([':id' => $id]);
$relatives = array_values($rels->fetchAll()); // Re-index array to 0, 1, 2...

// Get patient notes
$notes_st = $pdo->prepare('SELECT note_type, content FROM patient_notes WHERE patient_id = :id ORDER BY created_at DESC');
$notes_st->execute([':id' => $id]);
$patient_notes = array_values($notes_st->fetchAll());

include __DIR__ . '/../header.php';
?>
<style>
  .container{max-width:100%;margin:0;padding:0}
  .patient-page{padding:20px 24px;font-family:'Segoe UI','Helvetica Neue',Arial,sans-serif;background:#f6f8fb}
  .page-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:16px}
  .page-title{display:flex;align-items:center;gap:10px;font-weight:800;font-size:22px;color:#0f172a}
  .page-actions{display:flex;gap:10px;flex-wrap:wrap}
  .page-actions .btn{height:40px;border-radius:999px;font-weight:700;border:1px solid #d7e3f4;color:#0f172a;background:#fff;box-shadow:0 4px 12px rgba(12,20,40,.06);padding:0 14px;display:inline-flex;align-items:center;gap:8px}
  .page-actions .btn-primary{background:linear-gradient(90deg,#34618a,#5b7fa0);color:#fff;border:none}
  .grid{display:grid;grid-template-columns:repeat(3,minmax(280px,1fr));gap:14px}
  @media (max-width:1200px){.grid{grid-template-columns:repeat(2,minmax(260px,1fr))}}
  @media (max-width:768px){.grid{grid-template-columns:1fr}}
  .card{background:#fff;border:1px solid #e6eef6;border-radius:14px;box-shadow:0 6px 20px rgba(12,20,40,.06);padding:16px}
  .card h3{font-size:16px;font-weight:800;color:#0f172a;margin-bottom:14px}
  .row-3{display:grid;grid-template-columns:repeat(3,minmax(160px,1fr));gap:10px}
  .row-2{display:grid;grid-template-columns:repeat(2,minmax(200px,1fr));gap:10px}
  .row-1{display:grid;grid-template-columns:1fr;gap:10px}
  .field{display:flex;flex-direction:column;gap:6px}
  .field label{font-size:13px;color:#334155;font-weight:700}
  .field input,.field select,.field textarea{width:100%;padding:10px 12px;border:1px solid #e6eef6;border-radius:10px;background:#fbfdff;font-size:14px;font-family:inherit;transition:all 0.2s}
  .field input:focus,.field select:focus,.field textarea:focus{border-color:#34618a;background:#fff;outline:none;box-shadow:0 0 0 3px rgba(52,97,138,.1)}
  .field textarea{min-height:100px;resize:vertical}
  .field input[type="date"]{height:44px}
  .relative-row{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;align-items:flex-end;margin-bottom:12px;padding-bottom:12px;border-bottom:1px solid #e6eef6}
  .relative-row:last-of-type{border-bottom:none;margin-bottom:0;padding-bottom:0}
  .relative-row .field{margin:0}
  .relative-row .field label{font-size:12px}
  .relative-row .remove-btn{height:44px;padding:0 12px;background:#fecaca;border:1px solid #fca5a5;border-radius:10px;cursor:pointer;font-weight:700;color:#991b1b;transition:all 0.2s;white-space:nowrap}
  .relative-row .remove-btn:hover{background:#f87171;border-color:#ef4444}
  .add-relative-btn{display:inline-flex;align-items:center;gap:8px;padding:10px 14px;background:#d1fae5;border:1px solid #6ee7b7;border-radius:10px;color:#065f46;font-weight:700;cursor:pointer;transition:all 0.2s;font-size:14px}
  .add-relative-btn:hover{background:#a7f3d0;border-color:#34d399}
  .note-row{display:grid;grid-template-columns:repeat(6,1fr);gap:10px;align-items:flex-end;margin-bottom:12px;padding-bottom:12px;border-bottom:1px solid #e6eef6}
  .note-row:last-of-type{border-bottom:none;margin-bottom:0;padding-bottom:0}
  .note-row .field{margin:0}
  .note-row .field label{font-size:12px}
  .note-row .remove-btn{height:44px;padding:0 12px;background:#fecaca;border:1px solid #fca5a5;border-radius:10px;cursor:pointer;font-weight:700;color:#991b1b;transition:all 0.2s;white-space:nowrap}
  .note-row .remove-btn:hover{background:#f87171;border-color:#ef4444}
  .add-note-btn{display:inline-flex;align-items:center;gap:8px;padding:10px 14px;background:#dbeafe;border:1px solid #93c5fd;border-radius:10px;color:#1e40af;font-weight:700;cursor:pointer;transition:all 0.2s;font-size:14px}
  .add-note-btn:hover{background:#bfdbfe;border-color:#60a5fa}
  .alert-info{background:#dbeafe;border:1px solid #93c5fd;border-radius:10px;padding:12px;color:#1e40af;margin-bottom:16px;font-size:14px}
  .alert-errors{background:#fee2e2;border:1px solid #fca5a5;border-radius:10px;padding:12px;color:#991b1b;margin-bottom:16px}
  .alert-errors div{font-size:14px;margin-bottom:6px}
  .alert-errors div:last-child{margin-bottom:0}
  .actions-bar{display:flex;gap:10px;justify-content:flex-end;margin-top:16px}
  .actions-bar .btn{height:40px;border-radius:999px;font-weight:700;border:1px solid #d7e3f4;color:#0f172a;background:#fff;box-shadow:0 4px 12px rgba(12,20,40,.06);padding:0 16px;display:inline-flex;align-items:center;gap:8px;cursor:pointer;transition:all 0.2s}
  .actions-bar .btn-primary{background:linear-gradient(90deg,#34618a,#5b7fa0);color:#fff;border:none}
  .actions-bar .btn:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(12,20,40,.12)}
</style>

<div class="patient-page">
  <div class="page-head">
    <div class="page-title"><i class="bi bi-pencil-square"></i> Hasta Düzenle</div>
    <div class="page-actions">
      <a href="/HastaModulu/hastaListe.php" class="btn"><i class="bi bi-card-checklist"></i> Liste</a>
      <a href="/HastaModulu/onamArsiv.php?patient_id=<?= (int)$id ?>" class="btn"><i class="bi bi-file-earmark-medical"></i> Belgeler</a>
      <a href="/HastaModulu/hastaDetay.php?id=<?= (int)$id ?>" class="btn"><i class="bi bi-card-text"></i> Detay</a>
    </div>
  </div>

  <?php if($info): ?><div class="alert-info"><?= htmlspecialchars($info) ?></div><?php endif; ?>
  <?php if($errors): ?><div class="alert-errors"><?php foreach($errors as $e) echo '<div>'.htmlspecialchars($e).'</div>'; ?></div><?php endif; ?>

  <form method="post">
    <input type="hidden" name="_csrf" value="<?= htmlspecialchars($csrf) ?>">

    <div class="grid">
      <div class="card">
        <h3>Kimlik</h3>
        <div class="row-3">
          <div class="field">
            <label>TCKN</label>
            <input name="national_id" maxlength="11" value="<?= htmlspecialchars($p['national_id'] ?? '') ?>">
          </div>
          <div class="field">
            <label>Ad *</label>
            <input name="first_name" required value="<?= htmlspecialchars($p['first_name'] ?? '') ?>">
          </div>
          <div class="field">
            <label>Soyad *</label>
            <input name="last_name" required value="<?= htmlspecialchars($p['last_name'] ?? '') ?>">
          </div>
        </div>
        <div class="row-3" style="margin-top:10px">
          <div class="field">
            <label>Doğum</label>
            <input type="date" name="birth_date" value="<?= htmlspecialchars($p['birth_date'] ?? '') ?>">
          </div>
          <div class="field">
            <label>Cinsiyet</label>
            <select name="gender">
              <?php $g = $p['gender'] ?? ''; ?>
              <option value="">Seçiniz</option>
              <option value="male" <?= $g==='male'?'selected':'' ?>>Erkek</option>
              <option value="female" <?= $g==='female'?'selected':'' ?>>Kadın</option>
              <option value="other" <?= $g==='other'?'selected':'' ?>>Diğer</option>
            </select>
          </div>
          <div class="field">
            <label>Kan Grubu</label>
            <?php $bt = $p['blood_type'] ?? ''; ?>
            <select name="blood_type">
              <option value="">Seçiniz</option>
              <?php foreach ([
                'A Rh(+)','A Rh(-)','B Rh(+)','B Rh(-)',
                'AB Rh(+)','AB Rh(-)','O Rh(+)','O Rh(-)'
              ] as $b): ?>
                <option value="<?= $b ?>" <?= ($bt===$b)?'selected':'' ?>><?= $b ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>

      <div class="card">
        <h3>İletişim</h3>
        <div class="row-3">
          <div class="field">
            <label>Telefon</label>
            <input name="phone" value="<?= htmlspecialchars($p['phone'] ?? '') ?>">
          </div>
          <div class="field">
            <label>E-posta</label>
            <input name="email" type="email" value="<?= htmlspecialchars($p['email'] ?? '') ?>">
          </div>
          <div class="field">
            <label>İl</label>
            <input name="city" value="<?= htmlspecialchars($p['city'] ?? '') ?>">
          </div>
        </div>
        <div class="row-3" style="margin-top:10px">
          <div class="field">
            <label>İlçe</label>
            <input name="district" value="<?= htmlspecialchars($p['district'] ?? '') ?>">
          </div>
          <div class="field">
            <label>Adres</label>
            <input name="address" value="<?= htmlspecialchars($p['address'] ?? '') ?>">
          </div>
          <div class="field">
            <label>Servis Durumu</label>
            <?php $svc = (string)($p['service_needed'] ?? '0'); ?>
            <select name="service_needed">
              <option value="0" <?= $svc==='0'?'selected':'' ?>>Kendi imkanları</option>
              <option value="1" <?= $svc==='1'?'selected':'' ?>>Servis ile geliyor</option>
            </select>
          </div>
        </div>
        <div class="row-1" style="margin-top:10px">
          <div class="field">
            <label>Notlar</label>
            <textarea name="notes" rows="3"><?= htmlspecialchars($p['notes'] ?? '') ?></textarea>
          </div>
        </div>
      </div>

      <div class="card" style="grid-column: span 3;">
        <h3>Sevk Bilgileri</h3>
        <div class="row-3">
          <div class="field">
            <label>Doktor</label>
            <select name="doctor_id">
              <option value="">Seçiniz</option>
              <?php $selD = $p['doctor_id'] ?? ''; foreach($doctors as $d): ?>
                <option value="<?= (int)$d['id'] ?>" <?= ((string)$selD === (string)$d['id'])?'selected':'' ?>><?= htmlspecialchars($d['full_name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field">
            <label>Kurum</label>
            <select name="institution_id">
              <option value="">Seçiniz</option>
              <?php $selI = $p['institution_id'] ?? ''; foreach($institutions as $i): ?>
                <option value="<?= (int)$i['id'] ?>" <?= ((string)$selI === (string)$i['id'])?'selected':'' ?>><?= htmlspecialchars($i['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="field">
            <label>Sevk Tarihi</label>
            <input type="date" name="referral_date" value="<?= htmlspecialchars($p['referral_date'] ?? '') ?>">
          </div>
        </div>
        <div class="row-1" style="margin-top:10px">
          <div class="field">
            <label>Sevk Nedeni</label>
            <input name="referral_reason" value="<?= htmlspecialchars($p['referral_reason'] ?? '') ?>">
          </div>
        </div>
      </div>

      <div class="card" style="grid-column: span 3;">
        <h3>Notlar</h3>
        <div id="notes-container">
          <?php if($patient_notes): ?>
            <?php foreach($patient_notes as $idx => $note): ?>
              <div class="note-row">
                <div class="field" style="grid-column: span 2">
                  <label>Not Türü</label>
                  <select name="note_type_<?= $idx ?>">
                    <option value="genel" <?= (($note['note_type'] ?? '') === 'genel') ? 'selected' : '' ?>>Genel</option>
                    <option value="tibbi" <?= (($note['note_type'] ?? '') === 'tibbi') ? 'selected' : '' ?>>Tıbbi</option>
                    <option value="idari" <?= (($note['note_type'] ?? '') === 'idari') ? 'selected' : '' ?>>İdari</option>
                  </select>
                </div>
                <div class="field" style="grid-column: span 3">
                  <label>Not İçeriği</label>
                  <textarea name="note_content_<?= $idx ?>" rows="3"><?= htmlspecialchars($note['content'] ?? '') ?></textarea>
                </div>
                <button type="button" class="remove-btn" onclick="removeNote(this)">SİL</button>
              </div>
            <?php endforeach; ?>
          <?php else: ?>
            <div style="color:#64748b;font-size:14px">Kayıtlı not yok.</div>
          <?php endif; ?>
        </div>
        <button type="button" class="add-note-btn" onclick="addNote()"><i class="bi bi-plus-circle"></i> Not Ekle</button>
      </div>

      <div class="card" style="grid-column: span 3;">
        <h3>Yakın Bilgileri</h3>
        <div id="relatives-container">
          <?php if($relatives): ?>
            <?php foreach($relatives as $idx => $rel): ?>
              <div class="relative-row">
                <div class="field">
                  <label>Yakınlık</label>
                  <select name="relative_relation_<?= $idx ?>">
                    <option value="">Seçiniz</option>
                    <?php foreach(['Eş','Çocuk','Anne','Baba','Kardeş','Diğer'] as $r): ?>
                      <option value="<?= $r ?>" <?= (($rel['relation'] ?? '') === $r) ? 'selected' : '' ?>><?= $r ?></option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="field">
                  <label>Ad Soyad</label>
                  <input type="text" name="relative_name_<?= $idx ?>" value="<?= htmlspecialchars($rel['full_name'] ?? '') ?>">
                </div>
                <div class="field">
                  <label>Telefon</label>
                  <input type="text" name="relative_phone_<?= $idx ?>" value="<?= htmlspecialchars($rel['phone'] ?? '') ?>">
                </div>
                <div class="field">
                  <label>E-posta</label>
                  <input type="email" name="relative_email_<?= $idx ?>" value="<?= htmlspecialchars($rel['email'] ?? '') ?>">
                </div>
                <div class="field">
                  <label>Adres</label>
                  <input type="text" name="relative_address_<?= $idx ?>" value="<?= htmlspecialchars($rel['address'] ?? '') ?>">
                </div>
                <button type="button" class="remove-btn" onclick="removeRelative(this)">SİL</button>
              </div>
            <?php endforeach; ?>
          <?php else: ?>
            <div style="color:#64748b;font-size:14px">Kayıtlı yakın yok.</div>
          <?php endif; ?>
        </div>
        <button type="button" class="add-relative-btn" onclick="addRelative()"><i class="bi bi-plus-circle"></i> Yakın Ekle</button>
      </div>

      <input type="hidden" name="relative_count" id="relative_count" value="<?= count($relatives) ?>">
      <input type="hidden" name="note_count" id="note_count" value="<?= count($patient_notes) ?>">
    
    <div class="actions-bar">
      <a href="/HastaModulu/hastaListe.php" class="btn"><i class="bi bi-chevron-left"></i> Geri</a>
      <button class="btn btn-primary" type="submit"><i class="bi bi-save"></i> Değişiklikleri Kaydet</button>
    </div>
  </form>

  <script>
    function addRelative() {
      const container = document.getElementById('relatives-container');
      const countInput = document.getElementById('relative_count');
      
      // Mevcut satırları say
      const existingRows = container.querySelectorAll('.relative-row').length;
      const count = existingRows;
      
      // Empty state mesajını kaldır
      const emptyMsg = container.querySelector('div[style*="color:#64748b"]');
      if(emptyMsg) emptyMsg.remove();
      
      const row = document.createElement('div');
      row.className = 'relative-row';
      row.innerHTML = `
        <div class="field">
          <label>Yakınlık</label>
          <select name="relative_relation_${count}">
            <option value="">Seçiniz</option>
            <option value="Eş">Eş</option>
            <option value="Çocuk">Çocuk</option>
            <option value="Anne">Anne</option>
            <option value="Baba">Baba</option>
            <option value="Kardeş">Kardeş</option>
            <option value="Diğer">Diğer</option>
          </select>
        </div>
        <div class="field">
          <label>Ad Soyad</label>
          <input type="text" name="relative_name_${count}" placeholder="">
        </div>
        <div class="field">
          <label>Telefon</label>
          <input type="text" name="relative_phone_${count}" placeholder="">
        </div>
        <div class="field">
          <label>E-posta</label>
          <input type="email" name="relative_email_${count}" placeholder="">
        </div>
        <div class="field">
          <label>Adres</label>
          <input type="text" name="relative_address_${count}" placeholder="">
        </div>
        <button type="button" class="remove-btn" onclick="removeRelative(this)">SİL</button>
      `;
      
      container.appendChild(row);
      updateRelativeCount();
    }
    
    function removeRelative(btn) {
      btn.closest('.relative-row').remove();
      updateRelativeCount();
      
      const container = document.getElementById('relatives-container');
      const rows = container.querySelectorAll('.relative-row');
      if(rows.length === 0) {
        const empty = document.createElement('div');
        empty.style.cssText = 'color:#64748b;font-size:14px';
        empty.textContent = 'Kayıtlı yakın yok.';
        container.appendChild(empty);
      }
    }
    
    function updateRelativeCount() {
      const container = document.getElementById('relatives-container');
      const rows = container.querySelectorAll('.relative-row');
      document.getElementById('relative_count').value = rows.length;
    }
    
    function addNote() {
      const container = document.getElementById('notes-container');
      const existingRows = container.querySelectorAll('.note-row').length;
      const count = existingRows;
      
      const emptyMsg = container.querySelector('div[style*="color:#64748b"]');
      if(emptyMsg) emptyMsg.remove();
      
      const row = document.createElement('div');
      row.className = 'note-row';
      row.innerHTML = `
        <div class="field" style="grid-column: span 2">
          <label>Not Türü</label>
          <select name="note_type_${count}">
            <option value="genel">Genel</option>
            <option value="tibbi">Tıbbi</option>
            <option value="idari">İdari</option>
          </select>
        </div>
        <div class="field" style="grid-column: span 3">
          <label>Not İçeriği</label>
          <textarea name="note_content_${count}" placeholder="Not yazınız..."></textarea>
        </div>
        <button type="button" class="remove-btn" onclick="removeNote(this)">SİL</button>
      `;
      
      container.appendChild(row);
      updateNoteCount();
    }
    
    function removeNote(btn) {
      btn.closest('.note-row').remove();
      updateNoteCount();
      
      const container = document.getElementById('notes-container');
      const rows = container.querySelectorAll('.note-row');
      if(rows.length === 0) {
        const empty = document.createElement('div');
        empty.style.cssText = 'color:#64748b;font-size:14px';
        empty.textContent = 'Kayıtlı not yok.';
        container.appendChild(empty);
      }
    }
    
    function updateNoteCount() {
      const container = document.getElementById('notes-container');
      const rows = container.querySelectorAll('.note-row');
      document.getElementById('note_count').value = rows.length;
    }
    
    // Update count before submit
    document.querySelector('form').addEventListener('submit', function(e) {
      updateRelativeCount();
      updateNoteCount();
    });
  </script>
</div>
<?php include __DIR__ . '/../footer.php'; ?>
