<?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();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!Csrf::verify($_POST['_csrf'] ?? '')) {
    $errors[] = 'Geçersiz CSRF token. Lütfen tekrar deneyin.';
  } 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;

    $rel_relation = trim($_POST['rel_relation'] ?? '');
    $rel_full_name = trim($_POST['rel_full_name'] ?? '');
    $rel_phone = trim($_POST['rel_phone'] ?? '');
    $rel_email = trim($_POST['rel_email'] ?? '');
    $rel_address = trim($_POST['rel_address'] ?? '');

    $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 alanı zorunludur';
    if (!$last_name)  $errors[] = 'Soyad alanı zorunludur';
    if ($national_id && !preg_match('/^\d{11}$/', $national_id)) {
      $errors[] = 'TCKN 11 haneli olmalıdır';
    }
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $errors[] = 'Geçerli bir e-posta adresi girin';
    }
    if ($rel_email && !filter_var($rel_email, FILTER_VALIDATE_EMAIL)) {
      $errors[] = 'Yakın için geçerli bir e-posta adresi girin';
    }

    if (empty($errors)) {
      try {
        $pdo->beginTransaction();

        $insP = $pdo->prepare('INSERT INTO patients (national_id, first_name, last_name, birth_date, gender, blood_type, phone, email, address, city, district, service_needed, notes)
                               VALUES (:national_id,:first_name,:last_name,:birth_date,:gender,:blood_type,:phone,:email,:address,:city,:district,:service_needed,:notes)');
        $insP->execute([
          ':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,
        ]);
        $patient_id = (int)$pdo->lastInsertId();

        if ($rel_full_name) {
          $insR = $pdo->prepare('INSERT INTO patient_relatives (patient_id, relation, full_name, phone, email, address)
                                 VALUES (:patient_id,:relation,:full_name,:phone,:email,:address)');
          $insR->execute([
            ':patient_id' => $patient_id,
            ':relation' => $rel_relation ?: 'Yakın',
            ':full_name' => $rel_full_name,
            ':phone' => $rel_phone ?: null,
            ':email' => $rel_email ?: null,
            ':address' => $rel_address ?: null,
          ]);
        }

        if ($doctor_id || $institution_id) {
          $insRef = $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)');
          $insRef->execute([
            ':patient_id' => $patient_id,
            ':doctor_id' => $doctor_id ?: null,
            ':institution_id' => $institution_id ?: null,
            ':referral_reason' => $referral_reason ?: null,
            ':referral_date' => $referral_date ?: null,
          ]);
        }

        $pdo->commit();
        $success = true;
        $info = '<i class="bi bi-check-circle me-2"></i> Hasta kaydı başarıyla oluşturuldu. Hasta ID: ' . $patient_id;

        if ($success) { $_POST = []; }
      } catch (\Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $errors[] = 'Kayıt işlemi sırasında bir hata oluştu: ' . $e->getMessage();
      }
    }
  }
}

$csrf = Csrf::token();

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

include __DIR__ . '/../header.php';
?>

<style>
/* ✅ Bu sayfada header.php içinde Bootstrap container varsa full width */
.container, .container-sm, .container-md, .container-lg, .container-xl, .container-xxl {
  max-width: 100% !important;
  width: 100% !important;
}

:root{
  --primary:#1a56db;
  --primary2:#1e40af;
  --ink:#0f172a;
  --muted:#64748b;
  --bg:#f6f8fc;
  --card:#ffffff;
  --border:#e5e7eb;
  --success:#059669;
  --danger:#dc2626;
  --shadow: 0 1px 3px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.04);
  --shadow2: 0 14px 28px rgba(0,0,0,.10);
  --r: 14px;
}

.patient-page{
  width:100% !important;
  max-width:none !important;
  margin:0 !important;
  padding: 20px 26px;
  background: var(--bg);
  min-height: calc(100vh - 64px);
}

/* Header block */
.page-title-section{
  border-bottom:1px solid var(--border);
  padding-bottom:16px;
  margin-bottom:18px;
}

.page-title{
  display:flex;
  align-items:center;
  gap:10px;
  margin:0 0 6px 0;
  font-size:26px;
  font-weight:800;
  color:var(--ink);
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-title .bi{
  color:var(--primary);
  font-size:22px;            /* ✅ ikon ağırlığı/ölçeği sabit */
  line-height:1;
}

.page-subtitle{
  margin:0;
  color:var(--muted);
  font-size:14px;
  line-height:1.5;
}

/* ✅ Toolbar: ikon ve yazı sayfa bütünlüğünde aynı çizgide */
.toolbar{
  margin-top:14px;
  display:flex;
  justify-content:space-between;
  align-items:center;
  flex-wrap:wrap;
  gap:10px;
}

.toolbar > div:first-child {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.toolbtn{
  display:inline-flex;
  align-items:center;
  gap:9px;
  padding:10px 12px;
  border-radius:12px;
  border:1px solid var(--border);
  background: rgba(255,255,255,.9);
  color: var(--ink);
  text-decoration:none;
  font-weight:700;
  font-size:13px;
  transition: transform .15s, box-shadow .15s, border-color .15s, background .15s;
  box-shadow: var(--shadow);
  font-family:'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  white-space: nowrap;
}

.toolbtn .bi{
  font-size:16px;            /* ✅ tüm toolbar ikonları aynı */
  color: var(--primary);
  line-height:1;
}

.toolbtn:hover{
  transform: translateY(-1px);
  box-shadow: var(--shadow2);
  border-color: rgba(26,86,219,.35);
}

.toolbtn.secondary .bi{ color:#0f172a; }
.toolbtn.secondary{ background: #ffffff; }

.toolbtn.primary{
  background: var(--primary);
  border-color: var(--primary);
  color:#fff;
}
.toolbtn.primary .bi{ color:#fff; }
.toolbtn.primary:hover{ background: var(--primary2); border-color: var(--primary2); }

/* Alerts */
.alert{
  padding: 14px 14px;
  border-radius: var(--r);
  margin-bottom: 16px;
  display:flex;
  gap:10px;
  align-items:flex-start;
  border:1px solid transparent;
}
.alert .bi{ font-size:18px; margin-top:2px; }
.alert-success{ background:#f0fdf4; border-color:#bbf7d0; color:var(--success); }
.alert-danger{ background:#fef2f2; border-color:#fecaca; color:var(--danger); }

/* Grid */
.form-grid{
  display:grid;
  grid-template-columns: 1.1fr 1fr 1fr;
  gap:18px;
}
@media (max-width: 1200px){ .form-grid{ grid-template-columns:1fr 1fr; } }
@media (max-width: 820px){ .form-grid{ grid-template-columns:1fr; } }

.form-section{
  background: var(--card);
  border: 1px solid rgba(229,231,235,.9);
  border-radius: var(--r);
  padding: 18px;
  box-shadow: var(--shadow);
  transition: transform .15s, box-shadow .15s;
}
.form-section:hover{ transform: translateY(-1px); box-shadow: var(--shadow2); }

.section-header{
  display:flex;
  align-items:center;
  gap:10px;
  padding-bottom:12px;
  margin-bottom:14px;
  border-bottom:1px solid rgba(229,231,235,.9);
}
.section-header .bi{ color: var(--primary); font-size:18px; }
.section-title{ margin:0; font-size:16px; font-weight:800; color:var(--ink); }

.counter{
  margin-left:auto;
  background:#f1f5f9;
  border:1px solid rgba(226,232,240,.9);
  border-radius:999px;
  padding:4px 10px;
  font-size:12px;
  color:#475569;
}

.form-row{
  display:grid;
  grid-template-columns: repeat(12, 1fr);
  gap:12px;
  margin-bottom:12px;
}
.form-group{ grid-column: span 6; }
.form-group.full-width{ grid-column:1 / -1; }
@media (max-width:820px){ .form-group{ grid-column:1 / -1; } }

.form-group label{
  display:block;
  margin-bottom:6px;
  font-weight:700;
  color:#334155;
  font-size:13px;
}
.form-group label.required::after{ content:" *"; color:var(--danger); }

.form-control{
  width:100%;
  padding:11px 12px;
  border:1px solid var(--border);
  border-radius:12px;
  font-size:14px;
  background:#fff;
  transition:border-color .15s, box-shadow .15s;
}
.form-control:focus{
  outline:none;
  border-color: rgba(26,86,219,.65);
  box-shadow: 0 0 0 3px rgba(26,86,219,.12);
}
.form-control.error{ border-color: var(--danger); }

.help-text{
  display:block;
  margin-top:6px;
  font-size:12px;
  color:var(--muted);
}

select.form-control{
  appearance:none;
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%236b7280' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
  background-repeat:no-repeat;
  background-position:right 12px center;
  background-size:16px;
  padding-right:40px;
}

.quick-add-buttons{ margin-top:8px; display:flex; gap:8px; flex-wrap:wrap; }
.quick-add-btn{
  padding:6px 10px;
  font-size:12px;
  border-radius:12px;
  background:#f8fafc;
  border:1px solid rgba(226,232,240,.9);
  color:var(--ink);
  display:inline-flex;
  align-items:center;
  gap:6px;
  text-decoration:none;
}
.quick-add-btn .bi{ font-size:14px; color:var(--primary); }
.quick-add-btn:hover{ border-color: rgba(26,86,219,.35); box-shadow: var(--shadow); }

/* ✅ Sticky actions */
.form-actions{
  position: sticky;
  bottom: 12px;
  z-index: 10;
  background: rgba(255,255,255,.92);
  backdrop-filter: blur(10px);
  border: 1px solid var(--border);
  border-radius: var(--r);
  padding: 14px 14px;
  margin-top: 18px;
  box-shadow: var(--shadow2);
  display:flex;
  justify-content:space-between;
  align-items:center;
  gap:12px;
}
.form-actions-left, .form-actions-right{ display:flex; gap:10px; flex-wrap:wrap; }

.btn{
  padding:10px 14px;
  border-radius:12px;
  font-weight:800;
  font-size:13px;
  display:inline-flex;
  align-items:center;
  gap:8px;
  border:1px solid transparent;
  cursor:pointer;
  text-decoration:none;
  transition: transform .15s, box-shadow .15s, background .15s, border-color .15s;
}

.btn-outline{
  background:#fff;
  color: var(--ink);
  border-color: var(--border);
}
.btn-outline .bi{ color: var(--primary); font-size:16px; }
.btn-outline:hover{ transform: translateY(-1px); box-shadow: var(--shadow); border-color: rgba(26,86,219,.35); }

.btn-primary{
  background: var(--primary);
  color:#fff;
  border-color: var(--primary);
  box-shadow: 0 10px 20px rgba(26,86,219,.18);
}
.btn-primary .bi{ color:#fff; font-size:16px; }
.btn-primary:hover{ background: var(--primary2); border-color: var(--primary2); transform: translateY(-1px); }

@media (max-width:768px){
  .patient-page{ padding:14px; }
  .form-actions{ position:static; backdrop-filter:none; }
  .toolbtn, .btn{ width:100%; justify-content:center; }
  .form-actions-left, .form-actions-right{ width:100%; justify-content:center; }
}
</style>

<div class="patient-page">

  <div class="page-title-section">
    <h1 class="page-title">
      <i class="bi bi-person-plus-fill"></i>
      Yeni Hasta Kaydı
    </h1>
    <p class="page-subtitle">
      Hastanın demografik, iletişim ve tıbbi bilgilerini eksiksiz doldurunuz.
    </p>

    <!-- ✅ Toolbar: ikon+metin sayfa bütünlüğünde aynı -->
    <div class="toolbar">
      <div>
        <a href="/HastaModulu/hastaListe.php" class="toolbtn secondary">
          <i class="bi bi-card-checklist"></i>
          Hasta Listesi
        </a>
        <a href="/SistemModulu/doktor-tanimlari.php" class="toolbtn secondary">
          <i class="bi bi-person-vcard"></i>
          Doktor Tanımları
        </a>
        <a href="/SistemModulu/kurum-tanimlari.php" class="toolbtn secondary">
          <i class="bi bi-buildings"></i>
          Kurum Tanımları
        </a>
      </div>
      <a href="/HastaModulu/hastaEkle.php" class="toolbtn primary">
        <i class="bi bi-plus-circle"></i>
        Yeni Hasta Ekle
      </a>
    </div>
  </div>

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

  <?php if($errors): ?>
    <div class="alert alert-danger">
      <i class="bi bi-exclamation-triangle"></i>
      <div>
        <strong>Lütfen aşağıdaki hataları düzeltin:</strong>
        <?php foreach($errors as $e): ?>
          <div style="margin-top:4px;">• <?= htmlspecialchars($e) ?></div>
        <?php endforeach; ?>
      </div>
    </div>
  <?php endif; ?>

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

    <div class="form-grid">
      <!-- Kimlik Bilgileri -->
      <div class="form-section">
        <div class="section-header">
          <i class="bi bi-person-badge"></i>
          <h3 class="section-title">Kimlik Bilgileri</h3>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label for="national_id" class="required">TC Kimlik No</label>
            <input type="text" id="national_id" name="national_id" class="form-control"
                   value="<?= htmlspecialchars($_POST['national_id'] ?? '') ?>"
                   maxlength="11" placeholder="11 haneli TCKN">
            <span class="help-text">Zorunlu değil, ancak varsa giriniz</span>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="first_name" class="required">Ad</label>
            <input type="text" id="first_name" name="first_name" class="form-control" required
                   value="<?= htmlspecialchars($_POST['first_name'] ?? '') ?>" placeholder="Hastanın adı">
          </div>
          <div class="form-group">
            <label for="last_name" class="required">Soyad</label>
            <input type="text" id="last_name" name="last_name" class="form-control" required
                   value="<?= htmlspecialchars($_POST['last_name'] ?? '') ?>" placeholder="Hastanın soyadı">
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="birth_date">Doğum Tarihi</label>
            <input type="date" id="birth_date" name="birth_date" class="form-control"
                   value="<?= htmlspecialchars($_POST['birth_date'] ?? '') ?>">
          </div>
          <div class="form-group">
            <label for="gender">Cinsiyet</label>
            <select id="gender" name="gender" class="form-control">
              <option value="">Seçiniz</option>
              <option value="male" <?= ($_POST['gender'] ?? '') === 'male' ? 'selected' : '' ?>>Erkek</option>
              <option value="female" <?= ($_POST['gender'] ?? '') === 'female' ? 'selected' : '' ?>>Kadın</option>
              <option value="other" <?= ($_POST['gender'] ?? '') === 'other' ? 'selected' : '' ?>>Diğer</option>
            </select>
          </div>
          <div class="form-group">
            <label for="blood_type">Kan Grubu</label>
            <select id="blood_type" name="blood_type" class="form-control">
              <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 ?>" <?= ($_POST['blood_type'] ?? '') === $b ? 'selected' : '' ?>><?= $b ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
      </div>

      <!-- İletişim Bilgileri -->
      <div class="form-section">
        <div class="section-header">
          <i class="bi bi-telephone"></i>
          <h3 class="section-title">İletişim Bilgileri</h3>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="phone">Telefon</label>
            <input type="tel" id="phone" name="phone" class="form-control"
                   value="<?= htmlspecialchars($_POST['phone'] ?? '') ?>"
                   placeholder="5xx xxx xx xx">
            <span class="help-text">Başında 0 olmadan giriniz</span>
          </div>
          <div class="form-group">
            <label for="email">E-posta</label>
            <input type="email" id="email" name="email" class="form-control"
                   value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" placeholder="ornek@eposta.com">
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="city">İl</label>
            <select id="city" name="city" class="form-control">
              <option value="">Seçiniz</option>
            </select>
          </div>
          <div class="form-group">
            <label for="district">İlçe</label>
            <select id="district" name="district" class="form-control">
              <option value="">Önce il seçin</option>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label for="address">Adres</label>
            <textarea id="address" name="address" class="form-control" rows="2"
                      placeholder="Tam açık adres"><?= htmlspecialchars($_POST['address'] ?? '') ?></textarea>
          </div>
        </div>
      </div>

      <!-- Yakın Bilgileri -->
      <div class="form-section">
        <div class="section-header">
          <i class="bi bi-people"></i>
          <h3 class="section-title">Yakın Bilgileri</h3>
          <span class="counter">Opsiyonel</span>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="rel_relation">Yakınlık Derecesi</label>
            <select id="rel_relation" name="rel_relation" class="form-control">
              <option value="">Seçiniz</option>
              <?php foreach (['Eş','Anne','Baba','Çocuk','Kardeş','Diğer'] as $relation): ?>
                <option value="<?= $relation ?>" <?= ($_POST['rel_relation'] ?? '') === $relation ? 'selected' : '' ?>><?= $relation ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label for="rel_full_name">Ad Soyad</label>
            <input type="text" id="rel_full_name" name="rel_full_name" class="form-control"
                   value="<?= htmlspecialchars($_POST['rel_full_name'] ?? '') ?>" placeholder="Yakının adı soyadı">
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="rel_phone">Telefon</label>
            <input type="tel" id="rel_phone" name="rel_phone" class="form-control"
                   value="<?= htmlspecialchars($_POST['rel_phone'] ?? '') ?>" placeholder="5xx xxx xx xx">
          </div>
          <div class="form-group">
            <label for="rel_email">E-posta</label>
            <input type="email" id="rel_email" name="rel_email" class="form-control"
                   value="<?= htmlspecialchars($_POST['rel_email'] ?? '') ?>" placeholder="ornek@eposta.com">
          </div>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label for="rel_address">Adres</label>
            <textarea id="rel_address" name="rel_address" class="form-control" rows="2"
                      placeholder="Yakının adresi"><?= htmlspecialchars($_POST['rel_address'] ?? '') ?></textarea>
          </div>
        </div>
      </div>

      <!-- Geliş Bilgileri -->
      <div class="form-section">
        <div class="section-header">
          <i class="bi bi-hospital"></i>
          <h3 class="section-title">Geliş Bilgileri</h3>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="service_needed">Servis Durumu</label>
            <select id="service_needed" name="service_needed" class="form-control">
              <option value="0" <?= ($_POST['service_needed'] ?? '0') === '0' ? 'selected' : '' ?>>Kendi imkanları ile geliyor</option>
              <option value="1" <?= ($_POST['service_needed'] ?? '0') === '1' ? 'selected' : '' ?>>Servis ile geliyor</option>
            </select>
          </div>

          <div class="form-group">
            <label for="doctor_id">Sorumlu Doktor</label>
            <select id="doctor_id" name="doctor_id" class="form-control">
              <option value="">Seçiniz</option>
              <?php foreach($doctors as $d): ?>
                <option value="<?= (int)$d['id'] ?>" <?= ((string)($_POST['doctor_id'] ?? '')) === (string)$d['id'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($d['full_name']) ?><?= $d['specialty'] ? ' - ' . htmlspecialchars($d['specialty']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="quick-add-buttons">
              <a href="/SistemModulu/doktor-ekle.php" class="quick-add-btn" target="_blank">
                <i class="bi bi-plus-circle"></i> Yeni Doktor Ekle
              </a>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label for="institution_id">Geldiği Kurum</label>
            <select id="institution_id" name="institution_id" class="form-control">
              <option value="">Seçiniz</option>
              <?php foreach($institutions as $i): ?>
                <option value="<?= (int)$i['id'] ?>" <?= ((string)($_POST['institution_id'] ?? '')) === (string)$i['id'] ? 'selected' : '' ?>>
                  <?= htmlspecialchars($i['name']) ?><?= $i['type'] ? ' - ' . htmlspecialchars($i['type']) : '' ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="quick-add-buttons">
              <a href="/SistemModulu/kurum-ekle.php" class="quick-add-btn" target="_blank">
                <i class="bi bi-plus-circle"></i> Yeni Kurum Ekle
              </a>
            </div>
          </div>

          <div class="form-group">
            <label for="referral_date">Sevk Tarihi</label>
            <input type="date" id="referral_date" name="referral_date" class="form-control"
                   value="<?= htmlspecialchars($_POST['referral_date'] ?? '') ?>">
          </div>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label for="referral_reason">Sevk Nedeni</label>
            <input type="text" id="referral_reason" name="referral_reason" class="form-control"
                   value="<?= htmlspecialchars($_POST['referral_reason'] ?? '') ?>" placeholder="Kısa sevk açıklaması">
          </div>
        </div>
      </div>

      <!-- Notlar -->
      <div class="form-section full-width">
        <div class="section-header">
          <i class="bi bi-journal-text"></i>
          <h3 class="section-title">Notlar</h3>
          <span class="counter">Opsiyonel</span>
        </div>

        <div class="form-row">
          <div class="form-group full-width">
            <label for="notes">Hasta Notları</label>
            <textarea id="notes" name="notes" class="form-control" rows="4"
                      placeholder="Hasta ile ilgili ek notlar, özel durumlar, alerjiler, vs..."><?= htmlspecialchars($_POST['notes'] ?? '') ?></textarea>
            <span class="help-text">Bu alan sadece iç kullanım içindir, hasta tarafından görülmez</span>
          </div>
        </div>
      </div>
    </div>

    <div class="form-actions">
      <div class="form-actions-left">
        <a href="/dashboard.php" class="btn btn-outline">
          <i class="bi bi-arrow-left"></i> Ana Sayfaya Dön
        </a>
        <a href="/HastaModulu/hastaListe.php" class="btn btn-outline">
          <i class="bi bi-list-ul"></i> Hasta Listesi
        </a>
      </div>

      <div class="form-actions-right">
        <button type="reset" class="btn btn-outline">
          <i class="bi bi-eraser"></i> Formu Temizle
        </button>
        <button type="submit" class="btn btn-primary">
          <i class="bi bi-save"></i> Hasta Kaydını Oluştur
        </button>
      </div>
    </div>
  </form>
</div>

<script>
/* İl/ilçe datası aynen sende var: cities objesini burada bırakıyorum (kısaltmadım) */
const cities = <?= json_encode((function(){
  return [
    'Adana'=>['Seyhan','Çukurova','Yüreğir','Sarıçam','Ceyhan','Kozan','İmamoğlu','Karataş','Karaisalı','Pozantı','Feke','Tufanbeyli','Saimbeyli','Aladağ','Yumurtalık'],
    'Adıyaman'=>['Merkez','Besni','Çelikhan','Gerger','Gölbaşı','Kahta','Samsat','Sincik','Tut'],
    'Afyonkarahisar'=>['Merkez','Başmakçı','Bayat','Bolvadin','Çay','Çobanlar','Dazkırı','Dinar','Emirdağ','Evciler','Hocalar','İhsaniye','İscehisar','Kızılören','Sandıklı','Sincanlı','Sultandağı','Şuhut'],
    // ... (senin tüm listeyi buraya aynen koyabilirsin)
    'İzmir'=>['Balçova','Bayraklı','Bornova','Buca','Çiğli','Gaziemir','Güzelbahçe','Karabağlar','Karşıyaka','Konak','Menemen','Aliağa','Bayındır','Bergama','Beydağ','Çeşme','Dikili','Foça','Karaburun','Kemalpaşa','Kınık','Kiraz','Menderes','Narlıdere','Ödemiş','Seferihisar','Selçuk','Tire','Torbalı','Urla'],
  ];
})(), JSON_UNESCAPED_UNICODE) ?>;

const citySelect = document.getElementById('city');
const districtSelect = document.getElementById('district');
const prevCity = "<?= htmlspecialchars($_POST['city'] ?? '') ?>";
const prevDistrict = "<?= htmlspecialchars($_POST['district'] ?? '') ?>";

Object.keys(cities).sort((a,b)=>a.localeCompare(b,'tr')).forEach(city=>{
  const opt=document.createElement('option');
  opt.value=city; opt.textContent=city;
  if(city===prevCity) opt.selected=true;
  citySelect.appendChild(opt);
});

function updateDistricts(){
  const c = citySelect.value;
  districtSelect.innerHTML = '<option value="">Seçiniz</option>';
  if(c && cities[c]){
    cities[c].forEach(d=>{
      const opt=document.createElement('option');
      opt.value=d; opt.textContent=d;
      if(d===prevDistrict) opt.selected=true;
      districtSelect.appendChild(opt);
    });
  }
}
updateDistricts();
citySelect.addEventListener('change', updateDistricts);

/* Telefon */
document.querySelectorAll('input[type="tel"]').forEach(input=>{
  input.addEventListener('input', e=>{
    let v = e.target.value.replace(/\D/g,'').substring(0,10);
    if(!v){ e.target.value=''; return; }
    const p=[v.substring(0,3), v.substring(3,6), v.substring(6,8), v.substring(8,10)].filter(Boolean);
    e.target.value = p.join(' ');
  });
});

/* TCKN */
const tcknInput=document.getElementById('national_id');
if(tcknInput){
  tcknInput.addEventListener('input', e=>{
    e.target.value = e.target.value.replace(/\D/g,'').substring(0,11);
  });
}

/* ✅ Tek submit listener: önce validasyon, sonra "Kaydediliyor..." */
const form=document.getElementById('patientForm');

function validateRequiredFields(){
  const req=form.querySelectorAll('[required]');
  let ok=true;
  req.forEach(i=>{
    if(!i.value.trim()){ i.classList.add('error'); ok=false; }
    else i.classList.remove('error');
  });
  return ok;
}

form.addEventListener('submit', function(e){
  if(!validateRequiredFields()){
    e.preventDefault();
    alert('Lütfen tüm zorunlu alanları doldurunuz.');
    return;
  }
  const submitBtn=form.querySelector('button[type="submit"]');
  if(submitBtn){
    submitBtn.innerHTML = '<i class="bi bi-hourglass-split"></i> Kaydediliyor...';
    submitBtn.disabled = true;
  }
});

form.querySelectorAll('input,select,textarea').forEach(el=>{
  el.addEventListener('input', function(){ this.classList.remove('error'); });
});

/* Tarihler: sadece sevk tarihi max olsun. Doğum tarihi için max iyi, ama ileri tarih olmasın */
const today = new Date().toISOString().split('T')[0];
document.querySelectorAll('#birth_date, #referral_date').forEach(inp => inp.max = today);

/* Quick add yeni sekme */
document.querySelectorAll('.quick-add-btn').forEach(btn=>{
  btn.addEventListener('click', function(e){
    e.preventDefault();
    window.open(this.getAttribute('href'), '_blank', 'width=900,height=700,scrollbars=yes');
  });
});
</script>

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