<?php
declare(strict_types=1);

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

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

/* ---------------------------
   AUTH (esnek)
--------------------------- */
$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 []; }
}

function table_exists(PDO $pdo, string $table): bool {
  $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?");
  $st->execute([$table]);
  return (int)$st->fetchColumn() > 0;
}

function resolve_table(PDO $pdo, array $candidates): ?string {
  foreach ($candidates as $t) {
    if ($t && table_exists($pdo, $t)) return $t;
  }
  return null;
}

function table_columns(PDO $pdo, string $table): array {
  $st = $pdo->prepare("SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?");
  $st->execute([$table]);
  $cols = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
  $out = [];
  foreach ($cols as $c) $out[strtolower((string)$c)] = (string)$c; // map: lower => real
  return $out;
}

function pick_col(array $colsLowerToReal, array $candidates): ?string {
  foreach ($candidates as $c) {
    $key = strtolower((string)$c);
    if (isset($colsLowerToReal[$key])) return $colsLowerToReal[$key];
  }
  return null;
}

function select_alias_or_empty(?string $realCol, string $alias, string $emptyExpr = "''"): string {
  if ($realCol) return "`$realCol` AS `$alias`";
  return "$emptyExpr AS `$alias`";
}

/* ---------------------------
   ID
--------------------------- */
$hasta_id = (int)($_GET['id'] ?? 0);
if ($hasta_id <= 0) { echo "<div style='padding:16px'>Geçersiz hasta.</div>"; exit; }

/* ---------------------------
   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-duzenle';
$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; }
}

/* ---------------------------
   Lookup 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");

/* ---------------------------
   Hasta (ana)
--------------------------- */
$st = $pdo->prepare("SELECT * FROM hastalar WHERE id=? LIMIT 1");
$st->execute([$hasta_id]);
$hasta = $st->fetch(PDO::FETCH_ASSOC);
if (!$hasta) { echo "<div style='padding:16px'>Hasta bulunamadı.</div>"; exit; }

/* ---------------------------
   Tablo resolve
--------------------------- */
$adresTable  = resolve_table($pdo, ['hasta_adresleri','hasta_adres','hastalar_adresleri','hastalar_adres','adresler']);
$yakinTable  = resolve_table($pdo, ['hasta_yakinlari','hasta_yakin','hastalar_yakinlari','yakinlar']);
$sigTable    = resolve_table($pdo, ['hasta_sigorta','hastalar_sigorta']);
$klinikTable = resolve_table($pdo, ['hasta_klinik_ozet','hastalar_klinik_ozet','klinik_ozet']);
$diyTable    = resolve_table($pdo, ['hasta_diyaliz','hastalar_diyaliz','diyaliz']);
$dosyaTable  = resolve_table($pdo, ['hasta_dosyalar','hasta_dokumanlar','hastalar_dosyalar','dokumanlar']);

/* ---------------------------
   Adresler (kolon eşleme ile)
--------------------------- */
$adresler = [];
if ($adresTable) {
  $cols = table_columns($pdo, $adresTable);

  $c_id          = pick_col($cols, ['id','adres_id']);
  $c_hasta_id    = pick_col($cols, ['hasta_id','hastalar_id','patient_id']);
  $c_tip         = pick_col($cols, ['adres_tip','tip','adres_tipi','type']);
  $c_il          = pick_col($cols, ['il','adres_il','city']);
  $c_ilce        = pick_col($cols, ['ilce','adres_ilce','district']);
  $c_mahalle     = pick_col($cols, ['mahalle','semt','neighborhood']);
  $c_posta       = pick_col($cols, ['posta_kodu','postakodu','zip','zip_code']);
  $c_acik        = pick_col($cols, ['acik_adres','adres','adres_detay','detay','tam_adres','full_address']);
  $c_default     = pick_col($cols, ['is_default','varsayilan','default','is_varsayilan','is_primary']);

  // fallback: zorunlu kolonlar yoksa hiç çekmeyelim
  if ($c_hasta_id) {
    $orderParts = [];
    if ($c_default) $orderParts[] = "`$c_default` DESC";
    if ($c_id) $orderParts[] = "`$c_id` DESC";
    $orderSql = $orderParts ? (" ORDER BY " . implode(", ", $orderParts)) : "";

    $sel = [];
    $sel[] = $c_id ? "`$c_id` AS `id`" : "0 AS `id`";
    $sel[] = "`$c_hasta_id` AS `hasta_id`";
    $sel[] = select_alias_or_empty($c_tip, 'adres_tip');
    $sel[] = select_alias_or_empty($c_il, 'il');
    $sel[] = select_alias_or_empty($c_ilce, 'ilce');
    $sel[] = select_alias_or_empty($c_mahalle, 'mahalle');
    $sel[] = select_alias_or_empty($c_posta, 'posta_kodu');
    $sel[] = select_alias_or_empty($c_acik, 'acik_adres');
    $sel[] = $c_default ? "`$c_default` AS `is_default`" : "0 AS `is_default`";

    $sql = "SELECT " . implode(", ", $sel) . " FROM `$adresTable` WHERE `$c_hasta_id` = ? $orderSql";
    $st = $pdo->prepare($sql);
    $st->execute([$hasta_id]);
    $adresler = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
  }
}
if (!$adresler) {
  $adresler = [[
    'adres_tip' => 'ikamet',
    'il' => '', 'ilce' => '', 'mahalle'=>'', 'posta_kodu'=>'', 'acik_adres'=>'',
    'is_default' => 1
  ]];
}

/* ---------------------------
   Yakınlar (kolon eşleme ile)
--------------------------- */
$yakinlar = [];
if ($yakinTable) {
  $cols = table_columns($pdo, $yakinTable);

  $c_id          = pick_col($cols, ['id','yakin_id']);
  $c_hasta_id    = pick_col($cols, ['hasta_id','hastalar_id','patient_id']);
  $c_adsoyad     = pick_col($cols, ['ad_soyad','adsoyad','isim_soyisim','isim']);
  $c_ad          = pick_col($cols, ['ad','isim']);
  $c_soyad       = pick_col($cols, ['soyad','soy_isim','surname']);
  $c_yakinlik    = pick_col($cols, ['yakinlik','yakınlık','iliski','relation']);
  $c_tel1        = pick_col($cols, ['telefon','telefon1','tel','gsm']);
  $c_tel2        = pick_col($cols, ['telefon2','tel2','gsm2']);
  $c_email       = pick_col($cols, ['email','eposta','e_posta']);
  $c_adres       = pick_col($cols, ['adres','acik_adres','adres_detay']);
  $c_is_acil     = pick_col($cols, ['is_acil','acil','is_emergency']);
  $c_is_vasi     = pick_col($cols, ['is_vasi','vasi','is_guardian']);
  $c_notlar      = pick_col($cols, ['notlar','not','aciklama','aciklamalar']);

  if ($c_hasta_id) {
    $orderParts = [];
    if ($c_is_acil) $orderParts[] = "`$c_is_acil` DESC";
    if ($c_id) $orderParts[] = "`$c_id` DESC";
    $orderSql = $orderParts ? (" ORDER BY " . implode(", ", $orderParts)) : "";

    $sel = [];
    $sel[] = $c_id ? "`$c_id` AS `id`" : "0 AS `id`";
    $sel[] = "`$c_hasta_id` AS `hasta_id`";
    $sel[] = select_alias_or_empty($c_adsoyad, 'ad_soyad');
    $sel[] = select_alias_or_empty($c_ad, 'ad', "''");
    $sel[] = select_alias_or_empty($c_soyad, 'soyad', "''");
    $sel[] = select_alias_or_empty($c_yakinlik, 'yakinlik');
    $sel[] = select_alias_or_empty($c_tel1, 'telefon');
    $sel[] = select_alias_or_empty($c_tel2, 'telefon2');
    $sel[] = select_alias_or_empty($c_email, 'email');
    $sel[] = select_alias_or_empty($c_adres, 'adres');
    $sel[] = $c_is_acil ? "`$c_is_acil` AS `is_acil`" : "0 AS `is_acil`";
    $sel[] = $c_is_vasi ? "`$c_is_vasi` AS `is_vasi`" : "0 AS `is_vasi`";
    $sel[] = select_alias_or_empty($c_notlar, 'notlar');

    $sql = "SELECT " . implode(", ", $sel) . " FROM `$yakinTable` WHERE `$c_hasta_id` = ? $orderSql";
    $st = $pdo->prepare($sql);
    $st->execute([$hasta_id]);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

    // ad_soyad yoksa ad + soyad birleştir
    foreach ($rows as $r) {
      $full = trim((string)($r['ad_soyad'] ?? ''));
      if ($full === '') {
        $full = trim(((string)($r['ad'] ?? '')).' '.((string)($r['soyad'] ?? '')));
      }
      $r['ad_soyad'] = $full;
      $yakinlar[] = $r;
    }
  }
}
if (!$yakinlar) {
  $yakinlar = [[
    'ad_soyad'=>'', 'yakinlik'=>'', 'telefon'=>'', 'telefon2'=>'', 'email'=>'',
    'adres'=>'', 'is_acil'=>1, 'is_vasi'=>0, 'notlar'=>''
  ]];
}

/* ---------------------------
   Sigorta / Klinik / Diyaliz
--------------------------- */
$sigorta = null;
if ($sigTable) {
  $st = $pdo->prepare("SELECT * FROM `$sigTable` WHERE hasta_id=? LIMIT 1");
  $st->execute([$hasta_id]);
  $sigorta = $st->fetch(PDO::FETCH_ASSOC) ?: null;
}

$klinik = null;
if ($klinikTable) {
  $st = $pdo->prepare("SELECT * FROM `$klinikTable` WHERE hasta_id=? LIMIT 1");
  $st->execute([$hasta_id]);
  $klinik = $st->fetch(PDO::FETCH_ASSOC) ?: null;
}

$diyaliz = null;
if ($diyTable) {
  $st = $pdo->prepare("SELECT * FROM `$diyTable` WHERE hasta_id=? LIMIT 1");
  $st->execute([$hasta_id]);
  $diyaliz = $st->fetch(PDO::FETCH_ASSOC) ?: null;
}

$dosyalar = [];
if ($dosyaTable) {
  $st = $pdo->prepare("SELECT * FROM `$dosyaTable` WHERE hasta_id=? ORDER BY id DESC LIMIT 20");
  $st->execute([$hasta_id]);
  $dosyalar = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

// hastalar tablosunda durum yoksa boş geç
$hastaDurum = (string)($hasta['durum'] ?? 'aktif');
?>
<!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Hasta Düzenle - <?= e(($hasta['ad'] ?? '').' '.($hasta['soyad'] ?? '')) ?></title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
  <style>
    :root {
      --bg-primary: #f8fafc;
      --bg-secondary: #ffffff;
      --bg-hover: #f1f5f9;
      --bg-active: #e0f2fe;
      --text-primary: #0f172a;
      --text-secondary: #475569;
      --text-muted: #64748b;
      --border: #e2e8f0;
      --border-light: #f1f5f9;
      --primary: #3b82f6;
      --primary-hover: #2563eb;
      --success: #10b981;
      --success-hover: #059669;
      --warning: #f59e0b;
      --danger: #ef4444;
      --danger-hover: #dc2626;
      --radius: 16px;
      --radius-sm: 12px;
      --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
      --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.025);
      --transition: all 0.2s ease;
      --font-sans: 'Segoe UI', system-ui, -apple-system, BlinkMacSystemFont, 'Inter', sans-serif;
    }

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

    body {
      font-family: var(--font-sans);
      background: var(--bg-primary);
      color: var(--text-primary);
      line-height: 1.5;
      min-height: 100vh;
    }

    /* Container & Layout */
    .container {
      width: 100%;
      max-width: 1400px;
      margin: 0 auto;
      padding: 20px;
    }

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

    /* Header */
    .page-header {
      background: var(--bg-secondary);
      border-radius: var(--radius);
      padding: 24px;
      margin-bottom: 24px;
      border: 1px solid var(--border);
      box-shadow: var(--shadow);
    }

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 20px;
      flex-wrap: wrap;
    }

    .patient-title {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 8px;
    }

    .patient-title h1 {
      font-size: 24px;
      font-weight: 700;
      color: var(--text-primary);
    }

    .patient-id {
      background: var(--bg-hover);
      padding: 4px 12px;
      border-radius: 20px;
      font-size: 14px;
      color: var(--text-secondary);
      font-weight: 500;
    }

    .patient-subtitle {
      color: var(--text-muted);
      font-size: 15px;
      margin-top: 4px;
    }

    /* Action Buttons */
    .action-buttons {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }

    .btn {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      padding: 10px 16px;
      border-radius: var(--radius-sm);
      border: 1px solid transparent;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      transition: var(--transition);
      text-decoration: none;
      white-space: nowrap;
    }

    .btn i {
      font-size: 16px;
    }

    .btn-secondary {
      background: var(--bg-secondary);
      border-color: var(--border);
      color: var(--text-secondary);
    }

    .btn-secondary:hover {
      background: var(--bg-hover);
      border-color: var(--border);
      transform: translateY(-1px);
      box-shadow: var(--shadow);
    }

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

    .btn-primary:hover {
      background: var(--primary-hover);
      border-color: var(--primary-hover);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
    }

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

    .btn-success:hover {
      background: var(--success-hover);
      border-color: var(--success-hover);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(16, 185, 129, 0.2);
    }

    /* Alert Messages */
    .alert {
      padding: 16px;
      border-radius: var(--radius-sm);
      margin-bottom: 20px;
      display: flex;
      align-items: flex-start;
      gap: 12px;
      border: 1px solid transparent;
    }

    .alert i {
      margin-top: 2px;
    }

    .alert-success {
      background: rgba(16, 185, 129, 0.1);
      border-color: rgba(16, 185, 129, 0.2);
      color: var(--success);
    }

    .alert-error {
      background: rgba(239, 68, 68, 0.1);
      border-color: rgba(239, 68, 68, 0.2);
      color: var(--danger);
    }

    /* Main Content Grid */
    .main-grid {
      display: grid;
      grid-template-columns: 280px 1fr 320px;
      gap: 24px;
    }

    @media (max-width: 1200px) {
      .main-grid {
        grid-template-columns: 250px 1fr;
      }
      .summary-sidebar {
        display: none;
      }
    }

    @media (max-width: 900px) {
      .main-grid {
        grid-template-columns: 1fr;
      }
      .navigation-sidebar {
        position: static;
      }
    }

    /* Navigation Sidebar */
    .navigation-sidebar {
      position: sticky;
      top: 20px;
      height: fit-content;
    }

    .nav-card {
      background: var(--bg-secondary);
      border-radius: var(--radius);
      padding: 20px;
      border: 1px solid var(--border);
      box-shadow: var(--shadow);
    }

    .nav-title {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 16px;
      font-weight: 700;
      margin-bottom: 20px;
      color: var(--text-primary);
    }

    .step-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .step-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 14px 16px;
      border-radius: var(--radius-sm);
      cursor: pointer;
      transition: var(--transition);
      border: 1px solid transparent;
      user-select: none;
    }

    .step-item:hover {
      background: var(--bg-hover);
    }

    .step-item.active {
      background: var(--bg-active);
      border-color: rgba(59, 130, 246, 0.2);
      color: var(--primary);
      font-weight: 600;
    }

    .step-icon {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--bg-hover);
      border-radius: 10px;
      font-size: 16px;
      color: var(--text-muted);
    }

    .step-item.active .step-icon {
      background: var(--primary);
      color: white;
    }

    .step-text {
      flex: 1;
      font-size: 14px;
    }

    /* Form Content */
    .form-section {
      display: none;
      animation: fadeIn 0.3s ease;
    }

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

    .form-section.active {
      display: block;
    }

    .section-card {
      background: var(--bg-secondary);
      border-radius: var(--radius);
      padding: 28px;
      margin-bottom: 24px;
      border: 1px solid var(--border);
      box-shadow: var(--shadow);
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 24px;
      flex-wrap: wrap;
      gap: 16px;
    }

    .section-title {
      font-size: 18px;
      font-weight: 700;
      color: var(--text-primary);
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .section-description {
      color: var(--text-muted);
      font-size: 14px;
      margin-top: 6px;
    }

    /* Form Grid */
    .form-grid {
      display: grid;
      grid-template-columns: repeat(12, 1fr);
      gap: 16px;
    }

    .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;
      }
    }

    /* Form Fields */
    .form-group {
      margin-bottom: 4px;
    }

    .form-label {
      display: block;
      font-size: 13px;
      font-weight: 600;
      color: var(--text-secondary);
      margin-bottom: 8px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .required {
      color: var(--danger);
      font-weight: 600;
    }

    .form-control {
      width: 100%;
      padding: 12px 16px;
      border: 1px solid var(--border);
      border-radius: var(--radius-sm);
      font-size: 14px;
      font-family: var(--font-sans);
      transition: var(--transition);
      background: var(--bg-secondary);
    }

    .form-control:focus {
      outline: none;
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    select.form-control {
      appearance: none;
      background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 24 24' fill='none' stroke='%2364748b' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
      background-repeat: no-repeat;
      background-position: right 16px center;
      background-size: 16px;
      padding-right: 40px;
    }

    textarea.form-control {
      min-height: 100px;
      resize: vertical;
    }

    .form-help {
      font-size: 12px;
      color: var(--text-muted);
      margin-top: 8px;
      line-height: 1.4;
    }

    /* Repeatable Sections */
    .repeatable-section {
      border: 2px dashed var(--border);
      border-radius: var(--radius);
      padding: 24px;
      margin-bottom: 20px;
      background: rgba(241, 245, 249, 0.3);
    }

    .repeatable-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
    }

    .repeatable-title {
      font-weight: 600;
      color: var(--text-secondary);
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .btn-danger {
      background: rgba(239, 68, 68, 0.1);
      color: var(--danger);
      border: 1px solid rgba(239, 68, 68, 0.2);
      padding: 8px 12px;
      font-size: 13px;
    }

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

    /* Checkbox & Radio */
    .checkbox-group {
      display: flex;
      gap: 20px;
      align-items: center;
    }

    .checkbox-label {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      font-size: 14px;
    }

    .checkbox-label input[type="checkbox"] {
      width: 18px;
      height: 18px;
      border-radius: 4px;
      border: 2px solid var(--border);
      cursor: pointer;
    }

    /* Navigation Buttons */
    .section-navigation {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 32px;
      padding-top: 24px;
      border-top: 1px solid var(--border-light);
    }

    /* Summary Sidebar */
    .summary-sidebar {
      position: sticky;
      top: 20px;
      height: fit-content;
    }

    .summary-card {
      background: var(--bg-secondary);
      border-radius: var(--radius);
      padding: 24px;
      border: 1px solid var(--border);
      box-shadow: var(--shadow);
      margin-bottom: 20px;
    }

    .summary-title {
      font-size: 16px;
      font-weight: 700;
      margin-bottom: 20px;
      color: var(--text-primary);
      display: flex;
      align-items: center;
      gap: 10px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: 1fr;
      gap: 12px;
    }

    .stat-item {
      background: var(--bg-primary);
      border-radius: var(--radius-sm);
      padding: 16px;
      border: 1px solid var(--border-light);
    }

    .stat-label {
      font-size: 13px;
      color: var(--text-muted);
      margin-bottom: 6px;
    }

    .stat-value {
      font-size: 16px;
      font-weight: 700;
      color: var(--text-primary);
    }

    .documents-list {
      margin-top: 20px;
    }

    .document-item {
      padding: 12px;
      border: 1px solid var(--border-light);
      border-radius: var(--radius-sm);
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      gap: 12px;
      transition: var(--transition);
    }

    .document-item:hover {
      background: var(--bg-hover);
      border-color: var(--border);
    }

    .document-icon {
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: var(--bg-active);
      border-radius: 10px;
      color: var(--primary);
      font-size: 18px;
    }

    .document-info {
      flex: 1;
      min-width: 0;
    }

    .document-name {
      font-weight: 600;
      font-size: 14px;
      color: var(--text-primary);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .document-desc {
      font-size: 12px;
      color: var(--text-muted);
      margin-top: 2px;
    }

    /* Mobile Navigation */
    .mobile-navigation {
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      background: var(--bg-secondary);
      border-top: 1px solid var(--border);
      padding: 16px 20px;
      display: none;
      z-index: 1000;
      backdrop-filter: blur(10px);
      box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.05);
    }

    @media (max-width: 900px) {
      .mobile-navigation {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      body {
        padding-bottom: 80px;
      }
    }

    .mobile-step-info {
      font-weight: 600;
      font-size: 14px;
    }

    .mobile-step-title {
      color: var(--text-primary);
    }

    .mobile-step-subtitle {
      color: var(--text-muted);
      font-size: 12px;
    }

    /* Form Section Indicators */
    .section-indicator {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid var(--border-light);
    }

    .step-indicator {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
      color: var(--text-muted);
    }

    .step-indicator.active {
      color: var(--primary);
      font-weight: 600;
    }

    .step-divider {
      color: var(--border);
      margin: 0 4px;
    }

    /* Empty State */
    .empty-state {
      text-align: center;
      padding: 40px 20px;
      color: var(--text-muted);
    }

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

    .empty-state p {
      font-size: 14px;
    }

    /* File Input */
    .file-input-wrapper {
      position: relative;
      overflow: hidden;
      display: inline-block;
      width: 100%;
    }

    .file-input-wrapper input[type=file] {
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
      width: 100%;
      height: 100%;
      cursor: pointer;
    }

    .file-input-label {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 16px;
      border: 2px dashed var(--border);
      border-radius: var(--radius-sm);
      background: var(--bg-primary);
      color: var(--text-secondary);
      text-align: center;
      cursor: pointer;
      transition: var(--transition);
    }

    .file-input-label:hover {
      border-color: var(--primary);
      background: rgba(59, 130, 246, 0.05);
    }
  </style>
</head>
<body>

  <!-- TOPBAR -->
  <?php if ($topbarPath): include $topbarPath; endif; ?>

  <div class="container">
    <!-- Page Header -->
    <div class="page-header">
      <div class="header-content">
        <div>
          <div class="patient-title">
            <h1>Hasta Düzenle</h1>
            <span class="patient-id">#<?= (int)$hasta_id ?></span>
          </div>
          <div class="patient-subtitle">
            <?= e(trim((string)($hasta['ad'] ?? '').' '.($hasta['soyad'] ?? '')) . ' - ' . ($hasta['tc_no'] ?? 'TC yok')) ?> • 
            Son güncelleme: <?= date('d.m.Y H:i', strtotime($hasta['updated_at'] ?? 'now')) ?>
          </div>
        </div>
        <div class="action-buttons">
          <a href="dashboard.php?sayfa=hasta-detay&id=<?= (int)$hasta_id ?>" class="btn btn-secondary">
            <i class="bi bi-arrow-left"></i> Geri Dön
          </a>
          <a href="dashboard.php?sayfa=hasta-listesi" class="btn btn-secondary">
            <i class="bi bi-people"></i> Hasta Listesi
          </a>
          <button type="submit" form="editForm" class="btn btn-primary">
            <i class="bi bi-save2"></i> Kaydet
          </button>
        </div>
      </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flash_ok): ?>
      <div class="alert alert-success">
        <i class="bi bi-check-circle-fill"></i>
        <div><?= e((string)$flash_ok) ?></div>
      </div>
    <?php endif; ?>
    <?php if ($flash_err): ?>
      <div class="alert alert-error">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <div><?= e((string)$flash_err) ?></div>
      </div>
    <?php endif; ?>

    <form method="post" action="transactions/hasta-guncelle.php" enctype="multipart/form-data" id="editForm" autocomplete="off">
      <input type="hidden" name="csrf" value="<?= e($csrf) ?>">
      <input type="hidden" name="hasta_id" value="<?= (int)$hasta_id ?>">

      <div class="main-grid">
        <!-- Navigation Sidebar -->
        <div class="navigation-sidebar">
          <div class="nav-card">
            <div class="nav-title">
              <i class="bi bi-list-task"></i>
              Form Bölümleri
            </div>
            <div class="step-list">
              <div class="step-item active" data-step="kimlik">
                <div class="step-icon"><i class="bi bi-person-badge"></i></div>
                <div class="step-text">Kimlik Bilgileri</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="iletisim">
                <div class="step-icon"><i class="bi bi-telephone"></i></div>
                <div class="step-text">İletişim & Adres</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="yakin">
                <div class="step-icon"><i class="bi bi-people"></i></div>
                <div class="step-text">Yakınlar</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="sigorta">
                <div class="step-icon"><i class="bi bi-shield-check"></i></div>
                <div class="step-text">Sigorta Bilgileri</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="klinik">
                <div class="step-icon"><i class="bi bi-clipboard2-pulse"></i></div>
                <div class="step-text">Klinik Özet</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="diyaliz">
                <div class="step-icon"><i class="bi bi-droplet"></i></div>
                <div class="step-text">Diyaliz Profili</div>
                <i class="bi bi-chevron-right"></i>
              </div>
              <div class="step-item" data-step="belgeler">
                <div class="step-icon"><i class="bi bi-folder"></i></div>
                <div class="step-text">Belgeler</div>
                <i class="bi bi-chevron-right"></i>
              </div>
            </div>
            
            <div class="form-help" style="margin-top: 20px; padding-top: 20px; border-top: 1px solid var(--border-light);">
              <i class="bi bi-info-circle"></i>
              <strong>Zorunlu Alanlar:</strong> TC, Ad, Soyad, Telefon
            </div>
          </div>
        </div>

        <!-- Main Form Content -->
        <div>
          <!-- Kimlik Section -->
          <div class="form-section active" data-section="kimlik">
            <div class="section-indicator">
              <div class="step-indicator active">1. Kimlik Bilgileri</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-person-badge"></i>
                    Temel Kimlik Bilgileri
                  </div>
                  <div class="section-description">
                    Hastanın temel kimlik bilgilerini güncelleyin
                  </div>
                </div>
              </div>

              <div class="form-grid">
                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">
                      TC Kimlik No
                      <span class="required">*</span>
                    </label>
                    <input type="text" name="tc_no" maxlength="11" inputmode="numeric" required 
                           class="form-control" value="<?= e((string)($hasta['tc_no'] ?? '')) ?>"
                           placeholder="11 haneli TC no">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Dosya No</label>
                    <input type="text" name="dosya_no" class="form-control" 
                           value="<?= e((string)($hasta['dosya_no'] ?? '')) ?>"
                           placeholder="Opsiyonel dosya numarası">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Durum</label>
                    <select name="durum" class="form-control">
                      <?php foreach(['aktif'=>'Aktif','pasif'=>'Pasif','nakil'=>'Nakil','vefat'=>'Vefat','arsiv'=>'Arşiv'] as $k=>$v): ?>
                        <option value="<?= e($k) ?>" <?= ($hastaDurum === $k ? 'selected' : '') ?>>
                          <?= e($v) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">
                      Ad
                      <span class="required">*</span>
                    </label>
                    <input type="text" name="ad" required class="form-control" 
                           value="<?= e((string)($hasta['ad'] ?? '')) ?>"
                           placeholder="Hastanın adı">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">
                      Soyad
                      <span class="required">*</span>
                    </label>
                    <input type="text" name="soyad" required class="form-control" 
                           value="<?= e((string)($hasta['soyad'] ?? '')) ?>"
                           placeholder="Hastanın soyadı">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Cinsiyet</label>
                    <?php $cins = (string)($hasta['cinsiyet'] ?? 'Belirsiz'); ?>
                    <select name="cinsiyet" class="form-control">
                      <?php foreach(['Belirsiz'=>'Belirsiz','E'=>'Erkek','K'=>'Kadın','Diger'=>'Diğer'] as $k=>$v): ?>
                        <option value="<?= e($k) ?>" <?= ($cins === $k ? 'selected' : '') ?>>
                          <?= e($v) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Doğum Tarihi</label>
                    <input type="date" name="dogum_tarihi" class="form-control" 
                           value="<?= e((string)($hasta['dogum_tarihi'] ?? '')) ?>">
                  </div>
                </div>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="iletisim">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="iletisim">
                  İleri: İletişim Bilgileri <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- İletişim Section -->
          <div class="form-section" data-section="iletisim">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">2. İletişim & Adres</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-telephone"></i>
                    İletişim Bilgileri
                  </div>
                  <div class="section-description">
                    Hastanın iletişim bilgileri ve adres kayıtları
                  </div>
                </div>
                <button type="button" class="btn btn-secondary" id="addAddress">
                  <i class="bi bi-plus-lg"></i> Yeni Adres Ekle
                </button>
              </div>

              <div class="form-grid">
                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">
                      Telefon 1
                      <span class="required">*</span>
                    </label>
                    <input type="tel" name="telefon1" required class="form-control" 
                           value="<?= e((string)($hasta['telefon1'] ?? '')) ?>"
                           placeholder="05__ ___ __ __">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Telefon 2</label>
                    <input type="tel" name="telefon2" class="form-control" 
                           value="<?= e((string)($hasta['telefon2'] ?? '')) ?>"
                           placeholder="Opsiyonel ikinci telefon">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">E-posta</label>
                    <input type="email" name="email" class="form-control" 
                           value="<?= e((string)($hasta['email'] ?? '')) ?>"
                           placeholder="ornek@email.com">
                  </div>
                </div>
              </div>

              <!-- Address List -->
              <div id="addressList">
                <?php foreach($adresler as $idx=>$a): ?>
                  <div class="repeatable-section js-address-item">
                    <div class="repeatable-header">
                      <div class="repeatable-title">
                        <i class="bi bi-geo-alt"></i>
                        Adres <?= $idx + 1 ?>
                        <?php if ((int)($a['is_default'] ?? 0) === 1): ?>
                          <span style="background: var(--success); color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; margin-left: 8px;">
                            <i class="bi bi-star-fill"></i> Varsayılan
                          </span>
                        <?php endif; ?>
                      </div>
                      <?php if ($idx > 0): ?>
                        <button type="button" class="btn btn-danger removeAddress">
                          <i class="bi bi-trash"></i> Sil
                        </button>
                      <?php endif; ?>
                    </div>

                    <div class="form-grid">
                      <div class="col-3">
                        <div class="form-group">
                          <label class="form-label">Adres Tipi</label>
                          <?php $t = (string)($a['adres_tip'] ?? 'ikamet'); ?>
                          <select name="adres_tip[]" class="form-control">
                            <?php foreach(['ikamet'=>'İkamet','fatura'=>'Fatura','diger'=>'Diğer'] as $k=>$v): ?>
                              <option value="<?= e($k) ?>" <?= ($t===$k?'selected':'') ?>>
                                <?= e($v) ?>
                              </option>
                            <?php endforeach; ?>
                          </select>
                        </div>
                      </div>

                      <div class="col-3">
                        <div class="form-group">
                          <label class="form-label">İl</label>
                          <input name="adres_il[]" class="form-control" 
                                 value="<?= e((string)($a['il'] ?? '')) ?>"
                                 placeholder="İl adı">
                        </div>
                      </div>

                      <div class="col-3">
                        <div class="form-group">
                          <label class="form-label">İlçe</label>
                          <input name="adres_ilce[]" class="form-control" 
                                 value="<?= e((string)($a['ilce'] ?? '')) ?>"
                                 placeholder="İlçe adı">
                        </div>
                      </div>

                      <div class="col-3">
                        <div class="form-group">
                          <label class="form-label">Posta Kodu</label>
                          <input name="adres_posta_kodu[]" class="form-control" 
                                 inputmode="numeric" 
                                 value="<?= e((string)($a['posta_kodu'] ?? '')) ?>"
                                 placeholder="5 haneli posta kodu">
                        </div>
                      </div>

                      <div class="col-12">
                        <div class="form-group">
                          <label class="form-label">Açık Adres</label>
                          <textarea name="adres_acik[]" class="form-control" rows="3"
                                    placeholder="Mahalle, sokak, bina, daire bilgileri"><?= e((string)($a['acik_adres'] ?? '')) ?></textarea>
                        </div>
                      </div>

                      <div class="col-12">
                        <div class="checkbox-group">
                          <label class="checkbox-label">
                            <input type="checkbox" class="defaultAddr" name="adres_is_default[]" 
                                   value="1" <?= ((int)($a['is_default'] ?? 0)===1) ? 'checked' : '' ?>>
                            <span>Bu adresi varsayılan adres olarak ayarla</span>
                          </label>
                        </div>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="kimlik">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="yakin">
                  İleri: Yakınlar <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- Yakınlar Section -->
          <div class="form-section" data-section="yakin">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">2. İletişim</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">3. Yakınlar</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-people"></i>
                    Yakınlar & Acil İletişim
                  </div>
                  <div class="section-description">
                    Acil durumda ulaşılacak kişilerin bilgileri
                  </div>
                </div>
                <button type="button" class="btn btn-secondary" id="addKin">
                  <i class="bi bi-plus-lg"></i> Yeni Yakın Ekle
                </button>
              </div>

              <div id="kinList">
                <?php foreach($yakinlar as $i=>$y): ?>
                  <div class="repeatable-section js-kin-item">
                    <div class="repeatable-header">
                      <div class="repeatable-title">
                        <i class="bi bi-person"></i>
                        Yakın <?= $i + 1 ?>
                        <?php if ((int)($y['is_acil'] ?? 0) === 1): ?>
                          <span style="background: var(--danger); color: white; padding: 2px 8px; border-radius: 10px; font-size: 12px; margin-left: 8px;">
                            <i class="bi bi-telephone"></i> Acil
                          </span>
                        <?php endif; ?>
                      </div>
                      <?php if ($i > 0): ?>
                        <button type="button" class="btn btn-danger removeKin">
                          <i class="bi bi-trash"></i> Sil
                        </button>
                      <?php endif; ?>
                    </div>

                    <div class="form-grid">
                      <div class="col-6">
                        <div class="form-group">
                          <label class="form-label">Ad Soyad</label>
                          <input name="yakin_ad_soyad[]" class="form-control" 
                                 value="<?= e((string)($y['ad_soyad'] ?? '')) ?>"
                                 placeholder="Yakının tam adı">
                        </div>
                      </div>

                      <div class="col-6">
                        <div class="form-group">
                          <label class="form-label">Yakınlık Derecesi</label>
                          <input name="yakinlik[]" class="form-control" 
                                 value="<?= e((string)($y['yakinlik'] ?? '')) ?>"
                                 placeholder="Örn: Anne, Baba, Eş, Çocuk">
                        </div>
                      </div>

                      <div class="col-4">
                        <div class="form-group">
                          <label class="form-label">Telefon</label>
                          <input name="yakin_telefon[]" class="form-control" 
                                 inputmode="tel" 
                                 value="<?= e((string)($y['telefon'] ?? '')) ?>"
                                 placeholder="İletişim telefonu">
                        </div>
                      </div>

                      <div class="col-4">
                        <div class="form-group">
                          <label class="form-label">Telefon 2</label>
                          <input name="yakin_telefon2[]" class="form-control" 
                                 inputmode="tel" 
                                 value="<?= e((string)($y['telefon2'] ?? '')) ?>"
                                 placeholder="Opsiyonel ikinci telefon">
                        </div>
                      </div>

                      <div class="col-4">
                        <div class="form-group">
                          <label class="form-label">E-posta</label>
                          <input type="email" name="yakin_email[]" class="form-control" 
                                 value="<?= e((string)($y['email'] ?? '')) ?>"
                                 placeholder="ornek@email.com">
                        </div>
                      </div>

                      <div class="col-12">
                        <div class="form-group">
                          <label class="form-label">Adres</label>
                          <textarea name="yakin_adres[]" class="form-control" rows="2"
                                    placeholder="Yakının adresi"><?= e((string)($y['adres'] ?? '')) ?></textarea>
                        </div>
                      </div>

                      <div class="col-12">
                        <div class="form-group">
                          <div class="checkbox-group">
                            <label class="checkbox-label">
                              <input type="checkbox" name="yakin_is_acil[]" 
                                     value="1" <?= ((int)($y['is_acil'] ?? 0)===1) ? 'checked' : '' ?>>
                              <span>Acil durumda aranacak kişi</span>
                            </label>
                            <label class="checkbox-label">
                              <input type="checkbox" name="yakin_is_vasi[]" 
                                     value="1" <?= ((int)($y['is_vasi'] ?? 0)===1) ? 'checked' : '' ?>>
                              <span>Vasi</span>
                            </label>
                          </div>
                        </div>
                      </div>

                      <div class="col-12">
                        <div class="form-group">
                          <label class="form-label">Notlar</label>
                          <textarea name="yakin_not[]" class="form-control" rows="2"
                                    placeholder="Ek notlar"><?= e((string)($y['notlar'] ?? '')) ?></textarea>
                        </div>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="iletisim">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="sigorta">
                  İleri: Sigorta <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- Sigorta Section -->
          <div class="form-section" data-section="sigorta">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">3. Yakınlar</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">4. Sigorta</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-shield-check"></i>
                    Sigorta & Kurum Bilgileri
                  </div>
                  <div class="section-description">
                    SGK ve kurum bilgileri, provizyon numaraları
                  </div>
                </div>
              </div>

              <?php if(!$sigTable): ?>
                <div class="alert alert-error">
                  <i class="bi bi-exclamation-triangle"></i>
                  <div>Sigorta tablosu bulunamadı. Bu bölümdeki bilgiler kaydedilmeyecektir.</div>
                </div>
              <?php endif; ?>

              <div class="form-grid">
                <div class="col-6">
                  <div class="form-group">
                    <label class="form-label">SGK Tipi</label>
                    <select name="sgk_tipi_id" class="form-control">
                      <option value="">Seçiniz</option>
                      <?php foreach($sgk_tipleri as $x): ?>
                        <option value="<?= (int)$x['id'] ?>" 
                          <?= ((int)($sigorta['sgk_tipi_id'] ?? 0) === (int)$x['id']) ? 'selected' : '' ?>>
                          <?= e((string)$x['ad']) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-6">
                  <div class="form-group">
                    <label class="form-label">Kurum</label>
                    <select name="kurum_id" class="form-control">
                      <option value="">Seçiniz</option>
                      <?php foreach($kurumlar as $x): ?>
                        <option value="<?= (int)$x['id'] ?>" 
                          <?= ((int)($sigorta['kurum_id'] ?? 0) === (int)$x['id']) ? 'selected' : '' ?>>
                          <?= e((string)$x['ad']) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Sicil No</label>
                    <input name="sicil_no" class="form-control" 
                           value="<?= e((string)($sigorta['sicil_no'] ?? '')) ?>"
                           placeholder="Kurum sicil numarası">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Provizyon No</label>
                    <input name="provizyon_no" class="form-control" 
                           value="<?= e((string)($sigorta['provizyon_no'] ?? '')) ?>"
                           placeholder="Provizyon numarası">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Sigorta Durumu</label>
                    <input name="sigorta_not" class="form-control" 
                           value="<?= e((string)($sigorta['sigorta_not'] ?? '')) ?>"
                           placeholder="Sigorta durumu">
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Notlar</label>
                    <textarea name="sigorta_notlar" class="form-control" rows="3"
                              placeholder="Sigorta ile ilgili ek notlar"><?= e((string)($sigorta['notlar'] ?? '')) ?></textarea>
                  </div>
                </div>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="yakin">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="klinik">
                  İleri: Klinik Özet <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- Klinik Section -->
          <div class="form-section" data-section="klinik">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">4. Sigorta</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">5. Klinik Özet</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-clipboard2-pulse"></i>
                    Klinik Özet & Notlar
                  </div>
                  <div class="section-description">
                    Tanı, ilaç, uyarı ve diğer klinik bilgiler
                  </div>
                </div>
              </div>

              <?php if(!$klinikTable): ?>
                <div class="alert alert-error">
                  <i class="bi bi-exclamation-triangle"></i>
                  <div>Klinik özet tablosu bulunamadı. Bu bölümdeki bilgiler kaydedilmeyecektir.</div>
                </div>
              <?php endif; ?>

              <div class="form-grid">
                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Tanılar</label>
                    <textarea name="tanilar" class="form-control" rows="4"
                              placeholder="Hastanın tanıları, teşhisler..."><?= e((string)($klinik['tanilar'] ?? '')) ?></textarea>
                    <div class="form-help">Birden fazla tanıyı madde işaretleri ile listeleyebilirsiniz.</div>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Uyarılar</label>
                    <textarea name="uyarilar" class="form-control" rows="3"
                              placeholder="Önemli uyarılar, kontrendikasyonlar..."><?= e((string)($klinik['uyarilar'] ?? '')) ?></textarea>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">İlaçlar</label>
                    <textarea name="ilaclar" class="form-control" rows="4"
                              placeholder="Kullanılan ilaçlar, dozları ve zamanları..."><?= e((string)($klinik['ilaclar'] ?? '')) ?></textarea>
                    <div class="form-help">Her ilacı ayrı satırda belirtin.</div>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Serbest Not</label>
                    <textarea name="serbest_not" class="form-control" rows="3"
                              placeholder="Diğer klinik notlar..."><?= e((string)($klinik['serbest_not'] ?? '')) ?></textarea>
                  </div>
                </div>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="sigorta">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="diyaliz">
                  İleri: Diyaliz Profili <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- Diyaliz Section -->
          <div class="form-section" data-section="diyaliz">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">5. Klinik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">6. Diyaliz Profili</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-droplet"></i>
                    Diyaliz Tedavi Profili
                  </div>
                  <div class="section-description">
                    Diyaliz modalitesi, damar yolu ve tedavi parametreleri
                  </div>
                </div>
              </div>

              <?php if(!$diyTable): ?>
                <div class="alert alert-error">
                  <i class="bi bi-exclamation-triangle"></i>
                  <div>Diyaliz tablosu bulunamadı. Bu bölümdeki bilgiler kaydedilmeyecektir.</div>
                </div>
              <?php endif; ?>

              <div class="form-grid">
                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Başlangıç Tarihi</label>
                    <input type="date" name="diyaliz_baslangic" class="form-control" 
                           value="<?= e((string)($diyaliz['diyaliz_baslangic'] ?? '')) ?>">
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Modalite</label>
                    <?php $mod = (string)($diyaliz['modality'] ?? 'HD'); ?>
                    <select name="modality" class="form-control">
                      <?php foreach(['HD'=>'HD (Hemodiyaliz)','HDF'=>'HDF (Hemodiafiltrasyon)','PD'=>'PD (Periton Diyalizi)','HomeHD'=>'Ev HD','Diger'=>'Diğer'] as $k=>$v): ?>
                        <option value="<?= e($k) ?>" <?= ($mod===$k?'selected':'') ?>>
                          <?= e($v) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-4">
                  <div class="form-group">
                    <label class="form-label">Damar Yolu</label>
                    <select name="damar_yolu_id" class="form-control">
                      <option value="">Seçiniz</option>
                      <?php foreach($damar_yollari as $x): ?>
                        <option value="<?= (int)$x['id'] ?>" 
                          <?= ((int)($diyaliz['damar_yolu_id'] ?? 0) === (int)$x['id']) ? 'selected' : '' ?>>
                          <?= e((string)$x['ad']) ?>
                        </option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                </div>

                <div class="col-3">
                  <div class="form-group">
                    <label class="form-label">Kuru Ağırlık (kg)</label>
                    <input name="kuru_agirlik" class="form-control" 
                           inputmode="decimal" 
                           value="<?= e((string)($diyaliz['kuru_agirlik'] ?? '')) ?>"
                           placeholder="Örn: 65.5">
                  </div>
                </div>

                <div class="col-3">
                  <div class="form-group">
                    <label class="form-label">Hedef UF (L)</label>
                    <input name="hedef_uf" class="form-control" 
                           inputmode="decimal" 
                           value="<?= e((string)($diyaliz['hedef_uf'] ?? '')) ?>"
                           placeholder="Örn: 2.5">
                  </div>
                </div>

                <div class="col-3">
                  <div class="form-group">
                    <label class="form-label">Seans Süresi (dk)</label>
                    <input name="seans_suresi_dk" class="form-control" 
                           inputmode="numeric" 
                           value="<?= e((string)($diyaliz['seans_suresi_dk'] ?? '')) ?>"
                           placeholder="Örn: 240">
                  </div>
                </div>

                <div class="col-3">
                  <div class="form-group">
                    <label class="form-label">Damar Lokasyon</label>
                    <input name="damar_lokasyon" class="form-control" 
                           value="<?= e((string)($diyaliz['damar_lokasyon'] ?? '')) ?>"
                           placeholder="Örn: Sağ ön kol">
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Heparin Not</label>
                    <textarea name="heparin_not" class="form-control" rows="2"
                              placeholder="Heparin protokolü, doz bilgileri..."><?= e((string)($diyaliz['heparin_not'] ?? '')) ?></textarea>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Özel Uyarılar</label>
                    <textarea name="ozel_uyarilar" class="form-control" rows="3"
                              placeholder="Özel durumlar, alerjiler, önemli uyarılar..."><?= e((string)($diyaliz['ozel_uyarilar'] ?? '')) ?></textarea>
                  </div>
                </div>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="klinik">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="button" class="btn btn-primary" data-next="belgeler">
                  İleri: Belgeler <i class="bi bi-arrow-right"></i>
                </button>
              </div>
            </div>
          </div>

          <!-- Belgeler Section -->
          <div class="form-section" data-section="belgeler">
            <div class="section-indicator">
              <div class="step-indicator">1. Kimlik</div>
              <div class="step-divider">/</div>
              <div class="step-indicator">6. Diyaliz</div>
              <div class="step-divider">/</div>
              <div class="step-indicator active">7. Belgeler</div>
            </div>
            
            <div class="section-card">
              <div class="section-header">
                <div>
                  <div class="section-title">
                    <i class="bi bi-folder"></i>
                    Belge Yönetimi
                  </div>
                  <div class="section-description">
                    Hasta dosyalarını yükleyin veya mevcut belgeleri görüntüleyin
                  </div>
                </div>
              </div>

              <div class="form-grid">
                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Yeni Dosya Yükle</label>
                    <div class="file-input-wrapper">
                      <input type="file" name="dosyalar[]" multiple id="fileInput">
                      <label for="fileInput" class="file-input-label">
                        <i class="bi bi-cloud-arrow-up" style="font-size: 24px;"></i>
                        <div>
                          <div style="font-weight: 600;">Dosyaları sürükleyin veya tıklayın</div>
                          <div style="font-size: 13px; color: var(--text-muted); margin-top: 4px;">
                            PDF, JPEG, PNG formatlarında, maksimum 10MB
                          </div>
                        </div>
                      </label>
                    </div>
                    <div class="form-help">
                      Birden fazla dosya seçebilirsiniz. Yükleme tablosu yoksa kayıt atlanacaktır.
                    </div>
                  </div>
                </div>

                <div class="col-12">
                  <div class="form-group">
                    <label class="form-label">Belge Açıklaması</label>
                    <input name="belge_aciklama" class="form-control" 
                           placeholder="Örn: Laboratuvar sonuçları, kontrol evrakları, röntgen...">
                  </div>
                </div>

                <?php if(!empty($dosyalar)): ?>
                  <div class="col-12">
                    <div class="form-group">
                      <label class="form-label">Mevcut Belgeler</label>
                      <div class="documents-list">
                        <?php foreach($dosyalar as $f): ?>
                          <div class="document-item">
                            <div class="document-icon">
                              <i class="bi bi-file-earmark-text"></i>
                            </div>
                            <div class="document-info">
                              <div class="document-name">
                                <?= e((string)($f['orjinal_ad'] ?? $f['file_name'] ?? $f['dosya_adi'] ?? 'Belge')) ?>
                              </div>
                              <div class="document-desc">
                                <?= e((string)($f['aciklama'] ?? '-')) ?> • 
                                <?= date('d.m.Y H:i', strtotime($f['created_at'] ?? 'now')) ?>
                              </div>
                            </div>
                            <?php if(isset($f['dosya_yolu']) || isset($f['file_path'])): ?>
                              <a href="<?= e($f['dosya_yolu'] ?? $f['file_path']) ?>" 
                                 target="_blank" class="btn btn-secondary" style="padding: 8px 12px;">
                                <i class="bi bi-eye"></i>
                              </a>
                            <?php endif; ?>
                          </div>
                        <?php endforeach; ?>
                      </div>
                    </div>
                  </div>
                <?php endif; ?>
              </div>

              <div class="section-navigation">
                <button type="button" class="btn btn-secondary" data-prev="diyaliz">
                  <i class="bi bi-arrow-left"></i> Geri
                </button>
                <button type="submit" class="btn btn-success">
                  <i class="bi bi-check2-circle"></i> Tüm Bilgileri Kaydet
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Summary Sidebar -->
        <div class="summary-sidebar">
          <div class="summary-card">
            <div class="summary-title">
              <i class="bi bi-card-checklist"></i>
              Özet & İstatistikler
            </div>
            
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-label">Hasta</div>
                <div class="stat-value"><?= e(trim((string)($hasta['ad'] ?? '').' '.(string)($hasta['soyad'] ?? ''))) ?></div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">TC Kimlik No</div>
                <div class="stat-value"><?= e((string)($hasta['tc_no'] ?? '-')) ?></div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">Telefon</div>
                <div class="stat-value"><?= e((string)($hasta['telefon1'] ?? '-')) ?></div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">Durum</div>
                <div class="stat-value" style="color: <?= $hastaDurum === 'aktif' ? 'var(--success)' : 'var(--warning)' ?>;">
                  <?= e(ucfirst($hastaDurum)) ?>
                </div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">Adres Sayısı</div>
                <div class="stat-value" id="kpiAddr"><?= (int)count($adresler) ?></div>
              </div>
              
              <div class="stat-item">
                <div class="stat-label">Yakın Sayısı</div>
                <div class="stat-value" id="kpiKin"><?= (int)count($yakinlar) ?></div>
              </div>
            </div>

            <div style="margin-top: 20px; display: flex; flex-direction: column; gap: 10px;">
              <a href="dashboard.php?sayfa=hasta-detay&id=<?= (int)$hasta_id ?>" 
                 class="btn btn-secondary" style="justify-content: center;">
                <i class="bi bi-eye"></i> Detaylı Görüntüle
              </a>
              <button type="submit" class="btn btn-primary" style="justify-content: center;">
                <i class="bi bi-save2"></i> Kaydet ve Kapat
              </button>
            </div>
          </div>

          <?php if(!empty($dosyalar)): ?>
            <div class="summary-card">
              <div class="summary-title">
                <i class="bi bi-paperclip"></i>
                Son Yüklenenler
              </div>
              
              <div class="documents-list">
                <?php foreach(array_slice($dosyalar, 0, 3) as $f): ?>
                  <div class="document-item">
                    <div class="document-icon">
                      <i class="bi bi-file-earmark-text"></i>
                    </div>
                    <div class="document-info">
                      <div class="document-name">
                        <?= e(substr((string)($f['orjinal_ad'] ?? $f['file_name'] ?? $f['dosya_adi'] ?? 'Belge'), 0, 20)) ?>
                        <?= strlen((string)($f['orjinal_ad'] ?? $f['file_name'] ?? $f['dosya_adi'] ?? '')) > 20 ? '...' : '' ?>
                      </div>
                      <div class="document-desc">
                        <?= date('d.m.Y', strtotime($f['created_at'] ?? 'now')) ?>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
                
                <?php if(count($dosyalar) > 3): ?>
                  <div style="text-align: center; margin-top: 10px;">
                    <a href="#belgeler" class="btn btn-secondary" style="width: 100%; justify-content: center;">
                      <i class="bi bi-arrow-right"></i> Tümünü Gör
                    </a>
                  </div>
                <?php endif; ?>
              </div>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Mobile Navigation -->
      <div class="mobile-navigation">
        <div class="mobile-step-info">
          <div class="mobile-step-title" id="mobileStepTitle">Kimlik Bilgileri</div>
          <div class="mobile-step-subtitle">Adım 1 / 7</div>
        </div>
        <div style="display: flex; gap: 10px;">
          <button type="button" class="btn btn-secondary" id="mobilePrev">
            <i class="bi bi-arrow-left"></i>
          </button>
          <button type="button" class="btn btn-secondary" id="mobileNext">
            <i class="bi bi-arrow-right"></i>
          </button>
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-save2"></i>
          </button>
        </div>
      </div>
    </form>
  </div>

<script>
(function(){
  // Navigation
  const steps = Array.from(document.querySelectorAll('.step-item'));
  const sections = Array.from(document.querySelectorAll('.form-section'));
  const stepOrder = steps.map(s => s.dataset.step);
  const stepTitles = {
    kimlik: 'Kimlik Bilgileri',
    iletisim: 'İletişim & Adres',
    yakin: 'Yakınlar',
    sigorta: 'Sigorta Bilgileri',
    klinik: 'Klinik Özet',
    diyaliz: 'Diyaliz Profili',
    belgeler: 'Belgeler'
  };

  function activateStep(step) {
    // Update steps
    steps.forEach(s => s.classList.toggle('active', s.dataset.step === step));
    
    // Update sections
    sections.forEach(sec => {
      sec.classList.toggle('active', sec.dataset.section === step);
    });
    
    // Update mobile title
    const currentIndex = stepOrder.indexOf(step) + 1;
    document.getElementById('mobileStepTitle').textContent = stepTitles[step];
    document.querySelector('.mobile-step-subtitle').textContent = `Adım ${currentIndex} / ${stepOrder.length}`;
    
    // Scroll to top on mobile
    if (window.innerWidth <= 900) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
    
    // Update URL hash
    history.replaceState(null, null, `#${step}`);
  }

  // Step click events
  steps.forEach(step => {
    step.addEventListener('click', () => activateStep(step.dataset.step));
  });

  // Next/Previous buttons
  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));
  });

  // Mobile navigation
  document.getElementById('mobileNext')?.addEventListener('click', () => {
    const activeStep = document.querySelector('.step-item.active')?.dataset.step;
    const currentIndex = stepOrder.indexOf(activeStep || 'kimlik');
    if (currentIndex < stepOrder.length - 1) {
      activateStep(stepOrder[currentIndex + 1]);
    }
  });

  document.getElementById('mobilePrev')?.addEventListener('click', () => {
    const activeStep = document.querySelector('.step-item.active')?.dataset.step;
    const currentIndex = stepOrder.indexOf(activeStep || 'kimlik');
    if (currentIndex > 0) {
      activateStep(stepOrder[currentIndex - 1]);
    }
  });

  // Address management
  const addressList = document.getElementById('addressList');
  const addAddressBtn = document.getElementById('addAddress');

  function updateAddressCount() {
    const count = document.querySelectorAll('.js-address-item').length;
    document.getElementById('kpiAddr').textContent = count;
  }

  function enforceSingleDefaultAddress() {
    const checkboxes = document.querySelectorAll('.defaultAddr');
    checkboxes.forEach(cb => {
      cb.addEventListener('change', function() {
        if (this.checked) {
          checkboxes.forEach(other => {
            if (other !== this) other.checked = false;
          });
        }
      });
    });
  }

  addAddressBtn?.addEventListener('click', () => {
    const template = addressList.querySelector('.js-address-item');
    if (!template) return;
    
    const clone = template.cloneNode(true);
    const removeBtn = clone.querySelector('.removeAddress');
    const title = clone.querySelector('.repeatable-title');
    
    if (removeBtn) removeBtn.style.display = 'flex';
    if (title) {
      title.innerHTML = '<i class="bi bi-geo-alt"></i> Yeni Adres';
    }
    
    // Clear inputs
    clone.querySelectorAll('input, textarea, select').forEach(input => {
      if (input.type === 'checkbox') {
        input.checked = false;
      } else if (input.type !== 'file') {
        input.value = '';
      }
    });
    
    addressList.appendChild(clone);
    enforceSingleDefaultAddress();
    updateAddressCount();
    
    clone.scrollIntoView({ behavior: 'smooth', block: 'center' });
  });

  // Kin management
  const kinList = document.getElementById('kinList');
  const addKinBtn = document.getElementById('addKin');

  function updateKinCount() {
    const count = document.querySelectorAll('.js-kin-item').length;
    document.getElementById('kpiKin').textContent = count;
  }

  addKinBtn?.addEventListener('click', () => {
    const template = kinList.querySelector('.js-kin-item');
    if (!template) return;
    
    const clone = template.cloneNode(true);
    const removeBtn = clone.querySelector('.removeKin');
    const title = clone.querySelector('.repeatable-title');
    
    if (removeBtn) removeBtn.style.display = 'flex';
    if (title) {
      title.innerHTML = '<i class="bi bi-person"></i> Yeni Yakın';
    }
    
    // Clear inputs
    clone.querySelectorAll('input, textarea, select').forEach(input => {
      if (input.type === 'checkbox') {
        input.checked = false;
      } else if (input.type !== 'file') {
        input.value = '';
      }
    });
    
    kinList.appendChild(clone);
    updateKinCount();
    
    clone.scrollIntoView({ behavior: 'smooth', block: 'center' });
  });

  // Remove buttons
  document.addEventListener('click', function(e) {
    if (e.target.closest('.removeAddress')) {
      const item = e.target.closest('.js-address-item');
      if (item && document.querySelectorAll('.js-address-item').length > 1) {
        item.remove();
        updateAddressCount();
      }
    }
    
    if (e.target.closest('.removeKin')) {
      const item = e.target.closest('.js-kin-item');
      if (item && document.querySelectorAll('.js-kin-item').length > 1) {
        item.remove();
        updateKinCount();
      }
    }
  });

  // Initialize from hash
  const hash = window.location.hash.replace('#', '');
  if (hash && stepOrder.includes(hash)) {
    activateStep(hash);
  } else {
    activateStep('kimlik');
  }

  // Initialize counts and default address handling
  updateAddressCount();
  updateKinCount();
  enforceSingleDefaultAddress();

  // File input styling
  const fileInput = document.getElementById('fileInput');
  if (fileInput) {
    fileInput.addEventListener('change', function() {
      const label = this.nextElementSibling;
      if (this.files.length > 0) {
        const fileNames = Array.from(this.files).map(f => f.name).join(', ');
        label.querySelector('div').innerHTML = `
          <div style="font-weight: 600;">${this.files.length} dosya seçildi</div>
          <div style="font-size: 13px; color: var(--text-muted); margin-top: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
            ${fileNames}
          </div>
        `;
      }
    });
  }
})();
</script>

</body>
</html>