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

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

$q = trim($_GET['q'] ?? '');
$city = trim($_GET['city'] ?? '');
$district = trim($_GET['district'] ?? '');
$institution = trim($_GET['institution'] ?? '');
$service = trim($_GET['service'] ?? ''); // all|1|0
$gender = trim($_GET['gender'] ?? '');
$blood = trim($_GET['blood'] ?? '');
$sort = trim($_GET['sort'] ?? '');

$where = [];
$params = [];
if ($q !== '') {
  $where[] = '(p.first_name LIKE :q OR p.last_name LIKE :q OR p.national_id LIKE :q)';
  $params[':q'] = "%{$q}%";
}
if ($city !== '') {
  $where[] = 'p.city = :city';
  $params[':city'] = $city;
}
if ($district !== '') {
  $where[] = 'p.district = :district';
  $params[':district'] = $district;
}
if ($institution !== '') {
  $where[] = 'i.id = :inst';
  $params[':inst'] = (int)$institution;
}
if ($service !== '' && in_array($service,['0','1'],true)) {
  $where[] = 'p.service_needed = :svc';
  $params[':svc'] = (int)$service;
}
if ($gender !== '' && in_array($gender,['male','female','other'],true)) {
  $where[] = 'p.gender = :gender';
  $params[':gender'] = $gender;
}
if ($blood !== '') {
  $where[] = 'p.blood_type = :blood';
  $params[':blood'] = $blood;
}
$whereSql = $where ? ('WHERE '.implode(' AND ',$where)) : '';

// Sıralama
$orderBy = 'p.created_at DESC';
switch($sort) {
  case 'name_asc':
    $orderBy = 'p.first_name ASC, p.last_name ASC';
    break;
  case 'name_desc':
    $orderBy = 'p.first_name DESC, p.last_name DESC';
    break;
  case 'date_asc':
    $orderBy = 'p.created_at ASC';
    break;
  case 'date_desc':
    $orderBy = 'p.created_at DESC';
    break;
  case 'city_asc':
    $orderBy = 'p.city ASC, p.district ASC';
    break;
}

$sql = "SELECT p.id, p.first_name, p.last_name, p.national_id, p.phone, p.city, p.district, p.service_needed, p.created_at, p.gender, p.blood_type,
         i.name AS institution, r.referral_reason
  FROM patients p
  LEFT JOIN patient_referrals r ON r.patient_id = p.id
  LEFT JOIN institutions i ON i.id = r.institution_id AND i.status = 'active'
  $whereSql
  ORDER BY $orderBy
  LIMIT 300";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

$cities = $pdo->query('SELECT DISTINCT city FROM patients WHERE city IS NOT NULL AND city <> "" ORDER BY city')->fetchAll(PDO::FETCH_COLUMN);
$districts = [];
if ($city) {
  $st = $pdo->prepare('SELECT DISTINCT district FROM patients WHERE city = :c AND district IS NOT NULL AND district <> "" ORDER BY district');
  $st->execute([':c'=>$city]);
  $districts = $st->fetchAll(PDO::FETCH_COLUMN);
}
$bloods = $pdo->query('SELECT DISTINCT blood_type FROM patients WHERE blood_type IS NOT NULL AND blood_type <> "" ORDER BY blood_type')->fetchAll(PDO::FETCH_COLUMN);
$institutions = $pdo->query("SELECT id,name FROM institutions WHERE status = 'active' ORDER BY name")->fetchAll();

// stats
$stat = $pdo->query('SELECT COUNT(*) AS total,
  SUM(service_needed=1) AS svc,
  SUM(gender="male") AS male,
  SUM(gender="female") AS female
  FROM patients')->fetch();

include __DIR__ . '/../header.php';
?>
<style>
  :root {
    --primary: #4361ee;
    --primary-dark: #3a56d4;
    --secondary: #7209b7;
    --success: #06d6a0;
    --info: #118ab2;
    --warning: #ffd166;
    --danger: #ef476f;
    --light: #f8f9fa;
    --dark: #212529;
    --gray-100: #f8f9fa;
    --gray-200: #e9ecef;
    --gray-300: #dee2e6;
    --gray-400: #ced4da;
    --gray-500: #adb5bd;
    --gray-600: #6c757d;
    --gray-700: #495057;
    --gray-800: #343a40;
    --gray-900: #212529;
    --gradient-primary: linear-gradient(135deg, #4361ee, #3a56d4);
    --gradient-success: linear-gradient(135deg, #06d6a0, #05c591);
    --gradient-info: linear-gradient(135deg, #118ab2, #0f7a9e);
    --gradient-warning: linear-gradient(135deg, #ffd166, #ffc745);
    --shadow-sm: 0 2px 4px rgba(0,0,0,0.05);
    --shadow: 0 4px 12px rgba(0,0,0,0.08);
    --shadow-lg: 0 10px 25px rgba(0,0,0,0.1);
    --shadow-xl: 0 15px 35px rgba(0,0,0,0.12);
    --border-radius: 12px;
    --border-radius-lg: 16px;
    --border-radius-xl: 20px;
    --transition: all 0.3s ease;
  }

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

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

  .container {
    max-width: 100%;
    padding: 0;
    margin: 0;
  }

  .page {
    padding: 24px 28px;
    position: relative;
    overflow-x: hidden;
  }

  /* Header Styles */
  .page-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 28px;
    padding: 24px;
    background: white;
    border-radius: var(--border-radius-lg);
    box-shadow: var(--shadow);
    position: relative;
    overflow: hidden;
  }

  .page-head::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 6px;
    height: 100%;
    background: var(--gradient-primary);
  }

  .page-title {
    display: flex;
    align-items: center;
    gap: 14px;
  }

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

  .page-title .icon-wrapper {
    width: 56px;
    height: 56px;
    background: var(--gradient-primary);
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: var(--shadow-lg);
  }

  .page-title .icon-wrapper i {
    font-size: 24px;
    color: white;
  }

  .actions {
    display: flex;
    gap: 12px;
  }

  .btn {
    padding: 12px 24px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 14px;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: var(--transition);
    text-decoration: none;
    box-shadow: var(--shadow-sm);
  }

  .btn:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
  }

  .btn:active {
    transform: translateY(0);
  }

  .btn-outline {
    background: white;
    color: var(--primary);
    border: 2px solid #e2e8f0;
  }

  .btn-outline:hover {
    border-color: var(--primary);
    background: rgba(67, 97, 238, 0.05);
  }

  .btn-primary {
    background: var(--gradient-primary);
    color: white;
    box-shadow: var(--shadow);
  }

  .btn-primary:hover {
    background: linear-gradient(135deg, #3a56d4, #2f4bc4);
  }

  /* Stats Cards */
  .stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
    gap: 20px;
    margin-bottom: 28px;
  }

  .stat-card {
    background: white;
    border-radius: var(--border-radius-lg);
    padding: 24px;
    box-shadow: var(--shadow);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
  }

  .stat-card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-xl);
  }

  .stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 4px;
  }

  .stat-card:nth-child(1)::before { background: var(--gradient-primary); }
  .stat-card:nth-child(2)::before { background: var(--gradient-success); }
  .stat-card:nth-child(3)::before { background: var(--gradient-info); }
  .stat-card:nth-child(4)::before { background: linear-gradient(135deg, #ff6b6b, #ee5d5d); }

  .stat-card .label {
    font-size: 14px;
    font-weight: 600;
    color: var(--gray-600);
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .stat-card .value {
    font-size: 32px;
    font-weight: 800;
    color: var(--gray-900);
    letter-spacing: -0.5px;
    margin-bottom: 4px;
  }

  .stat-card .sub {
    font-size: 13px;
    color: var(--gray-500);
  }

  /* Filter Bar */
  .filter-container {
    background: white;
    border-radius: var(--border-radius-lg);
    padding: 24px;
    margin-bottom: 28px;
    box-shadow: var(--shadow);
  }

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

  .filter-header h3 {
    font-size: 18px;
    font-weight: 700;
    color: var(--gray-900);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .filter-header h3 i {
    color: var(--primary);
  }

  .filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }

  .form-group {
    margin-bottom: 0;
  }

  .form-label {
    display: block;
    font-size: 13px;
    font-weight: 600;
    color: var(--gray-700);
    margin-bottom: 8px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .form-control {
    width: 100%;
    height: 46px;
    padding: 0 16px;
    border: 2px solid var(--gray-300);
    border-radius: 10px;
    font-size: 14px;
    color: var(--gray-800);
    background: white;
    transition: var(--transition);
  }

  .form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.15);
  }

  .form-control::placeholder {
    color: var(--gray-500);
  }

  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 16px;
    border-top: 1px solid var(--gray-200);
  }

  /* Table */
  .table-container {
    background: white;
    border-radius: var(--border-radius-lg);
    padding: 24px;
    box-shadow: var(--shadow);
    overflow: hidden;
  }

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

  .table-header h3 {
    font-size: 18px;
    font-weight: 700;
    color: var(--gray-900);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .table-header h3 i {
    color: var(--primary);
  }

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

  .table thead {
    background: linear-gradient(90deg, #f8fafc, #f1f5f9);
  }

  .table th {
    padding: 18px 16px;
    font-weight: 700;
    color: var(--gray-700);
    text-align: left;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 2px solid var(--gray-200);
    white-space: nowrap;
  }

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

  .table tbody tr:hover {
    background-color: rgba(67, 97, 238, 0.05);
  }

  .table td {
    padding: 18px 16px;
    border-bottom: 1px solid var(--gray-200);
    font-size: 14px;
    color: var(--gray-800);
  }

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

  /* Badges */
  .badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 700;
    letter-spacing: 0.3px;
  }

  .badge-success {
    background: rgba(6, 214, 160, 0.1);
    color: #05a37a;
    border: 1px solid rgba(6, 214, 160, 0.2);
  }

  .badge-secondary {
    background: rgba(108, 117, 125, 0.1);
    color: var(--gray-600);
    border: 1px solid rgba(108, 117, 125, 0.2);
  }

  .badge-warning {
    background: rgba(255, 209, 102, 0.1);
    color: #e6a700;
    border: 1px solid rgba(255, 209, 102, 0.2);
  }

  .badge-danger {
    background: rgba(239, 71, 111, 0.1);
    color: #d62d54;
    border: 1px solid rgba(239, 71, 111, 0.2);
  }

  /* Patient Name */
  .patient-name {
    font-weight: 700;
    color: var(--gray-900);
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .patient-avatar {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    background: var(--gradient-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: 700;
    font-size: 14px;
    flex-shrink: 0;
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .empty-state i {
    font-size: 64px;
    color: var(--gray-300);
    margin-bottom: 20px;
  }

  .empty-state h4 {
    font-size: 18px;
    font-weight: 700;
    color: var(--gray-600);
    margin-bottom: 8px;
  }

  .empty-state p {
    color: var(--gray-500);
    max-width: 400px;
    margin: 0 auto;
  }

  /* Mobile Cards */
  .mobile-cards {
    display: none;
  }

  .patient-card {
    background: white;
    border-radius: var(--border-radius);
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: var(--shadow);
    transition: var(--transition);
    border-left: 4px solid var(--primary);
  }

  .patient-card:hover {
    transform: translateY(-2px);
    box-shadow: var(--shadow-lg);
  }

  .card-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 2px solid var(--gray-200);
  }

  .card-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid var(--gray-100);
  }

  .card-row:last-child {
    border-bottom: none;
  }

  .card-label {
    font-size: 12px;
    color: var(--gray-600);
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .card-value {
    font-size: 14px;
    color: var(--gray-900);
    font-weight: 500;
    text-align: right;
  }

  .card-actions {
    display: flex;
    gap: 8px;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 2px solid var(--gray-200);
  }

  .card-actions .btn {
    flex: 1;
    justify-content: center;
    padding: 10px 16px;
    font-size: 13px;
  }

  /* Responsive */
  @media (max-width: 1200px) {
    .filter-grid {
      grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
    }
  }

  @media (max-width: 992px) {
    .page {
      padding: 20px;
    }
    
    .page-head {
      flex-direction: column;
      align-items: flex-start;
      gap: 20px;
    }
    
    .actions {
      width: 100%;
      justify-content: flex-start;
    }
  }

  @media (max-width: 768px) {
    .stats {
      grid-template-columns: repeat(2, 1fr);
    }
    
    .filter-grid {
      grid-template-columns: 1fr;
    }
    
    .filter-actions {
      flex-direction: column;
    }
    
    .btn {
      width: 100%;
      justify-content: center;
    }

    .table {
      display: none;
    }

    .mobile-cards {
      display: block;
    }

    .page-title .icon-wrapper {
      width: 48px;
      height: 48px;
    }

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

  @media (max-width: 576px) {
    .stats {
      grid-template-columns: 1fr;
    }
    
    .page {
      padding: 16px;
    }

    .filter-container,
    .table-container {
      padding: 16px;
    }

    .patient-card {
      padding: 16px;
    }
    
    .table-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 15px;
    }
  }

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

  .page-head, .stats, .filter-container, .table-container {
    animation: fadeIn 0.5s ease forwards;
  }

  .stats { animation-delay: 0.1s; }
  .filter-container { animation-delay: 0.2s; }
  .table-container { animation-delay: 0.3s; }
</style>

<div class="page">
  <!-- Header -->
  <div class="page-head">
    <div class="page-title">
      <div class="icon-wrapper">
        <i class="bi bi-people-fill"></i>
      </div>
      <div>
        <h1>Hasta Yönetimi</h1>
        <p class="text-muted" style="color: var(--gray-600); font-size: 14px; margin-top: 4px;">
          Toplam <?= (int)($stat['total'] ?? 0) ?> hasta kaydı • Son 300 kayıt listeleniyor
        </p>
      </div>
    </div>
    <div class="actions">
      <a href="/dashboard.php" class="btn btn-outline">
        <i class="bi bi-arrow-left"></i>
        Panele Dön
      </a>
      <a href="/HastaModulu/hastaEkle.php" class="btn btn-primary">
        <i class="bi bi-plus-circle"></i>
        Yeni Hasta Ekle
      </a>
    </div>
  </div>

  <!-- Stats Cards -->
  <div class="stats">
    <div class="stat-card">
      <div class="label">
        <i class="bi bi-people"></i>
        Toplam Hasta
      </div>
      <div class="value"><?= (int)($stat['total'] ?? 0) ?></div>
      <div class="sub">Sistemde kayıtlı toplam hasta</div>
    </div>
    
    <div class="stat-card">
      <div class="label">
        <i class="bi bi-truck"></i>
        Servis Kullanımı
      </div>
      <div class="value"><?= (int)($stat['svc'] ?? 0) ?></div>
      <div class="sub">Servis ile gelen hastalar</div>
    </div>
    
    <div class="stat-card">
      <div class="label">
        <i class="bi bi-gender-male"></i>
        Erkek Hasta
      </div>
      <div class="value"><?= (int)($stat['male'] ?? 0) ?></div>
      <div class="sub">Toplam erkek hasta sayısı</div>
    </div>
    
    <div class="stat-card">
      <div class="label">
        <i class="bi bi-gender-female"></i>
        Kadın Hasta
      </div>
      <div class="value"><?= (int)($stat['female'] ?? 0) ?></div>
      <div class="sub">Toplam kadın hasta sayısı</div>
    </div>
  </div>

  <!-- Filter Form -->
  <div class="filter-container">
    <div class="filter-header">
      <h3><i class="bi bi-funnel"></i> Hasta Filtreleme</h3>
    </div>
    
    <form method="get" aria-label="Hasta filtreleri">
      <div class="filter-grid">
        <div class="form-group">
          <label class="form-label">Arama (Ad, Soyad, TCKN)</label>
          <input type="text" name="q" value="<?= htmlspecialchars($q) ?>" 
                 class="form-control" placeholder="Hasta adı, soyadı veya TCKN">
        </div>
        
        <div class="form-group">
          <label class="form-label">İl</label>
          <select name="city" id="cityFilter" class="form-control">
            <option value="">Tüm İller</option>
            <?php foreach($cities as $c): ?>
              <option value="<?= htmlspecialchars($c) ?>" <?= ($city===$c)?'selected':'' ?>>
                <?= htmlspecialchars($c) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">İlçe</label>
          <select name="district" id="districtFilter" class="form-control" <?= empty($city) ? 'disabled' : '' ?>>
            <option value="">Tüm İlçeler</option>
            <?php foreach($districts as $d): ?>
              <option value="<?= htmlspecialchars($d) ?>" <?= ($district===$d)?'selected':'' ?>>
                <?= htmlspecialchars($d) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Kurum</label>
          <select name="institution" class="form-control">
            <option value="">Tüm Kurumlar</option>
            <?php foreach($institutions as $inst): ?>
              <option value="<?= (int)$inst['id'] ?>" <?= ($institution==(string)$inst['id'])?'selected':'' ?>>
                <?= htmlspecialchars($inst['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Servis Durumu</label>
          <select name="service" class="form-control">
            <option value="">Tümü</option>
            <option value="1" <?= $service==='1'?'selected':'' ?>>Servis ile Gelen</option>
            <option value="0" <?= $service==='0'?'selected':'' ?>>Kendi İmkanı ile Gelen</option>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Cinsiyet</label>
          <select name="gender" class="form-control">
            <option value="">Tümü</option>
            <option value="male" <?= $gender==='male'?'selected':'' ?>>Erkek</option>
            <option value="female" <?= $gender==='female'?'selected':'' ?>>Kadın</option>
            <option value="other" <?= $gender==='other'?'selected':'' ?>>Diğer</option>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Kan Grubu</label>
          <select name="blood" class="form-control">
            <option value="">Tüm Kan Grupları</option>
            <?php foreach($bloods as $b): ?>
              <option value="<?= htmlspecialchars($b) ?>" <?= ($blood===$b)?'selected':'' ?>>
                <?= htmlspecialchars($b) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Sıralama</label>
          <select name="sort" class="form-control">
            <option value="">Varsayılan (En Yeni)</option>
            <option value="name_asc" <?= $sort==='name_asc'?'selected':'' ?>>Ad Soyad (A-Z)</option>
            <option value="name_desc" <?= $sort==='name_desc'?'selected':'' ?>>Ad Soyad (Z-A)</option>
            <option value="date_asc" <?= $sort==='date_asc'?'selected':'' ?>>Tarih (En Eski)</option>
            <option value="date_desc" <?= $sort==='date_desc'?'selected':'' ?>>Tarih (En Yeni)</option>
            <option value="city_asc" <?= $sort==='city_asc'?'selected':'' ?>>Şehir (A-Z)</option>
          </select>
        </div>
      </div>
      
      <div class="filter-actions">
        <button type="submit" class="btn btn-primary">
          <i class="bi bi-search"></i>
          Filtrele
        </button>
        <a href="/HastaModulu/hastaListe.php" class="btn btn-outline">
          <i class="bi bi-x-circle"></i>
          Filtreleri Temizle
        </a>
      </div>
    </form>
  </div>

  <!-- Results Table -->
  <div class="table-container">
    <div class="table-header">
      <h3><i class="bi bi-list-ul"></i> Hasta Listesi</h3>
      <div class="text-muted" style="color: var(--gray-600); font-size: 14px;">
        <?= count($rows) ?> kayıt listeleniyor
      </div>
    </div>
    
    <?php if(!$rows): ?>
      <div class="empty-state">
        <i class="bi bi-search"></i>
        <h4>Hasta kaydı bulunamadı</h4>
        <p>Filtre kriterlerinize uygun hasta kaydı bulunamadı. Filtreleri değiştirip tekrar deneyin.</p>
      </div>
    <?php else: ?>
      <!-- Desktop Table View -->
      <table class="table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Hasta Bilgisi</th>
            <th>TCKN</th>
            <th>Telefon</th>
            <th>Lokasyon</th>
            <th>Kurum</th>
            <th>Geliş Nedeni</th>
            <th>Kan Grubu</th>
            <th>Servis</th>
            <th>Kayıt Tarihi</th>
            <th>İşlem</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach($rows as $r): 
            $firstLetter = mb_substr($r['first_name'], 0, 1, 'UTF-8');
            $avatarColor = match(strtolower($r['gender'] ?? '')) {
              'male' => 'linear-gradient(135deg, #4361ee, #3a56d4)',
              'female' => 'linear-gradient(135deg, #f72585, #b5179e)',
              default => 'linear-gradient(135deg, #7209b7, #560bad)'
            };
          ?>
            <tr>
              <td><strong>#<?= (int)$r['id'] ?></strong></td>
              <td>
                <div class="patient-name">
                  <div class="patient-avatar" style="background: <?= $avatarColor ?>;">
                    <?= $firstLetter ?>
                  </div>
                  <div>
                    <?= htmlspecialchars($r['first_name'] . ' ' . $r['last_name']) ?>
                    <div style="font-size: 12px; color: var(--gray-600); margin-top: 2px;">
                      <?= htmlspecialchars($r['gender'] ?? 'Belirtilmemiş') ?>
                    </div>
                  </div>
                </div>
              </td>
              <td><?= htmlspecialchars($r['national_id'] ?? '-') ?></td>
              <td><?= htmlspecialchars($r['phone'] ?? '-') ?></td>
              <td>
                <?php if(!empty($r['city'])): ?>
                  <div style="font-weight: 600;"><?= htmlspecialchars($r['city']) ?></div>
                  <div style="font-size: 12px; color: var(--gray-600);"><?= htmlspecialchars($r['district'] ?? 'Belirtilmemiş') ?></div>
                <?php else: ?>
                  <span style="color: var(--gray-500);">Belirtilmemiş</span>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($r['institution'] ?? '-') ?></td>
              <td>
                <?php if(!empty($r['referral_reason'])): ?>
                  <span style="font-size: 13px; color: #334155;">
                    <?= htmlspecialchars($r['referral_reason']) ?>
                  </span>
                <?php else: ?>
                  <span style="color: var(--gray-500);">-</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if(!empty($r['blood_type'])): ?>
                  <span class="badge badge-danger">
                    <i class="bi bi-droplet"></i>
                    <?= htmlspecialchars($r['blood_type']) ?>
                  </span>
                <?php else: ?>
                  <span style="color: var(--gray-500);">-</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if((int)($r['service_needed'] ?? 0) === 1): ?>
                  <span class="badge badge-success">
                    <i class="bi bi-truck"></i>
                    Servis ile
                  </span>
                <?php else: ?>
                  <span class="badge badge-secondary">
                    <i class="bi bi-person-walking"></i>
                    Kendi imkanı
                  </span>
                <?php endif; ?>
              </td>
              <td>
                <div style="font-weight: 600; font-size: 13px;">
                  <?= date('d.m.Y', strtotime($r['created_at'] ?? '')) ?>
                </div>
                <div style="font-size: 12px; color: var(--gray-600);">
                  <?= date('H:i', strtotime($r['created_at'] ?? '')) ?>
                </div>
              </td>
              <td style="white-space:nowrap;">
                <a class="btn btn-outline" href="/HastaModulu/hastaDetay.php?id=<?= (int)$r['id'] ?>"><i class="bi bi-card-text"></i> Detay</a>
                <a class="btn btn-outline" href="/HastaModulu/onamArsiv.php?patient_id=<?= (int)$r['id'] ?>"><i class="bi bi-file-earmark-medical"></i> Belgeler</a>
                <a class="btn btn-primary" href="/HastaModulu/hastaDuzenle.php?id=<?= (int)$r['id'] ?>"><i class="bi bi-pencil-square"></i> Düzenle</a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>

      <!-- Mobile Card View -->
      <div class="mobile-cards">
        <?php foreach($rows as $r): 
          $firstLetter = mb_substr($r['first_name'], 0, 1, 'UTF-8');
          $avatarColor = match(strtolower($r['gender'] ?? '')) {
            'male' => 'linear-gradient(135deg, #4361ee, #3a56d4)',
            'female' => 'linear-gradient(135deg, #f72585, #b5179e)',
            default => 'linear-gradient(135deg, #7209b7, #560bad)'
          };
        ?>
          <div class="patient-card">
            <div class="card-header">
              <div class="patient-avatar" style="background: <?= $avatarColor ?>; width: 48px; height: 48px; font-size: 18px;">
                <?= $firstLetter ?>
              </div>
              <div style="flex: 1;">
                <div style="font-weight: 700; font-size: 16px; color: var(--gray-900); margin-bottom: 4px;">
                  <?= htmlspecialchars($r['first_name'] . ' ' . $r['last_name']) ?>
                </div>
                <div style="font-size: 12px; color: var(--gray-600);">
                  #<?= (int)$r['id'] ?> • <?= htmlspecialchars($r['gender'] ?? 'Belirtilmemiş') ?>
                </div>
              </div>
            </div>

            <div class="card-row">
              <span class="card-label">TCKN</span>
              <span class="card-value"><?= htmlspecialchars($r['national_id'] ?? '-') ?></span>
            </div>

            <div class="card-row">
              <span class="card-label">Telefon</span>
              <span class="card-value"><?= htmlspecialchars($r['phone'] ?? '-') ?></span>
            </div>

            <div class="card-row">
              <span class="card-label">Lokasyon</span>
              <span class="card-value">
                <?php if(!empty($r['city'])): ?>
                  <?= htmlspecialchars($r['city']) ?>
                  <?php if(!empty($r['district'])): ?> / <?= htmlspecialchars($r['district']) ?><?php endif; ?>
                <?php else: ?>
                  -
                <?php endif; ?>
              </span>
            </div>

            <div class="card-row">
              <span class="card-label">Kurum</span>
              <span class="card-value"><?= htmlspecialchars($r['institution'] ?? '-') ?></span>
            </div>

            <div class="card-row">
              <span class="card-label">Kan Grubu</span>
              <span class="card-value">
                <?php if(!empty($r['blood_type'])): ?>
                  <span class="badge badge-danger">
                    <i class="bi bi-droplet"></i>
                    <?= htmlspecialchars($r['blood_type']) ?>
                  </span>
                <?php else: ?>
                  -
                <?php endif; ?>
              </span>
            </div>

            <div class="card-row">
              <span class="card-label">Servis</span>
              <span class="card-value">
                <?php if((int)($r['service_needed'] ?? 0) === 1): ?>
                  <span class="badge badge-success">
                    <i class="bi bi-truck"></i>
                    Servis
                  </span>
                <?php else: ?>
                  <span class="badge badge-secondary">
                    <i class="bi bi-person-walking"></i>
                    Kendi
                  </span>
                <?php endif; ?>
              </span>
            </div>

            <div class="card-row">
              <span class="card-label">Kayıt</span>
              <span class="card-value">
                <?= date('d.m.Y H:i', strtotime($r['created_at'] ?? '')) ?>
              </span>
            </div>

            <div class="card-actions">
              <a class="btn btn-outline" href="/HastaModulu/hastaDetay.php?id=<?= (int)$r['id'] ?>">
                <i class="bi bi-card-text"></i> Detay
              </a>
              <a class="btn btn-outline" href="/HastaModulu/onamArsiv.php?patient_id=<?= (int)$r['id'] ?>">
                <i class="bi bi-file-earmark-medical"></i> Belgeler
              </a>
              <a class="btn btn-primary" href="/HastaModulu/hastaDuzenle.php?id=<?= (int)$r['id'] ?>">
                <i class="bi bi-pencil-square"></i> Düzenle
              </a>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
</div>

<script>
  // İl seçildiğinde ilçe dropdown'ını aktif et
  document.getElementById('cityFilter')?.addEventListener('change', function() {
    const districtFilter = document.getElementById('districtFilter');
    
    if (this.value) {
      // Formu submit etmek yerine AJAX ile ilçeleri yükleyebiliriz
      // Ancak mevcut mantığı koruyarak formu submit ediyoruz
      this.form.submit();
    } else {
      districtFilter.disabled = true;
      this.form.submit();
    }
  });

  // Tarih formatlama (mevcut tarihler için)
  document.addEventListener('DOMContentLoaded', function() {
    // Hover efekti için
    const tableRows = document.querySelectorAll('.table tbody tr');
    tableRows.forEach(row => {
      row.addEventListener('mouseenter', function() {
        this.style.transform = 'scale(1.002)';
        this.style.boxShadow = '0 5px 15px rgba(0,0,0,0.05)';
      });
      
      row.addEventListener('mouseleave', function() {
        this.style.transform = 'scale(1)';
        this.style.boxShadow = 'none';
      });
    });
    
    // İlçe dropdown'ı için durum kontrolü
    const cityFilter = document.getElementById('cityFilter');
    const districtFilter = document.getElementById('districtFilter');
    
    if (cityFilter && !cityFilter.value) {
      districtFilter.disabled = true;
    }
  });
</script>

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