<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) { session_start(); }

$root = realpath(__DIR__ . '/..');
if (!$root) { $root = realpath(__DIR__); }

/* Auth resolver */
$authCandidates = [
  $root . '/auth.php',
  $root . '/core/auth.php',
  $root . '/includes/auth.php',
  $root . '/inc/auth.php',
  $root . '/middleware/auth.php',
];
$authLoaded = false;
foreach ($authCandidates as $p) {
  if (is_file($p)) { require_once $p; $authLoaded = true; break; }
}
if (!$authLoaded) {
  $uid = (int)($_SESSION['user_id'] ?? 0);
  if ($uid <= 0) { header('Location: login.php'); exit; }
}

/* DB */
require_once $root . '/core/db.php';
if (!isset($pdo) || !($pdo instanceof PDO)) {
  http_response_code(500);
  exit('PDO bulunamadı. core/db.php içinde $pdo olmalı.');
}

/* Helpers */
if (!function_exists('e')) {
  function e(?string $s): string { return htmlspecialchars((string)($s ?? ''), ENT_QUOTES, 'UTF-8'); }
}
function fetch_all(PDO $pdo, string $sql): array {
  try { return $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC) ?: []; }
  catch(Throwable $e){ return []; }
}

/* Data */
$sgk_tipleri   = fetch_all($pdo, "SELECT id, ad FROM sgk_tipleri WHERE is_active=1 ORDER BY ad");
$kurumlar      = fetch_all($pdo, "SELECT id, ad FROM kurumlar WHERE is_active=1 ORDER BY ad");
$damar_yollari = fetch_all($pdo, "SELECT id, ad FROM damar_yolu_tanimlari WHERE is_active=1 ORDER BY ad");
$alerjiler     = fetch_all($pdo, "SELECT id, ad FROM alerji_tanimlari WHERE is_active=1 ORDER BY ad");
$kronikler     = fetch_all($pdo, "SELECT id, ad FROM kronik_hastalik_tanimlari WHERE is_active=1 ORDER BY ad");
$riskler       = fetch_all($pdo, "SELECT id, ad FROM risk_uyari_tanimlari WHERE is_active=1 ORDER BY ad");
$hepatitler    = fetch_all($pdo, "SELECT id, ad FROM hepatit_tanimlari WHERE is_active=1 ORDER BY ad");

/* Flash + CSRF */
$flash_ok  = $_SESSION['flash_ok']  ?? null;
$flash_err = $_SESSION['flash_err'] ?? null;
unset($_SESSION['flash_ok'], $_SESSION['flash_err']);

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$csrf = (string)$_SESSION['csrf'];

/* Topbar include */
$current_page = 'hasta-ekle';
$topbarPath = null;
$topbarCandidates = [
  __DIR__ . '/topbar.php',
  $root . '/topbar.php',
  $root . '/includes/topbar.php',
  $root . '/partials/topbar.php',
  $root . '/layout/topbar.php',
  $root . '/components/topbar.php',
];
foreach ($topbarCandidates as $p) {
  if (is_file($p)) { $topbarPath = $p; break; }
}
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Yeni Hasta Kaydı - Medisys Sağlık Yönetimi</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
  <style>
  :root {
    --primary-color: #2563eb;
    --primary-light: #dbeafe;
    --secondary-color: #475569;
    --accent-color: #0ea5e9;
    --success-color: #10b981;
    --warning-color: #f59e0b;
    --danger-color: #ef4444;
    --light-color: #f8fafc;
    --dark-color: #1e293b;
    --border-color: #e2e8f0;
    --card-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    --hover-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    --transition: all 0.2s ease-in-out;
  }
  
  * {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }
  
  body {
    font-family: 'Inter', 'Segoe UI', system-ui, -apple-system, sans-serif;
    background-color: #f1f5f9;
    color: #334155;
    line-height: 1.5;
    min-height: 100vh;
  }
  
  a {
    text-decoration: none;
    color: inherit;
  }
  
  .container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  /* Header */
  .page-header {
    background: white;
    border-bottom: 1px solid var(--border-color);
    padding: 1.5rem 0;
    margin-bottom: 2rem;
  }
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
  }
  
  .page-title {
    font-size: 1.75rem;
    font-weight: 700;
    color: var(--dark-color);
    display: flex;
    align-items: center;
    gap: 0.75rem;
  }
  
  .page-title i {
    color: var(--primary-color);
  }
  
  .page-subtitle {
    color: var(--secondary-color);
    font-size: 0.95rem;
    margin-top: 0.25rem;
  }
  
  .header-actions {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
  }
  
  .btn {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.625rem 1.25rem;
    border-radius: 8px;
    font-weight: 500;
    font-size: 0.875rem;
    cursor: pointer;
    transition: var(--transition);
    border: 1px solid transparent;
  }
  
  .btn-outline {
    background: white;
    border-color: var(--border-color);
    color: var(--secondary-color);
  }
  
  .btn-outline:hover {
    background: #f8fafc;
    border-color: #cbd5e1;
  }
  
  .btn-primary {
    background: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
  }
  
  .btn-primary:hover {
    background: #1d4ed8;
    box-shadow: var(--hover-shadow);
  }
  
  .btn-success {
    background: var(--success-color);
    color: white;
    border-color: var(--success-color);
  }
  
  .btn-success:hover {
    background: #0da271;
  }
  
  /* Alert */
  .alert {
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.75rem;
  }
  
  .alert-success {
    background-color: #d1fae5;
    color: #065f46;
    border-left: 4px solid var(--success-color);
  }
  
  .alert-error {
    background-color: #fee2e2;
    color: #991b1b;
    border-left: 4px solid var(--danger-color);
  }
  
  /* Form Layout */
  .form-container {
    display: grid;
    grid-template-columns: 280px 1fr 300px;
    gap: 1.5rem;
    margin-bottom: 3rem;
  }
  
  @media (max-width: 1200px) {
    .form-container {
      grid-template-columns: 250px 1fr;
    }
    
    .summary-panel {
      display: none;
    }
  }
  
  @media (max-width: 768px) {
    .form-container {
      grid-template-columns: 1fr;
    }
    
    .form-steps {
      order: 2;
    }
  }
  
  /* Steps Navigation */
  .form-steps {
    position: sticky;
    top: 1.5rem;
  }
  
  .steps-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: var(--card-shadow);
  }
  
  .steps-title {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 1.25rem;
    color: var(--dark-color);
    display: flex;
    align-items: center;
    gap: 0.5rem;
  }
  
  .steps-list {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .step-item {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.875rem;
    border-radius: 8px;
    cursor: pointer;
    transition: var(--transition);
    color: var(--secondary-color);
  }
  
  .step-item:hover {
    background: #f1f5f9;
  }
  
  .step-item.active {
    background: var(--primary-light);
    color: var(--primary-color);
    font-weight: 500;
  }
  
  .step-number {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background: #e2e8f0;
    color: var(--secondary-color);
    font-size: 0.75rem;
    font-weight: 600;
  }
  
  .step-item.active .step-number {
    background: var(--primary-color);
    color: white;
  }
  
  .step-name {
    font-size: 0.875rem;
  }
  
  .form-help {
    margin-top: 1.25rem;
    padding-top: 1rem;
    border-top: 1px solid var(--border-color);
    color: #64748b;
    font-size: 0.8125rem;
    line-height: 1.4;
  }
  
  /* Form Sections */
  .form-section {
    display: none;
    background: white;
    border-radius: 12px;
    padding: 1.75rem;
    box-shadow: var(--card-shadow);
    margin-bottom: 1.5rem;
  }
  
  .form-section.active {
    display: block;
    animation: fadeIn 0.3s ease-in-out;
  }
  
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 1.5rem;
    flex-wrap: wrap;
    gap: 1rem;
  }
  
  .section-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--dark-color);
  }
  
  .section-description {
    color: var(--secondary-color);
    font-size: 0.875rem;
    margin-top: 0.25rem;
  }
  
  .section-badge {
    background: var(--primary-light);
    color: var(--primary-color);
    padding: 0.375rem 0.75rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 0.375rem;
  }
  
  /* Form Fields */
  .form-grid {
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    gap: 1rem;
  }
  
  .field-group {
    margin-bottom: 1rem;
  }
  
  .field-group label {
    display: block;
    font-size: 0.875rem;
    font-weight: 500;
    margin-bottom: 0.375rem;
    color: var(--dark-color);
  }
  
  .field-group label.required::after {
    content: " *";
    color: var(--danger-color);
  }
  
  .field-group input,
  .field-group select,
  .field-group textarea {
    width: 100%;
    padding: 0.75rem;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 0.875rem;
    transition: var(--transition);
    background: white;
  }
  
  .field-group input:focus,
  .field-group select:focus,
  .field-group textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
  }
  
  .field-group textarea {
    min-height: 100px;
    resize: vertical;
  }
  
  .col-12 { grid-column: span 12; }
  .col-6 { grid-column: span 6; }
  .col-4 { grid-column: span 4; }
  .col-3 { grid-column: span 3; }
  
  @media (max-width: 768px) {
    .col-6, .col-4, .col-3 {
      grid-column: span 12;
    }
  }
  
  /* Repeatable Sections */
  .repeatable-section {
    border: 1px dashed var(--border-color);
    border-radius: 8px;
    padding: 1.25rem;
    margin-bottom: 1rem;
    background: #f8fafc;
  }
  
  .repeatable-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
  }
  
  .repeatable-title {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--secondary-color);
  }
  
  .btn-remove {
    background: #fee2e2;
    color: var(--danger-color);
    border: none;
    border-radius: 6px;
    padding: 0.375rem 0.75rem;
    font-size: 0.75rem;
    cursor: pointer;
    transition: var(--transition);
  }
  
  .btn-remove:hover {
    background: #fecaca;
  }
  
  /* Chip Selection */
  .chip-container {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    padding: 1rem;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    max-height: 200px;
    overflow-y: auto;
  }
  
  .chip-item {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    background: #f1f5f9;
    border: 1px solid #e2e8f0;
    border-radius: 20px;
    padding: 0.5rem 0.875rem;
    font-size: 0.8125rem;
    cursor: pointer;
    transition: var(--transition);
  }
  
  .chip-item:hover {
    background: #e2e8f0;
  }
  
  .chip-item input[type="checkbox"] {
    margin: 0;
    accent-color: var(--primary-color);
  }
  
  /* Form Navigation */
  .form-navigation {
    display: flex;
    justify-content: space-between;
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 1px solid var(--border-color);
  }
  
  /* Summary Panel */
  .summary-panel {
    position: sticky;
    top: 1.5rem;
  }
  
  .summary-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: var(--card-shadow);
  }
  
  .summary-title {
    font-size: 1rem;
    font-weight: 600;
    margin-bottom: 1.25rem;
    color: var(--dark-color);
  }
  
  .summary-items {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
    margin-bottom: 1.5rem;
  }
  
  .summary-item {
    display: flex;
    flex-direction: column;
    padding: 0.875rem;
    border-radius: 8px;
    background: #f8fafc;
  }
  
  .summary-label {
    font-size: 0.75rem;
    color: var(--secondary-color);
    margin-bottom: 0.25rem;
  }
  
  .summary-value {
    font-size: 0.875rem;
    font-weight: 500;
    color: var(--dark-color);
  }
  
  .summary-actions {
    display: flex;
    gap: 0.5rem;
  }
  
  .summary-actions .btn {
    flex: 1;
    justify-content: center;
  }
  
  /* Mobile Actions Bar */
  .mobile-actions-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    border-top: 1px solid var(--border-color);
    padding: 1rem;
    display: none;
    z-index: 100;
  }
  
  @media (max-width: 768px) {
    .mobile-actions-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .mobile-summary {
      display: flex;
      gap: 1rem;
      overflow-x: auto;
    }
    
    .mobile-summary-item {
      min-width: 120px;
      padding: 0.5rem;
      background: #f8fafc;
      border-radius: 8px;
    }
    
    .mobile-summary-label {
      font-size: 0.75rem;
      color: var(--secondary-color);
    }
    
    .mobile-summary-value {
      font-size: 0.875rem;
      font-weight: 500;
    }
    
    .mobile-navigation {
      display: flex;
      gap: 0.5rem;
    }
  }
  
  /* Utility Classes */
  .text-muted {
    color: #64748b;
  }
  
  .text-small {
    font-size: 0.8125rem;
  }
  
  .mb-2 {
    margin-bottom: 0.5rem;
  }
  
  .mb-3 {
    margin-bottom: 1rem;
  }
  
  .mt-3 {
    margin-top: 1rem;
  }
  
  .d-flex {
    display: flex;
  }
  
  .align-center {
    align-items: center;
  }
  
  .justify-between {
    justify-content: space-between;
  }
  
  .gap-1 {
    gap: 0.5rem;
  }
  
  .gap-2 {
    gap: 1rem;
  }
  </style>
</head>
<body>
  
  <!-- TOPBAR -->
  <?php if ($topbarPath): ?>
    <?php include $topbarPath; ?>
  <?php endif; ?>
  
  <div class="page-header">
    <div class="container">
      <div class="header-content">
        <div>
          <h1 class="page-title">
            <i class="bi bi-person-plus-fill"></i> Yeni Hasta Kaydı
          </h1>
          <p class="page-subtitle">Hasta bilgilerini adım adım ekleyin ve kaydedin</p>
        </div>
        <div class="header-actions">
          <a href="dashboard.php" class="btn btn-outline">
            <i class="bi bi-speedometer2"></i> Dashboard
          </a>
          <a href="hasta-listesi.php" class="btn btn-primary">
            <i class="bi bi-people-fill"></i> Hasta Listesi
          </a>
        </div>
      </div>
    </div>
  </div>
  
  <div class="container">
    <?php if ($flash_ok): ?>
      <div class="alert alert-success">
        <i class="bi bi-check-circle-fill"></i> <?= e($flash_ok) ?>
      </div>
    <?php endif; ?>
    
    <?php if ($flash_err): ?>
      <div class="alert alert-error">
        <i class="bi bi-exclamation-triangle-fill"></i> <?= e($flash_err) ?>
      </div>
    <?php endif; ?>
    
    <form method="post" action="transactions/hasta-kaydet.php" enctype="multipart/form-data" id="hastaForm" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
      
      <div class="form-container">
        <!-- Steps Navigation -->
        <div class="form-steps">
          <div class="steps-card">
            <h3 class="steps-title">
              <i class="bi bi-list-ol"></i> Kayıt Adımları
            </h3>
            <div class="steps-list">
              <div class="step-item active" data-step="kimlik">
                <span class="step-number">1</span>
                <span class="step-name">Kimlik Bilgileri</span>
              </div>
              <div class="step-item" data-step="iletisim">
                <span class="step-number">2</span>
                <span class="step-name">İletişim & Adres</span>
              </div>
              <div class="step-item" data-step="yakin">
                <span class="step-number">3</span>
                <span class="step-name">Yakınlar / Acil</span>
              </div>
              <div class="step-item" data-step="sigorta">
                <span class="step-number">4</span>
                <span class="step-name">Sigorta & Kurum</span>
              </div>
              <div class="step-item" data-step="klinik">
                <span class="step-number">5</span>
                <span class="step-name">Klinik Özet</span>
              </div>
              <div class="step-item" data-step="diyaliz">
                <span class="step-number">6</span>
                <span class="step-name">Diyaliz Profili</span>
              </div>
              <div class="step-item" data-step="belge">
                <span class="step-number">7</span>
                <span class="step-name">Belgeler</span>
              </div>
            </div>
            <div class="form-help">
              <i class="bi bi-info-circle"></i> Sadece zorunlu alanları doldurarak hızlı kayıt yapabilir, detayları sonra tamamlayabilirsiniz.
            </div>
          </div>
        </div>
        
        <!-- Form Sections -->
        <div class="form-content">
          <!-- Kimlik Section -->
          <section class="form-section active" id="section-kimlik">
            <div class="section-header">
              <div>
                <h2 class="section-title">Kimlik Bilgileri</h2>
                <p class="section-description">Hastanın temel kimlik bilgilerini girin</p>
              </div>
              <div class="section-badge" id="ageBadge">
                <i class="bi bi-calendar3"></i> Yaş: <span id="ageValue">-</span>
              </div>
            </div>
            
            <div class="form-grid">
              <div class="field-group col-4">
                <label for="tc_no" class="required">TC Kimlik No</label>
                <input type="text" id="tc_no" name="tc_no" maxlength="11" inputmode="numeric" placeholder="11 haneli TC no" required>
              </div>
              
              <div class="field-group col-4">
                <label for="dosya_no">Dosya No</label>
                <input type="text" id="dosya_no" name="dosya_no" placeholder="Merkez dosya numarası">
              </div>
              
              <div class="field-group col-4">
                <label for="durum">Durum</label>
                <select id="durum" name="durum">
                  <option value="aktif" selected>Aktif</option>
                  <option value="pasif">Pasif</option>
                  <option value="nakil">Nakil</option>
                  <option value="vefat">Vefat</option>
                  <option value="arsiv">Arşiv</option>
                </select>
              </div>
              
              <div class="field-group col-4">
                <label for="ad" class="required">Ad</label>
                <input type="text" id="ad" name="ad" placeholder="Hastanın adı" required>
              </div>
              
              <div class="field-group col-4">
                <label for="soyad" class="required">Soyad</label>
                <input type="text" id="soyad" name="soyad" placeholder="Hastanın soyadı" required>
              </div>
              
              <div class="field-group col-4">
                <label for="cinsiyet">Cinsiyet</label>
                <select id="cinsiyet" name="cinsiyet">
                  <option value="Belirsiz" selected>Belirsiz</option>
                  <option value="E">Erkek</option>
                  <option value="K">Kadın</option>
                  <option value="Diger">Diğer</option>
                </select>
              </div>
              
              <div class="field-group col-4">
                <label for="dogum_tarihi">Doğum Tarihi</label>
                <input type="date" id="dogum_tarihi" name="dogum_tarihi">
              </div>
              
              <div class="col-12">
                <div class="form-navigation">
                  <div></div>
                  <button type="button" class="btn btn-primary" data-next="iletisim">
                    İleri <i class="bi bi-arrow-right"></i>
                  </button>
                </div>
              </div>
            </div>
          </section>
          
          <!-- İletişim Section -->
          <section class="form-section" id="section-iletisim">
            <div class="section-header">
              <div>
                <h2 class="section-title">İletişim & Adres Bilgileri</h2>
                <p class="section-description">Hastanın iletişim bilgilerini ve adreslerini girin</p>
              </div>
              <button type="button" class="btn btn-outline" id="addAddressBtn">
                <i class="bi bi-plus-lg"></i> Adres Ekle
              </button>
            </div>
            
            <div class="form-grid mb-3">
              <div class="field-group col-4">
                <label for="telefon1" class="required">Telefon 1</label>
                <input type="tel" id="telefon1" name="telefon1" placeholder="05xx xxx xx xx" required>
              </div>
              
              <div class="field-group col-4">
                <label for="telefon2">Telefon 2</label>
                <input type="tel" id="telefon2" name="telefon2" placeholder="Opsiyonel">
              </div>
              
              <div class="field-group col-4">
                <label for="email">E-posta</label>
                <input type="email" id="email" name="email" placeholder="ornek@email.com">
              </div>
            </div>
            
            <h4 class="mb-2">Adres Bilgileri</h4>
            <div id="addressList">
              <div class="repeatable-section">
                <div class="repeatable-header">
                  <div class="repeatable-title">Adres 1</div>
                  <button type="button" class="btn-remove remove-address" style="display:none;">
                    <i class="bi bi-trash"></i> Sil
                  </button>
                </div>
                
                <div class="form-grid">
                  <div class="field-group col-3">
                    <label>Adres Tipi</label>
                    <select name="adres_tip[]">
                      <option value="ikamet" selected>İkamet</option>
                      <option value="fatura">Fatura</option>
                      <option value="diger">Diğer</option>
                    </select>
                  </div>
                  
                  <div class="field-group col-3">
                    <label>İl</label>
                    <input name="adres_il[]" placeholder="İl">
                  </div>
                  
                  <div class="field-group col-3">
                    <label>İlçe</label>
                    <input name="adres_ilce[]" placeholder="İlçe">
                  </div>
                  
                  <div class="field-group col-3">
                    <label>Posta Kodu</label>
                    <input name="adres_posta_kodu[]" placeholder="35xxx">
                  </div>
                  
                  <div class="field-group col-12">
                    <label>Açık Adres</label>
                    <textarea name="adres_acik[]" placeholder="Sokak, mahalle, apartman no..."></textarea>
                  </div>
                  
                  <div class="field-group col-12">
                    <label class="d-flex align-center gap-1">
                      <input type="checkbox" name="adres_is_default[]" value="1" checked>
                      Varsayılan adres olarak ayarla
                    </label>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="kimlik">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="button" class="btn btn-primary" data-next="yakin">
                İleri <i class="bi bi-arrow-right"></i>
              </button>
            </div>
          </section>
          
          <!-- Yakınlar Section -->
          <section class="form-section" id="section-yakin">
            <div class="section-header">
              <div>
                <h2 class="section-title">Yakınlar / Acil Durum İletişim</h2>
                <p class="section-description">Acil durumda aranacak kişilerin bilgilerini girin</p>
              </div>
              <button type="button" class="btn btn-outline" id="addKinBtn">
                <i class="bi bi-plus-lg"></i> Yakın Ekle
              </button>
            </div>
            
            <div id="kinList">
              <div class="repeatable-section">
                <div class="repeatable-header">
                  <div class="repeatable-title">Yakın 1</div>
                  <button type="button" class="btn-remove remove-kin" style="display:none;">
                    <i class="bi bi-trash"></i> Sil
                  </button>
                </div>
                
                <div class="form-grid">
                  <div class="field-group col-6">
                    <label>Ad Soyad</label>
                    <input name="yakin_ad_soyad[]" placeholder="Yakının adı soyadı">
                  </div>
                  
                  <div class="field-group col-6">
                    <label>Yakınlık Derecesi</label>
                    <input name="yakinlik[]" placeholder="Eşi, oğlu, kardeşi...">
                  </div>
                  
                  <div class="field-group col-4">
                    <label>Telefon</label>
                    <input name="yakin_telefon[]" placeholder="05xx xxx xx xx">
                  </div>
                  
                  <div class="field-group col-4">
                    <label>Telefon 2</label>
                    <input name="yakin_telefon2[]" placeholder="Opsiyonel">
                  </div>
                  
                  <div class="field-group col-4">
                    <label>E-posta</label>
                    <input type="email" name="yakin_email[]" placeholder="ornek@email.com">
                  </div>
                  
                  <div class="field-group col-12">
                    <label>Adres</label>
                    <textarea name="yakin_adres[]" placeholder="Yakının adresi"></textarea>
                  </div>
                  
                  <div class="field-group col-12">
                    <div class="d-flex align-center justify-between gap-2">
                      <label class="d-flex align-center gap-1">
                        <input type="checkbox" name="yakin_is_acil[]" value="1">
                        Acil durumda aranacak
                      </label>
                      <label class="d-flex align-center gap-1">
                        <input type="checkbox" name="yakin_is_vasi[]" value="1">
                        Vasi
                      </label>
                    </div>
                  </div>
                  
                  <div class="field-group col-12">
                    <label>Not</label>
                    <textarea name="yakin_not[]" placeholder="Ek bilgiler..."></textarea>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="iletisim">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="button" class="btn btn-primary" data-next="sigorta">
                İleri <i class="bi bi-arrow-right"></i>
              </button>
            </div>
          </section>
          
          <!-- Sigorta Section -->
          <section class="form-section" id="section-sigorta">
            <div class="section-header">
              <div>
                <h2 class="section-title">Sigorta & Kurum Bilgileri</h2>
                <p class="section-description">Hastanın sigorta ve bağlı olduğu kurum bilgileri</p>
              </div>
            </div>
            
            <div class="form-grid">
              <div class="field-group col-6">
                <label for="sgk_tipi_id">SGK Tipi</label>
                <select id="sgk_tipi_id" name="sgk_tipi_id">
                  <option value="">Seçiniz</option>
                  <?php foreach($sgk_tipleri as $x): ?>
                    <option value="<?= (int)$x['id'] ?>"><?= e((string)$x['ad']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              
              <div class="field-group col-6">
                <label for="kurum_id">Kurum</label>
                <select id="kurum_id" name="kurum_id">
                  <option value="">Seçiniz</option>
                  <?php foreach($kurumlar as $x): ?>
                    <option value="<?= (int)$x['id'] ?>"><?= e((string)$x['ad']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              
              <div class="field-group col-4">
                <label for="sicil_no">Sicil No</label>
                <input type="text" id="sicil_no" name="sicil_no" placeholder="Kurum sicil no">
              </div>
              
              <div class="field-group col-4">
                <label for="provizyon_no">Provizyon No</label>
                <input type="text" id="provizyon_no" name="provizyon_no" placeholder="Provizyon numarası">
              </div>
              
              <div class="field-group col-4">
                <label for="sigorta_not">Sigorta Durumu</label>
                <input type="text" id="sigorta_not" name="sigorta_not" placeholder="Özel durum varsa">
              </div>
              
              <div class="field-group col-12">
                <label for="sigorta_notlar">Notlar</label>
                <textarea id="sigorta_notlar" name="sigorta_notlar" placeholder="Sigorta ile ilgili ek açıklamalar"></textarea>
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="yakin">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="button" class="btn btn-primary" data-next="klinik">
                İleri <i class="bi bi-arrow-right"></i>
              </button>
            </div>
          </section>
          
          <!-- Klinik Section -->
          <section class="form-section" id="section-klinik">
            <div class="section-header">
              <div>
                <h2 class="section-title">Klinik Özet</h2>
                <p class="section-description">Hastanın klinik bilgilerini ve özel durumlarını girin</p>
              </div>
            </div>
            
            <div class="form-grid">
              <div class="field-group col-12">
                <label>Alerjiler</label>
                <div class="chip-container">
                  <?php if($alerjiler): ?>
                    <?php foreach($alerjiler as $x): ?>
                      <label class="chip-item">
                        <input type="checkbox" name="alerji_ids[]" value="<?= (int)$x['id'] ?>">
                        <?= e((string)$x['ad']) ?>
                      </label>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <div class="text-muted">Tanımlı alerji bulunmamaktadır.</div>
                  <?php endif; ?>
                </div>
              </div>
              
              <div class="field-group col-12">
                <label>Kronik Hastalıklar</label>
                <div class="chip-container">
                  <?php if($kronikler): ?>
                    <?php foreach($kronikler as $x): ?>
                      <label class="chip-item">
                        <input type="checkbox" name="kronik_ids[]" value="<?= (int)$x['id'] ?>">
                        <?= e((string)$x['ad']) ?>
                      </label>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <div class="text-muted">Tanımlı kronik hastalık bulunmamaktadır.</div>
                  <?php endif; ?>
                </div>
              </div>
              
              <div class="field-group col-12">
                <label>Risk Uyarıları</label>
                <div class="chip-container">
                  <?php if($riskler): ?>
                    <?php foreach($riskler as $x): ?>
                      <label class="chip-item">
                        <input type="checkbox" name="risk_ids[]" value="<?= (int)$x['id'] ?>">
                        <?= e((string)$x['ad']) ?>
                      </label>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <div class="text-muted">Tanımlı risk uyarısı bulunmamaktadır.</div>
                  <?php endif; ?>
                </div>
              </div>
              
              <div class="field-group col-12 mt-3">
                <label>Seroloji Sonuçları</label>
                <div class="form-grid">
                  <?php if($hepatitler): ?>
                    <?php foreach($hepatitler as $x): ?>
                      <div class="field-group col-4">
                        <label><?= e((string)$x['ad']) ?></label>
                        <select name="sero_sonuc[<?= (int)$x['id'] ?>]">
                          <option value="bilinmiyor" selected>Bilinmiyor</option>
                          <option value="negatif">Negatif</option>
                          <option value="pozitif">Pozitif</option>
                          <option value="belirsiz">Belirsiz</option>
                        </select>
                        <div class="mt-3">
                          <input type="date" name="sero_tarih[<?= (int)$x['id'] ?>]" class="text-small" style="width:100%">
                        </div>
                      </div>
                    <?php endforeach; ?>
                  <?php else: ?>
                    <div class="col-12 text-muted">Tanımlı seroloji testi bulunmamaktadır.</div>
                  <?php endif; ?>
                </div>
              </div>
              
              <div class="field-group col-12">
                <label for="ilaclar">İlaçlar</label>
                <textarea id="ilaclar" name="ilaclar" placeholder="Kullandığı ilaçlar ve dozları"></textarea>
              </div>
              
              <div class="field-group col-12">
                <label for="serbest_not">Serbest Not</label>
                <textarea id="serbest_not" name="serbest_not" placeholder="Diğer klinik notlar"></textarea>
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="sigorta">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="button" class="btn btn-primary" data-next="diyaliz">
                İleri <i class="bi bi-arrow-right"></i>
              </button>
            </div>
          </section>
          
          <!-- Diyaliz Section -->
          <section class="form-section" id="section-diyaliz">
            <div class="section-header">
              <div>
                <h2 class="section-title">Diyaliz Profili</h2>
                <p class="section-description">Hastanın diyaliz tedavi bilgilerini girin</p>
              </div>
            </div>
            
            <div class="form-grid">
              <div class="field-group col-4">
                <label for="diyaliz_baslangic">Başlangıç Tarihi</label>
                <input type="date" id="diyaliz_baslangic" name="diyaliz_baslangic">
              </div>
              
              <div class="field-group col-4">
                <label for="modality">Modalite</label>
                <select id="modality" name="modality">
                  <option value="HD" selected>HD</option>
                  <option value="HDF">HDF</option>
                  <option value="PD">PD</option>
                  <option value="HomeHD">HomeHD</option>
                  <option value="Diger">Diğer</option>
                </select>
              </div>
              
              <div class="field-group col-4">
                <label for="damar_yolu_id">Damar Yolu</label>
                <select id="damar_yolu_id" name="damar_yolu_id">
                  <option value="">Seçiniz</option>
                  <?php foreach($damar_yollari as $x): ?>
                    <option value="<?= (int)$x['id'] ?>"><?= e((string)$x['ad']) ?></option>
                  <?php endforeach; ?>
                </select>
              </div>
              
              <div class="field-group col-3">
                <label for="kuru_agirlik">Kuru Ağırlık (kg)</label>
                <input type="number" step="0.1" id="kuru_agirlik" name="kuru_agirlik" placeholder="68.5">
              </div>
              
              <div class="field-group col-3">
                <label for="hedef_uf">Hedef UF (L)</label>
                <input type="number" step="0.1" id="hedef_uf" name="hedef_uf" placeholder="2.5">
              </div>
              
              <div class="field-group col-3">
                <label for="seans_suresi_dk">Seans Süresi (dk)</label>
                <input type="number" id="seans_suresi_dk" name="seans_suresi_dk" placeholder="240">
              </div>
              
              <div class="field-group col-3">
                <label for="damar_lokasyon">Damar Lokasyon</label>
                <input type="text" id="damar_lokasyon" name="damar_lokasyon" placeholder="Sol kol">
              </div>
              
              <div class="field-group col-12">
                <label for="heparin_not">Heparin Protokolü</label>
                <textarea id="heparin_not" name="heparin_not" placeholder="Heparin dozu ve uygulama bilgileri"></textarea>
              </div>
              
              <div class="field-group col-12">
                <label for="ozel_uyarilar">Özel Uyarılar</label>
                <textarea id="ozel_uyarilar" name="ozel_uyarilar" placeholder="Tedavi sırasında dikkat edilecek hususlar"></textarea>
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="klinik">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="button" class="btn btn-primary" data-next="belge">
                İleri <i class="bi bi-arrow-right"></i>
              </button>
            </div>
          </section>
          
          <!-- Belgeler Section -->
          <section class="form-section" id="section-belge">
            <div class="section-header">
              <div>
                <h2 class="section-title">Belge Yükleme</h2>
                <p class="section-description">Hasta dosyasına eklemek için belgeleri yükleyin</p>
              </div>
            </div>
            
            <div class="form-grid">
              <div class="field-group col-12">
                <label for="dosyalar">Dosyalar</label>
                <input type="file" id="dosyalar" name="dosyalar[]" multiple>
                <div class="text-small text-muted mt-1">Birden fazla dosya seçebilirsiniz (PDF, JPEG, PNG)</div>
              </div>
              
              <div class="field-group col-12">
                <label for="belge_aciklama">Belge Açıklaması</label>
                <input type="text" id="belge_aciklama" name="belge_aciklama" placeholder="Belge içeriği hakkında açıklama">
              </div>
            </div>
            
            <div class="form-navigation">
              <button type="button" class="btn btn-outline" data-prev="diyaliz">
                <i class="bi bi-arrow-left"></i> Geri
              </button>
              <button type="submit" class="btn btn-success">
                <i class="bi bi-check-circle"></i> Kaydı Tamamla
              </button>
            </div>
          </section>
        </div>
        
        <!-- Summary Panel -->
        <div class="summary-panel">
          <div class="summary-card">
            <h3 class="summary-title">Özet</h3>
            
            <div class="summary-items">
              <div class="summary-item">
                <div class="summary-label">Hasta Adı</div>
                <div class="summary-value" id="summaryName">-</div>
              </div>
              
              <div class="summary-item">
                <div class="summary-label">Telefon</div>
                <div class="summary-value" id="summaryPhone">-</div>
              </div>
              
              <div class="summary-item">
                <div class="summary-label">TC No (Son 4)</div>
                <div class="summary-value" id="summaryTc">-</div>
              </div>
              
              <div class="summary-item">
                <div class="summary-label">Yaş</div>
                <div class="summary-value" id="summaryAge">-</div>
              </div>
              
              <div class="summary-item">
                <div class="summary-label">Adres Sayısı</div>
                <div class="summary-value" id="summaryAddressCount">1</div>
              </div>
              
              <div class="summary-item">
                <div class="summary-label">Yakın Sayısı</div>
                <div class="summary-value" id="summaryKinCount">1</div>
              </div>
            </div>
            
            <div class="summary-actions">
              <button type="button" class="btn btn-outline" id="prevStepBtn">
                <i class="bi bi-arrow-left"></i>
              </button>
              <button type="button" class="btn btn-outline" id="nextStepBtn">
                <i class="bi bi-arrow-right"></i>
              </button>
              <button type="submit" class="btn btn-success">
                <i class="bi bi-save"></i> Kaydet
              </button>
            </div>
            
            <div class="form-help mt-3">
              <i class="bi bi-lightbulb"></i> Tüm bilgileri doldurmadan da kayıt yapabilirsiniz. Eksik bilgileri sonradan güncelleyebilirsiniz.
            </div>
          </div>
        </div>
      </div>
      
      <!-- Mobile Actions Bar -->
      <div class="mobile-actions-bar">
        <div class="mobile-summary">
          <div class="mobile-summary-item">
            <div class="mobile-summary-label">Hasta</div>
            <div class="mobile-summary-value" id="mobileSummaryName">-</div>
          </div>
          <div class="mobile-summary-item">
            <div class="mobile-summary-label">Telefon</div>
            <div class="mobile-summary-value" id="mobileSummaryPhone">-</div>
          </div>
        </div>
        <div class="mobile-navigation">
          <button type="button" class="btn btn-outline" id="prevStepMobileBtn">
            <i class="bi bi-arrow-left"></i>
          </button>
          <button type="button" class="btn btn-outline" id="nextStepMobileBtn">
            <i class="bi bi-arrow-right"></i>
          </button>
          <button type="submit" class="btn btn-success">
            <i class="bi bi-check"></i>
          </button>
        </div>
      </div>
    </form>
  </div>

<script>
document.addEventListener('DOMContentLoaded', function() {
  // Form navigation
  const steps = document.querySelectorAll('.step-item');
  const sections = document.querySelectorAll('.form-section');
  const stepOrder = Array.from(steps).map(step => step.dataset.step);
  
  function activateStep(step) {
    // Update steps
    steps.forEach(s => {
      s.classList.toggle('active', s.dataset.step === step);
    });
    
    // Update sections
    sections.forEach(section => {
      section.classList.toggle('active', section.id === `section-${step}`);
    });
    
    // Scroll to top on mobile
    if (window.innerWidth <= 768) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  }
  
  // Step click handlers
  steps.forEach(step => {
    step.addEventListener('click', () => {
      activateStep(step.dataset.step);
    });
  });
  
  // Next/Prev button handlers
  document.querySelectorAll('[data-next]').forEach(btn => {
    btn.addEventListener('click', () => {
      activateStep(btn.dataset.next);
    });
  });
  
  document.querySelectorAll('[data-prev]').forEach(btn => {
    btn.addEventListener('click', () => {
      activateStep(btn.dataset.prev);
    });
  });
  
  // Quick navigation buttons
  function getCurrentStepIndex() {
    const activeStep = document.querySelector('.step-item.active');
    return stepOrder.indexOf(activeStep?.dataset.step || 'kimlik');
  }
  
  function goToNextStep() {
    const currentIndex = getCurrentStepIndex();
    if (currentIndex < stepOrder.length - 1) {
      activateStep(stepOrder[currentIndex + 1]);
    }
  }
  
  function goToPrevStep() {
    const currentIndex = getCurrentStepIndex();
    if (currentIndex > 0) {
      activateStep(stepOrder[currentIndex - 1]);
    }
  }
  
  document.getElementById('prevStepBtn')?.addEventListener('click', goToPrevStep);
  document.getElementById('nextStepBtn')?.addEventListener('click', goToNextStep);
  document.getElementById('prevStepMobileBtn')?.addEventListener('click', goToPrevStep);
  document.getElementById('nextStepMobileBtn')?.addEventListener('click', goToNextStep);
  
  // Age calculation
  const dobInput = document.getElementById('dogum_tarihi');
  const ageBadge = document.getElementById('ageBadge');
  const ageValue = document.getElementById('ageValue');
  
  function calculateAge() {
    const dob = dobInput?.value;
    if (!dob) {
      ageValue.textContent = '-';
      return;
    }
    
    const birthDate = new Date(dob);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    
    ageValue.textContent = age >= 0 ? age : '-';
    updateSummary();
  }
  
  if (dobInput) {
    dobInput.addEventListener('change', calculateAge);
  }
  
  // Summary updates
  const tcInput = document.getElementById('tc_no');
  const nameInput = document.getElementById('ad');
  const surnameInput = document.getElementById('soyad');
  const phoneInput = document.getElementById('telefon1');
  
  function updateSummary() {
    // Name
    const name = nameInput?.value || '';
    const surname = surnameInput?.value || '';
    const fullName = name || surname ? `${name} ${surname}`.trim() : '-';
    
    document.getElementById('summaryName').textContent = fullName;
    document.getElementById('mobileSummaryName').textContent = fullName;
    
    // Phone
    const phone = phoneInput?.value || '-';
    document.getElementById('summaryPhone').textContent = phone;
    document.getElementById('mobileSummaryPhone').textContent = phone;
    
    // TC (last 4 digits)
    const tc = tcInput?.value?.replace(/\D/g, '') || '';
    const tcLast4 = tc.length >= 4 ? `****${tc.slice(-4)}` : '-';
    document.getElementById('summaryTc').textContent = tcLast4;
    
    // Age
    const dob = dobInput?.value;
    if (dob) {
      const birthDate = new Date(dob);
      const today = new Date();
      let age = today.getFullYear() - birthDate.getFullYear();
      const monthDiff = today.getMonth() - birthDate.getMonth();
      
      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
        age--;
      }
      
      document.getElementById('summaryAge').textContent = age >= 0 ? age : '-';
    } else {
      document.getElementById('summaryAge').textContent = '-';
    }
    
    // Address count
    const addressCount = document.querySelectorAll('.repeatable-section.nl-address-item, .repeatable-section:has([name^="adres_tip"])').length;
    document.getElementById('summaryAddressCount').textContent = addressCount;
    
    // Kin count
    const kinCount = document.querySelectorAll('.repeatable-section.nl-kin-item, .repeatable-section:has([name^="yakin_ad_soyad"])').length;
    document.getElementById('summaryKinCount').textContent = kinCount;
  }
  
  // Phone formatting
  function formatPhoneNumber(input) {
    let value = input.value.replace(/\D/g, '');
    if (value.length > 11) value = value.substring(0, 11);
    
    if (value.length <= 4) {
      input.value = value;
    } else if (value.length <= 7) {
      input.value = `${value.substring(0, 4)} ${value.substring(4)}`;
    } else if (value.length <= 9) {
      input.value = `${value.substring(0, 4)} ${value.substring(4, 7)} ${value.substring(7)}`;
    } else {
      input.value = `${value.substring(0, 4)} ${value.substring(4, 7)} ${value.substring(7, 9)} ${value.substring(9)}`;
    }
  }
  
  if (phoneInput) {
    phoneInput.addEventListener('input', function() {
      formatPhoneNumber(this);
      updateSummary();
    });
  }
  
  // Initialize summary
  [tcInput, nameInput, surnameInput, phoneInput, dobInput].forEach(input => {
    if (input) {
      input.addEventListener('input', updateSummary);
    }
  });
  
  // Dynamic address addition
  const addAddressBtn = document.getElementById('addAddressBtn');
  const addressList = document.getElementById('addressList');
  
  if (addAddressBtn && addressList) {
    addAddressBtn.addEventListener('click', function() {
      const addressItems = addressList.querySelectorAll('.repeatable-section');
      const newIndex = addressItems.length + 1;
      
      const template = addressItems[0].cloneNode(true);
      template.querySelector('.repeatable-title').textContent = `Adres ${newIndex}`;
      template.querySelector('.remove-address').style.display = 'block';
      
      // Clear inputs
      template.querySelectorAll('input, textarea, select').forEach(input => {
        if (input.type === 'checkbox') {
          input.checked = false;
        } else if (input.type !== 'file') {
          input.value = '';
        }
      });
      
      addressList.appendChild(template);
      updateSummary();
      
      // Scroll to new address
      template.scrollIntoView({ behavior: 'smooth', block: 'center' });
    });
  }
  
  // Dynamic kin addition
  const addKinBtn = document.getElementById('addKinBtn');
  const kinList = document.getElementById('kinList');
  
  if (addKinBtn && kinList) {
    addKinBtn.addEventListener('click', function() {
      const kinItems = kinList.querySelectorAll('.repeatable-section');
      const newIndex = kinItems.length + 1;
      
      const template = kinItems[0].cloneNode(true);
      template.querySelector('.repeatable-title').textContent = `Yakın ${newIndex}`;
      template.querySelector('.remove-kin').style.display = 'block';
      
      // Clear inputs
      template.querySelectorAll('input, textarea, select').forEach(input => {
        if (input.type === 'checkbox') {
          input.checked = false;
        } else if (input.type !== 'file') {
          input.value = '';
        }
      });
      
      kinList.appendChild(template);
      updateSummary();
      
      // Scroll to new kin
      template.scrollIntoView({ behavior: 'smooth', block: 'center' });
    });
  }
  
  // Remove buttons
  document.addEventListener('click', function(e) {
    if (e.target.closest('.remove-address')) {
      const addressItems = addressList.querySelectorAll('.repeatable-section');
      if (addressItems.length > 1) {
        e.target.closest('.repeatable-section').remove();
        updateSummary();
      } else {
        alert('En az bir adres bilgisi olmalıdır.');
      }
    }
    
    if (e.target.closest('.remove-kin')) {
      const kinItems = kinList.querySelectorAll('.repeatable-section');
      if (kinItems.length > 1) {
        e.target.closest('.repeatable-section').remove();
        updateSummary();
      } else {
        alert('En az bir yakın bilgisi olmalıdır.');
      }
    }
  });
  
  // Initialize
  updateSummary();
  calculateAge();
});
</script>

</body>
</html>