<?php
declare(strict_types=1);

/**
 * NEPHRO LINK - HASTA LİSTESİ (Full-Width + Mobil Uyumlu)
 */

if (session_status() === PHP_SESSION_NONE) { session_start(); }
$root = realpath(__DIR__ . '/..');

/* Auth resolve */
$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 include */
$dbCandidates = [
  $root . '/core/db.php',
  $root . '/db.php',
  $root . '/config/db.php',
  $root . '/includes/db.php',
];
$dbLoaded = false;
foreach ($dbCandidates as $p) {
  if (is_file($p)) { require_once $p; $dbLoaded = true; break; }
}
if (!$dbLoaded) {
  http_response_code(500);
  echo "DB include bulunamadı. core/db.php yolunu kontrol et.";
  exit;
}

/* PDO resolve */
global $pdo, $db, $conn;
if (!isset($pdo) || !($pdo instanceof PDO)) {
  if (isset($db) && $db instanceof PDO) $pdo = $db;
  elseif (isset($conn) && $conn instanceof PDO) $pdo = $conn;
}
if (!isset($pdo) || !($pdo instanceof PDO)) {
  http_response_code(500);
  echo "PDO bulunamadı. core/db.php içinde \$pdo tanımlı olmalı.";
  exit;
}

/* Helpers */
if (!function_exists('e')) {
  function e(?string $s): string { return htmlspecialchars((string)($s ?? ''), ENT_QUOTES, 'UTF-8'); }
}
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 column_exists(PDO $pdo, string $table, string $col): bool {
  $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?");
  $st->execute([$table, $col]);
  return (int)$st->fetchColumn() > 0;
}
function pick_col(PDO $pdo, string $table, array $candidates): ?string {
  foreach ($candidates as $c) if (column_exists($pdo, $table, $c)) return $c;
  return null;
}
function age_from_date(?string $date): string {
  if (!$date) return '-';
  $d = date_create($date);
  if (!$d) return '-';
  $now = new DateTime();
  return (string)$now->diff($d)->y;
}
function badge_class(string $durum): string {
  $durum = mb_strtolower(trim($durum));
  return match($durum){
    'aktif' => 'nl-b-green',
    'pasif' => 'nl-b-gray',
    'nakil' => 'nl-b-blue',
    'vefat' => 'nl-b-red',
    'arsiv' => 'nl-b-amber',
    default => 'nl-b-gray',
  };
}

/* Table + Columns */
$table = 'hastalar';
if (!table_exists($pdo, $table)) {
  echo "<div style='padding:16px'>hastalar tablosu bulunamadı.</div>";
  exit;
}

$col_id        = 'id';
$col_tc        = pick_col($pdo, $table, ['tc_no','tc']);
$col_dosya     = pick_col($pdo, $table, ['dosya_no','dosyano','hasta_no']);
$col_ad        = pick_col($pdo, $table, ['ad','adi','isim']);
$col_soyad     = pick_col($pdo, $table, ['soyad','soyadi']);
$col_tel1      = pick_col($pdo, $table, ['telefon1','telefon','tel','gsm']);
$col_tel2      = pick_col($pdo, $table, ['telefon2','tel2','gsm2']);
$col_mail      = pick_col($pdo, $table, ['email','eposta']);
$col_cinsiyet  = pick_col($pdo, $table, ['cinsiyet','gender']);
$col_dogum     = pick_col($pdo, $table, ['dogum_tarihi','dogum','birth_date']);
$col_durum     = pick_col($pdo, $table, ['durum','status']);
$col_created   = pick_col($pdo, $table, ['created_at','kayit_tarihi','created']);
$col_il        = pick_col($pdo, $table, ['il','city','sehir']);
$col_ilce      = pick_col($pdo, $table, ['ilce','district']);

/* Filters */
$q        = trim((string)($_GET['q'] ?? ''));
$durum    = trim((string)($_GET['durum'] ?? ''));
$cinsiyet = trim((string)($_GET['cinsiyet'] ?? ''));
$il       = trim((string)($_GET['il'] ?? ''));
$ilce     = trim((string)($_GET['ilce'] ?? ''));
$sort = trim((string)($_GET['sort'] ?? 'ad'));
$dir  = strtolower(trim((string)($_GET['dir'] ?? 'asc'))) === 'desc' ? 'desc' : 'asc';

$page = max(1, (int)($_GET['p'] ?? 1));
$pp   = (int)($_GET['pp'] ?? 25);
$pp   = max(10, min(100, $pp));
$off  = ($page - 1) * $pp;

/* WHERE */
$where = [];
$params = [];

if ($q !== '') {
  $like = "%{$q}%";
  $or = [];
  if ($col_ad)    { $or[] = "h.`{$col_ad}` LIKE ?";    $params[] = $like; }
  if ($col_soyad) { $or[] = "h.`{$col_soyad}` LIKE ?"; $params[] = $like; }
  if ($col_tc)    { $or[] = "h.`{$col_tc}` LIKE ?";    $params[] = $like; }
  if ($col_dosya) { $or[] = "h.`{$col_dosya}` LIKE ?"; $params[] = $like; }
  if ($col_tel1)  { $or[] = "h.`{$col_tel1}` LIKE ?";  $params[] = $like; }
  if ($col_il)    { $or[] = "h.`{$col_il}` LIKE ?";    $params[] = $like; }
  if ($col_ilce)  { $or[] = "h.`{$col_ilce}` LIKE ?";  $params[] = $like; }
  if ($or) $where[] = "(" . implode(" OR ", $or) . ")";
}

if ($durum !== '' && $col_durum) { $where[] = "h.`{$col_durum}` = ?"; $params[] = $durum; }
if ($cinsiyet !== '' && $col_cinsiyet) { $where[] = "h.`{$col_cinsiyet}` = ?"; $params[] = $cinsiyet; }
if ($il !== '' && $col_il) { $where[] = "h.`{$col_il}` = ?"; $params[] = $il; }
if ($ilce !== '' && $col_ilce) { $where[] = "h.`{$col_ilce}` = ?"; $params[] = $ilce; }

$whereSql = $where ? ("WHERE " . implode(" AND ", $where)) : "";

/* Sorting */
$sortMap = [
  'ad'     => $col_ad ? "h.`{$col_ad}`" : "h.`id`",
  'dosya'  => $col_dosya ? "h.`{$col_dosya}`" : "h.`id`",
  'tc'     => $col_tc ? "h.`{$col_tc}`" : "h.`id`",
  'durum'  => $col_durum ? "h.`{$col_durum}`" : "h.`id`",
  'kayit'  => $col_created ? "h.`{$col_created}`" : "h.`id`",
];
$orderBy = $sortMap[$sort] ?? ($col_ad ? "h.`{$col_ad}`" : "h.`id`");
$orderSql = "ORDER BY {$orderBy} {$dir}, h.`id` DESC";

/* Count total */
$st = $pdo->prepare("SELECT COUNT(*) FROM hastalar h {$whereSql}");
$st->execute($params);
$total = (int)$st->fetchColumn();

/* Stats */
$stat_aktif = $stat_pasif = 0;
if ($col_durum) {
  $st = $pdo->prepare("SELECT
      SUM(CASE WHEN h.`{$col_durum}`='aktif' THEN 1 ELSE 0 END) AS aktif,
      SUM(CASE WHEN h.`{$col_durum}`='pasif' THEN 1 ELSE 0 END) AS pasif
    FROM hastalar h {$whereSql}");
  $st->execute($params);
  $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
  $stat_aktif = (int)($row['aktif'] ?? 0);
  $stat_pasif = (int)($row['pasif'] ?? 0);
}

/* Data query */
$select = [
  "h.`id` AS id",
  ($col_ad ? "h.`{$col_ad}` AS ad" : "'' AS ad"),
  ($col_soyad ? "h.`{$col_soyad}` AS soyad" : "'' AS soyad"),
  ($col_tc ? "h.`{$col_tc}` AS tc_no" : "NULL AS tc_no"),
  ($col_dosya ? "h.`{$col_dosya}` AS dosya_no" : "NULL AS dosya_no"),
  ($col_tel1 ? "h.`{$col_tel1}` AS telefon1" : "NULL AS telefon1"),
  ($col_tel2 ? "h.`{$col_tel2}` AS telefon2" : "NULL AS telefon2"),
  ($col_mail ? "h.`{$col_mail}` AS email" : "NULL AS email"),
  ($col_cinsiyet ? "h.`{$col_cinsiyet}` AS cinsiyet" : "NULL AS cinsiyet"),
  ($col_dogum ? "h.`{$col_dogum}` AS dogum_tarihi" : "NULL AS dogum_tarihi"),
  ($col_durum ? "h.`{$col_durum}` AS durum" : "'-' AS durum"),
  ($col_created ? "h.`{$col_created}` AS created_at" : "NULL AS created_at"),
  ($col_il ? "h.`{$col_il}` AS il" : "NULL AS il"),
  ($col_ilce ? "h.`{$col_ilce}` AS ilce" : "NULL AS ilce"),
];

// Export handling: POST export_selected (selected ids, xlsx/csv) OR GET export=csv (all filtered rows as CSV)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'export_selected') {
  $exportType = ($_POST['export_type'] ?? 'xlsx');
  $ids = $_POST['selected_ids'] ?? [];
  $ids = array_values(array_filter(array_map('intval', (array)$ids), fn($v)=>$v>0));

  if (!$ids) {
    // No selection: redirect back
    header('Location: ' . (string)($_SERVER['REQUEST_URI'] ?? $selfPath)); exit;
  }

  $placeholders = implode(',', array_fill(0, count($ids), '?'));
  $sqlSel = "SELECT " . implode(", ", $select) . " FROM hastalar h WHERE h.`id` IN ($placeholders) ORDER BY FIELD(h.`id`, " . implode(',', $ids) . ")";
  $st2 = $pdo->prepare($sqlSel);
  $st2->execute($ids);
  $allRows = $st2->fetchAll(PDO::FETCH_ASSOC) ?: [];

  // XLSX using PhpSpreadsheet if requested and available
  if (strtolower($exportType) === 'xlsx') {
    // try to load Composer autoload (if packages are installed)
    if (file_exists(__DIR__ . '/../vendor/autoload.php')) {
      require_once __DIR__ . '/../vendor/autoload.php';
    }

    if (class_exists('PhpOffice\\PhpSpreadsheet\\Spreadsheet')) {
      $sheetTitles = ['id','ad','soyad','tc_no','dosya_no','telefon1','telefon2','email','cinsiyet','dogum_tarihi','durum','created_at','il','ilce'];

      $spreadsheet = new PhpOffice\\PhpSpreadsheet\\Spreadsheet();
      $sheet = $spreadsheet->getActiveSheet();
      $sheet->fromArray($sheetTitles, null, 'A1');

      $r = 2;
      foreach ($allRows as $rw) {
        $sheet->fromArray([
          $rw['id'] ?? '',
          $rw['ad'] ?? '',
          $rw['soyad'] ?? '',
          $rw['tc_no'] ?? '',
          $rw['dosya_no'] ?? '',
          $rw['telefon1'] ?? '',
          $rw['telefon2'] ?? '',
          $rw['email'] ?? '',
          $rw['cinsiyet'] ?? '',
          $rw['dogum_tarihi'] ?? '',
          $rw['durum'] ?? '',
          $rw['created_at'] ?? '',
          $rw['il'] ?? '',
          $rw['ilce'] ?? ''
        ], null, 'A' . $r);
        $r++;
      }

      // autosize columns
      foreach (range('A', $sheet->getHighestColumn()) as $col) {
        $sheet->getColumnDimension($col)->setAutoSize(true);
      }

      header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      header('Content-Disposition: attachment; filename=hasta_list_sel_' . date('Ymd_His') . '.xlsx');

      $writer = new PhpOffice\\PhpSpreadsheet\\Writer\\Xlsx($spreadsheet);
      $writer->save('php://output');
      exit;
    }
    // else fallthrough to CSV fallback below
  }

  // Fallback to CSV
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=hasta_list_sel_' . date('Ymd_His') . '.csv');
  echo "\xEF\xBB\xBF"; // UTF-8 BOM
  $out = fopen('php://output', 'w');
  fputcsv($out, ['id','ad','soyad','tc_no','dosya_no','telefon1','telefon2','email','cinsiyet','dogum_tarihi','durum','created_at','il','ilce']);
  foreach ($allRows as $rw) {
    fputcsv($out, [
      $rw['id'] ?? '', $rw['ad'] ?? '', $rw['soyad'] ?? '', $rw['tc_no'] ?? '', $rw['dosya_no'] ?? '',
      $rw['telefon1'] ?? '', $rw['telefon2'] ?? '', $rw['email'] ?? '', $rw['cinsiyet'] ?? '',
      $rw['dogum_tarihi'] ?? '', $rw['durum'] ?? '', $rw['created_at'] ?? '', $rw['il'] ?? '', $rw['ilce'] ?? ''
    ]);
  }
  fclose($out);
  exit;
}

// CSV export (tüm filtrelerle eşleşen kayıtları dışa aktar)
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  $csvSql = "SELECT " . implode(", ", $select) . " FROM hastalar h {$whereSql} {$orderSql}";
  $st2 = $pdo->prepare($csvSql);
  $st2->execute($params);
  $allRows = $st2->fetchAll(PDO::FETCH_ASSOC) ?: [];

  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=hasta_list_' . date('Ymd_His') . '.csv');
  echo "\xEF\xBB\xBF"; // UTF-8 BOM

  $out = fopen('php://output', 'w');
  fputcsv($out, ['id','ad','soyad','tc_no','dosya_no','telefon1','telefon2','email','cinsiyet','dogum_tarihi','durum','created_at','il','ilce']);
  foreach ($allRows as $rw) {
    fputcsv($out, [
      $rw['id'] ?? '',
      $rw['ad'] ?? '',
      $rw['soyad'] ?? '',
      $rw['tc_no'] ?? '',
      $rw['dosya_no'] ?? '',
      $rw['telefon1'] ?? '',
      $rw['telefon2'] ?? '',
      $rw['email'] ?? '',
      $rw['cinsiyet'] ?? '',
      $rw['dogum_tarihi'] ?? '',
      $rw['durum'] ?? '',
      $rw['created_at'] ?? '',
      $rw['il'] ?? '',
      $rw['ilce'] ?? ''
    ]);
  }
  fclose($out);
  exit;
}

$sql = "SELECT " . implode(", ", $select) . " FROM hastalar h {$whereSql} {$orderSql} LIMIT {$pp} OFFSET {$off}";
$st = $pdo->prepare($sql);
$st->execute($params);
$rows = $st->fetchAll(PDO::FETCH_ASSOC) ?: [];

/* Pagination */
$totalPages = max(1, (int)ceil($total / $pp));
if ($page > $totalPages) { $page = $totalPages; }

/* Self URL */
$selfPath = (string)parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
$selfPath = $selfPath !== '' ? $selfPath : 'hastaListe.php';
$qsBase = $_GET; unset($qsBase['p']);
function build_self_url(string $selfPath, array $qs): string {
  $q = http_build_query($qs);
  return $q ? ($selfPath . '?' . $q) : $selfPath;
}
$clearUrl = $selfPath;

/* Options */
$durumOptions = [];
if ($col_durum) {
  $st = $pdo->query("SELECT DISTINCT `{$col_durum}` AS v FROM hastalar WHERE `{$col_durum}` IS NOT NULL AND `{$col_durum}`<>'' ORDER BY v ASC");
  $durumOptions = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
}
$cinsiyetOptions = [];
if ($col_cinsiyet) {
  $st = $pdo->query("SELECT DISTINCT `{$col_cinsiyet}` AS v FROM hastalar WHERE `{$col_cinsiyet}` IS NOT NULL AND `{$col_cinsiyet}`<>'' ORDER BY v ASC");
  $cinsiyetOptions = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
}
$ilOptions = [];
if ($col_il) {
  $st = $pdo->query("SELECT DISTINCT `{$col_il}` AS v FROM hastalar WHERE `{$col_il}` IS NOT NULL AND `{$col_il}`<>'' ORDER BY v ASC");
  $ilOptions = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
}
$ilceOptions = [];
if ($col_ilce) {
  if ($il !== '' && $col_il) {
    $st = $pdo->prepare("SELECT DISTINCT `{$col_ilce}` AS v FROM hastalar WHERE `{$col_ilce}` IS NOT NULL AND `{$col_ilce}`<>'' AND `{$col_il}` = ? ORDER BY v ASC");
    $st->execute([$il]);
    $ilceOptions = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
  } else {
    $st = $pdo->query("SELECT DISTINCT `{$col_ilce}` AS v FROM hastalar WHERE `{$col_ilce}` IS NOT NULL AND `{$col_ilce}`<>'' ORDER BY v ASC");
    $ilceOptions = $st->fetchAll(PDO::FETCH_COLUMN) ?: [];
  }
}

/* Module links */
$hrefNew    = 'hastaEkle.php';
$hrefDetail = 'hastaDetay.php';
$hrefEdit   = 'hastaDuzenle.php';

?><!doctype html>
<html lang="tr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>NephroLink | Hasta Listesi</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    :root {
      --primary: #2c3e50;
      --secondary: #3498db;
      --accent: #2980b9;
      --success: #27ae60;
      --warning: #f39c12;
      --danger: #e74c3c;
      --light: #ecf0f1;
      --dark: #2c3e50;
      --gray: #95a5a6;
      --border: #dfe6e9;
      --card-bg: #ffffff;
      --bg: #f8f9fa;
      --text: #2c3e50;
      --text-light: #7f8c8d;
      --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.06);
      --radius: 10px;
      --radius-sm: 6px;
      --transition: all 0.3s ease;
    }
    
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: var(--bg);
      color: var(--text);
      line-height: 1.6;
      font-size: 14px;
      overflow-x: hidden;
      width: 100%;
    }
    
    .nl-page {
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      width: 100%;
      overflow-x: hidden;
    }
    
    .nl-shell {
      width: 100%;
      padding: 0;
      flex: 1;
      margin: 0;
    }
    
    /* Topbar override */
    .topbar-container {
      width: 100% !important;
      max-width: none !important;
    }
    
    /* Başlık Alanı - Beyaz Arka Plan */
    .nl-head {
      width: 100%;
      background: white;
      padding: 25px 30px;
      color: var(--text);
      margin-bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      border-bottom: 1px solid var(--border);
    }
    
    .nl-title-container {
      display: flex;
      flex-direction: column;
      max-width: 100%;
      flex: 1;
    }
    
    .nl-title {
      display: flex;
      align-items: center;
      gap: 15px;
      font-size: 28px;
      font-weight: 600;
      color: var(--primary);
      margin-bottom: 5px;
    }
    
    .nl-title i {
      color: var(--secondary);
      font-size: 32px;
    }
    
    .nl-sub {
      color: var(--text-light);
      font-size: 15px;
      margin-top: 5px;
      font-weight: 400;
    }
    
    .nl-sub b {
      color: var(--primary);
    }
    
    /* Başlık Sağ Butonlar */
    .nl-header-right {
      display: flex;
      gap: 15px;
      align-items: center;
    }
    
    /* Butonlar */
    .nl-btn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 24px;
      border-radius: var(--radius-sm);
      font-weight: 600;
      font-size: 14px;
      cursor: pointer;
      text-decoration: none;
      border: 2px solid transparent;
      transition: var(--transition);
      white-space: nowrap;
      min-height: 44px;
    }
    
    .nl-btn i {
      font-size: 16px;
    }
    
    .nl-btn-default {
      background-color: white;
      border-color: var(--border);
      color: var(--text);
    }
    
    .nl-btn-default:hover {
      background-color: #f8f9fa;
      border-color: var(--secondary);
      transform: translateY(-2px);
      box-shadow: var(--shadow-sm);
    }
    
    .nl-btn-primary {
      background-color: var(--secondary);
      border-color: var(--secondary);
      color: white;
    }
    
    .nl-btn-primary:hover {
      background-color: var(--accent);
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(52, 152, 219, 0.3);
    }
    
    /* İçerik Alanı */
    .nl-content {
      width: 100%;
      padding: 25px 30px;
    }
    
    /* Kartlar - Full Width */
    .nl-card {
      background-color: var(--card-bg);
      border-radius: var(--radius);
      box-shadow: var(--shadow);
      border: 1px solid var(--border);
      margin-bottom: 25px;
      overflow: hidden;
      width: 100%;
    }
    
    .nl-card-header {
      padding: 22px 25px;
      border-bottom: 1px solid var(--border);
      background-color: #f8fafc;
      width: 100%;
    }
    
    .nl-card-header h2 {
      font-size: 20px;
      font-weight: 600;
      color: var(--primary);
      display: flex;
      align-items: center;
      gap: 12px;
    }
    
    .nl-card-header h2 i {
      color: var(--secondary);
    }
    
    .nl-card-body {
      padding: 25px;
      width: 100%;
    }
    
    /* Form Alanı - Responsive Grid */
    .nl-form {
      display: grid;
      grid-template-columns: repeat(6, 1fr);
      gap: 20px;
      align-items: end;
      width: 100%;
    }
    
    @media (max-width: 1400px) {
      .nl-form {
        grid-template-columns: repeat(4, 1fr);
      }
    }
    
    @media (max-width: 1100px) {
      .nl-form {
        grid-template-columns: repeat(3, 1fr);
      }
    }
    
    @media (max-width: 768px) {
      .nl-form {
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }
    }
    
    @media (max-width: 576px) {
      .nl-form {
        grid-template-columns: 1fr;
        gap: 12px;
      }
    }
    
    .nl-field {
      margin-bottom: 0;
      width: 100%;
    }

    /* small helper for inline metadata rows */
    .meta-block {
      margin-bottom: 8px;
      display:flex;
      align-items:center;
      gap:8px;
    }
    .meta-block .label { color: var(--text-light); font-size: 12px; }
    .meta-block .value { font-size: 14px; color: var(--text); }

    /* Bulk action bar */
    #bulkActions { border: 1px solid var(--border); background: #fff; border-radius: var(--radius); }

    /* Checkbox styling */
    .row-checkbox, #selectAll { width: 18px; height: 18px; transform: scale(1.06); }

    /* search wrapper */
    .nl-search-wrap { position: relative; }
    .nl-search-wrap .nl-inp { padding-right: 44px; }

    
    .nl-field label {
      display: block;
      font-size: 13px;
      font-weight: 600;
      color: var(--text);
      margin-bottom: 8px;
    }
    
    .nl-inp, .nl-sel {
      width: 100%;
      padding: 12px 15px;
      border: 1px solid var(--border);
      border-radius: var(--radius-sm);
      font-size: 14px;
      font-family: 'Segoe UI', sans-serif;
      color: var(--text);
      background-color: white;
      transition: var(--transition);
      min-height: 44px;
    }
    
    .nl-inp:focus, .nl-sel:focus {
      outline: none;
      border-color: var(--secondary);
      box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.15);
    }
    
    /* Filtre Butonları - Sağa Yaslı */
    .nl-filter-actions {
      display: flex;
      justify-content: flex-end;
      gap: 15px;
      margin-top: 25px;
      padding-top: 20px;
      border-top: 1px solid var(--border);
    }
    
    /* Badge */
    .nl-badge {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 6px 15px;
      border-radius: 50px;
      font-size: 12px;
      font-weight: 600;
      border: 1px solid transparent;
      white-space: nowrap;
      min-width: 70px;
      text-align: center;
    }
    
    .nl-b-green {
      background-color: rgba(39, 174, 96, 0.1);
      border-color: rgba(39, 174, 96, 0.2);
      color: #27ae60;
    }
    
    .nl-b-gray {
      background-color: rgba(149, 165, 166, 0.1);
      border-color: rgba(149, 165, 166, 0.2);
      color: #7f8c8d;
    }
    
    .nl-b-blue {
      background-color: rgba(52, 152, 219, 0.1);
      border-color: rgba(52, 152, 219, 0.2);
      color: #2980b9;
    }
    
    .nl-b-red {
      background-color: rgba(231, 76, 60, 0.1);
      border-color: rgba(231, 76, 60, 0.2);
      color: #c0392b;
    }
    
    .nl-b-amber {
      background-color: rgba(243, 156, 18, 0.1);
      border-color: rgba(243, 156, 18, 0.2);
      color: #d35400;
    }
    
    /* Tablo - Full Width */
    .nl-table-container {
      overflow-x: auto;
      border-radius: var(--radius-sm);
      width: 100%;
      -webkit-overflow-scrolling: touch;
    }
    
    .nl-table {
      width: 100%;
      min-width: 900px;
      border-collapse: collapse;
    }

    
    .nl-table thead {
      background-color: #f8fafc;
    }
    
    .nl-table th {
      padding: 18px 15px;
      text-align: left;
      font-weight: 600;
      font-size: 13px;
      color: var(--primary);
      border-bottom: 2px solid var(--border);
      white-space: nowrap;
    }
    
    .nl-table td {
      padding: 18px 15px;
      border-bottom: 1px solid var(--border);
      vertical-align: middle;
      font-size: 14px;
    }
    
    .nl-table tbody tr {
      transition: var(--transition);
    }
    
    .nl-table tbody tr:hover {
      background-color: #f8fafc;
    }
    
    .nl-table .patient-info h4 {
      font-weight: 600;
      color: var(--primary);
      margin-bottom: 5px;
      font-size: 15px;
    }
    
    .nl-table .patient-meta {
      font-size: 12px;
      color: var(--text-light);
    }
    
    .nl-table .patient-meta b {
      color: var(--primary);
    }
    
    /* Mobil Kart Görünümü */
    .nl-cards {
      display: none;
      gap: 15px;
      width: 100%;
    }
    
    @media (max-width: 992px) {
      .nl-table-container {
        display: none;
      }
      
      .nl-cards {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }
    }
    
    @media (max-width: 768px) {
      .nl-cards {
        grid-template-columns: 1fr;
      }
    }
    
    .nl-item {
      background-color: white;
      border-radius: var(--radius);
      padding: 20px;
      border: 1px solid var(--border);
      box-shadow: var(--shadow-sm);
      transition: var(--transition);
    }
    
    .nl-item:hover {
      transform: translateY(-3px);
      box-shadow: var(--shadow);
    }
    
    .nl-item-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 15px;
      flex-wrap: wrap;
      gap: 10px;
    }
    
    .nl-item-name {
      font-weight: 600;
      font-size: 16px;
      color: var(--primary);
      margin-bottom: 5px;
      word-break: break-word;
    }
    
    .nl-item-meta {
      font-size: 13px;
      color: var(--text-light);
      line-height: 1.5;
    }
    
    .nl-item-meta b {
      color: var(--primary);
    }
    
    .nl-item-actions {
      display: flex;
      gap: 10px;
      margin-top: 15px;
      flex-wrap: wrap;
    }
    
    /* Sayfalama */
    .nl-pagination {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 25px;
      border-top: 1px solid var(--border);
      flex-wrap: wrap;
      gap: 15px;
      width: 100%;
    }
    
    .nl-pagination-info {
      color: var(--text-light);
      font-size: 14px;
    }
    
    .nl-pagination-pages {
      display: flex;
      gap: 8px;
      flex-wrap: wrap;
      justify-content: center;
    }
    
    .nl-pagebtn {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      min-width: 44px;
      height: 44px;
      border-radius: var(--radius-sm);
      border: 1px solid var(--border);
      background-color: white;
      color: var(--text);
      font-weight: 600;
      font-size: 14px;
      text-decoration: none;
      transition: var(--transition);
      padding: 0 5px;
    }
    
    .nl-pagebtn:hover {
      background-color: #f8f9fa;
      border-color: var(--secondary);
    }
    
    .nl-pagebtn.active {
      background-color: var(--secondary);
      border-color: var(--secondary);
      color: white;
    }
    
    /* Footer */
    .nl-footer {
      width: 100%;
      text-align: center;
      padding: 25px 30px;
      color: var(--text-light);
      font-size: 14px;
      border-top: 1px solid var(--border);
      margin-top: 20px;
      background-color: white;
    }
    
    /* Boş Durum */
    .nl-empty-state {
      text-align: center;
      padding: 60px 20px;
      color: var(--text-light);
      width: 100%;
    }
    
    .nl-empty-state i {
      font-size: 56px;
      color: var(--border);
      margin-bottom: 20px;
    }
    
    .nl-empty-state h3 {
      font-size: 20px;
      color: var(--text-light);
      margin-bottom: 15px;
      font-weight: 500;
    }
    
    /* Responsive Düzenlemeler */
    @media (max-width: 768px) {
      .nl-head {
        padding: 20px;
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
      }
      
      .nl-header-right {
        width: 100%;
        justify-content: flex-start;
      }
      
      .nl-title {
        font-size: 24px;
      }
      
      .nl-title i {
        font-size: 28px;
      }
      
      .nl-content {
        padding: 20px;
      }
      
      .nl-card-body {
        padding: 20px;
      }
      
      .nl-filter-actions {
        flex-direction: column;
      }
      
      .nl-filter-actions .nl-btn {
        width: 100%;
      }
      
      .nl-pagination {
        flex-direction: column;
        text-align: center;
      }
    }
    
    @media (max-width: 480px) {
      .nl-head {
        padding: 15px;
      }
      
      .nl-title {
        font-size: 22px;
      }
      
      .nl-content {
        padding: 15px;
      }
      
      .nl-card-header,
      .nl-card-body {
        padding: 18px;
      }
      
      .nl-form {
        gap: 10px;
      }
      
      .nl-item-actions {
        flex-direction: column;
      }
      
      .nl-item-actions .nl-btn {
        width: 100%;
      }
    }
    
    /* Mobile touch improvements */
    @media (hover: none) {
      .nl-btn:hover,
      .nl-pagebtn:hover,
      .nl-item:hover {
        transform: none;
      }
      
      .nl-btn:active,
      .nl-pagebtn:active {
        background-color: #f0f0f0;
      }
      
      .nl-btn-primary:active {
        background-color: var(--accent);
      }
    }
  </style>
</head>

<body>
<?php
$topbar = $root . '/layout/topbar.php';
if (is_file($topbar)) {
  require_once $topbar;
} else {
  echo "<div style='padding:10px;color:#b91c1c;font-weight:600'>topbar.php bulunamadı: /layout/topbar.php</div>";
}
?>

<div class="nl-page">
  <div class="nl-shell">

    <!-- Başlık Alanı - Beyaz Arka Plan -->
    <div class="nl-head">
      <div class="nl-title-container">
        <div class="nl-title">
          <i class="bi bi-people-fill"></i>
          Hasta Listesi
        </div>
        <div class="nl-sub">
          Toplam <b><?= (int)$total ?></b> hasta
          <?php if($col_durum): ?>
            · <span class="nl-badge nl-b-green" style="margin:0 5px;">Aktif: <?= (int)$stat_aktif ?></span>
            · <span class="nl-badge nl-b-gray" style="margin:0 5px;">Pasif: <?= (int)$stat_pasif ?></span>
          <?php endif; ?>
          · Sayfa <b><?= (int)$page ?></b> / <b><?= (int)$totalPages ?></b>
        </div>
      </div>

      <?php $exportQs = $qsBase; $exportQs['export']='csv'; ?>
      <div class="nl-header-right">
        <a class="nl-btn nl-btn-default" href="<?= e(build_self_url($selfPath, $exportQs)) ?>">
          <i class="bi bi-file-earmark-arrow-down"></i> CSV Dışa Aktar
        </a>
        <a class="nl-btn nl-btn-primary" href="<?= e($hrefNew) ?>">
          <i class="bi bi-person-plus"></i> Yeni Hasta Ekle
        </a>
      </div>
    </div>

    <div class="nl-content">
      <div class="nl-card">
        <div class="nl-card-header">
          <h2><i class="bi bi-funnel"></i> Filtreleme ve Sıralama</h2>
        </div>
        <div class="nl-card-body">

          <!-- Bulk action bar (hidden until selection) -->
          <div class="nl-card" id="bulkActions" style="display:none; margin-bottom:12px;">
            <div class="nl-card-body" style="display:flex; justify-content:space-between; align-items:center; gap:12px;">
              <div><strong id="selectedCount">0</strong> kayıt seçili</div>
              <div style="display:flex; gap:8px;">
                <button type="button" class="nl-btn nl-btn-default" id="clearSelection">Seçimi Temizle</button>
                <button type="button" class="nl-btn nl-btn-default" id="exportCsvSelected">CSV Dışa Aktar</button>
                <button type="button" class="nl-btn nl-btn-primary" id="exportXlsxSelected">Excel (XLSX) Dışa Aktar</button>
              </div>
              <form id="bulkForm" method="post" style="display:none;">
                <input type="hidden" name="action" value="export_selected">
                <input type="hidden" name="export_type" id="exportTypeInput" value="xlsx">
              </form>
            </div>
          </div>

          <form method="get" class="nl-form" autocomplete="off" id="filterForm" role="search" aria-label="Hasta arama ve filtreleme">
            <div class="nl-field nl-search-wrap">
              <label for="qInput"><i class="bi bi-search"></i> Arama</label>
              <div style="position:relative;">
                <input id="qInput" class="nl-inp" type="text" name="q" value="<?= e($q) ?>" placeholder="Ad, soyad, TC, dosya no..." aria-label="Hasta arama">
                <button type="button" id="clearQ" class="nl-btn nl-btn-default" aria-label="Aramayı temizle" style="position:absolute; right:6px; top:6px; height:36px; padding:0 8px;"><i class="bi bi-x-lg"></i></button>
              </div>
            </div>

            <?php if($col_durum): ?>
            <div class="nl-field">
              <label><i class="bi bi-info-circle"></i> Durum</label>
              <select class="nl-sel" name="durum">
                <option value="">Tüm Durumlar</option>
                <?php foreach($durumOptions as $opt): ?>
                  <option value="<?= e((string)$opt) ?>" <?= ($durum===(string)$opt) ? 'selected' : '' ?>>
                    <?= e((string)$opt) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <?php endif; ?>

            <?php if($col_cinsiyet): ?>
            <div class="nl-field">
              <label><i class="bi bi-gender-ambiguous"></i> Cinsiyet</label>
              <select class="nl-sel" name="cinsiyet">
                <option value="">Tümü</option>
                <?php foreach($cinsiyetOptions as $opt): ?>
                  <option value="<?= e((string)$opt) ?>" <?= ($cinsiyet===(string)$opt) ? 'selected' : '' ?>>
                    <?= e((string)$opt) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <?php endif; ?>

            <?php if($col_il): ?>
            <div class="nl-field">
              <label><i class="bi bi-geo-alt"></i> İl</label>
              <select class="nl-sel" name="il" id="ilSelect">
                <option value="">Tüm İller</option>
                <?php foreach($ilOptions as $opt): ?>
                  <option value="<?= e((string)$opt) ?>" <?= ($il===(string)$opt) ? 'selected' : '' ?>>
                    <?= e((string)$opt) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <?php endif; ?>

            <?php if($col_ilce): ?>
            <div class="nl-field">
              <label><i class="bi bi-geo"></i> İlçe</label>
              <select class="nl-sel" name="ilce" id="ilceSelect" <?= empty($il) ? 'disabled' : '' ?>>
                <option value=""><?= empty($il) ? 'İl seçiniz' : 'Tüm İlçeler' ?></option>
                <?php foreach($ilceOptions as $opt): ?>
                  <option value="<?= e((string)$opt) ?>" <?= ($ilce===(string)$opt) ? 'selected' : '' ?>>
                    <?= e((string)$opt) ?>
                  </option>
                <?php endforeach; ?>
              </select>
            </div>
            <?php endif; ?>

            <div class="nl-field">
              <label><i class="bi bi-sort-alpha-down"></i> Sırala</label>
              <select class="nl-sel" name="sort">
                <option value="ad"    <?= $sort==='ad' ? 'selected':'' ?>>Ada Göre</option>
                <option value="dosya" <?= $sort==='dosya' ? 'selected':'' ?>>Dosya No</option>
                <option value="tc"    <?= $sort==='tc' ? 'selected':'' ?>>TC Kimlik</option>
                <option value="durum" <?= $sort==='durum' ? 'selected':'' ?>>Duruma Göre</option>
                <option value="kayit" <?= $sort==='kayit' ? 'selected':'' ?>>Kayıt Tarihi</option>
              </select>
            </div>

            <div class="nl-field">
              <label><i class="bi bi-arrow-up-down"></i> Sıralama Yönü</label>
              <select class="nl-sel" name="dir">
                <option value="asc"  <?= $dir==='asc' ? 'selected':'' ?>>Artan (A-Z)</option>
                <option value="desc" <?= $dir==='desc' ? 'selected':'' ?>>Azalan (Z-A)</option>
              </select>
            </div>

            <div class="nl-field">
              <label><i class="bi bi-file-text"></i> Sayfa Başına</label>
              <select class="nl-sel" name="pp">
                <?php foreach([10,25,50,100] as $x): ?>
                  <option value="<?= $x ?>" <?= $pp===$x ? 'selected':'' ?>><?= $x ?> Kayıt</option>
                <?php endforeach; ?>
              </select>
            </div>
          </form>

          <!-- Filtre Butonları - Sağa Yaslı -->
          <div class="nl-filter-actions">
            <a class="nl-btn nl-btn-default" href="<?= e($clearUrl) ?>">
              <i class="bi bi-arrow-clockwise"></i> Filtreyi Temizle
            </a>
            <button class="nl-btn nl-btn-primary" type="submit" form="filterForm">
              <i class="bi bi-funnel-fill"></i> Filtrele
            </button>
          </div>
        </div>
      </div>

      <div class="nl-card">
        <div class="nl-card-header">
          <h2><i class="bi bi-list-ul"></i> Hasta Listesi</h2>
        </div>
        
        <div class="nl-table-container">
          <table class="nl-table" role="table" aria-label="Hasta listesi">
            <colgroup>
              <col style="width:5%">
              <col style="width:25%">
              <col style="width:15%">
              <col style="width:20%">
              <col style="width:15%">
              <col style="width:10%">
              <col style="width:10%">
            </colgroup>
            <thead>
              <tr>
                <th scope="col"><input type="checkbox" id="selectAll" aria-label="Tümünü seç"></th>
                <th scope="col">Hasta Bilgileri</th>
                <th scope="col">Dosya / TC</th>
                <th scope="col">İletişim</th>
                <th scope="col">İl / İlçe</th>
                <th scope="col">Durum</th>
                <th scope="col">İşlemler</th>
              </tr>
            </thead>
            <tbody>
            <?php if(!$rows): ?>
              <tr>
                <td colspan="6">
                  <div class="nl-empty-state" role="status" aria-live="polite">
                    <i class="bi bi-people"></i>
                    <h3>Kayıt bulunamadı</h3>
                    <p>Filtrelerinizi değiştirerek tekrar deneyin</p>
                  </div>
                </td>
              </tr>
            <?php else: ?>
              <?php foreach($rows as $r): ?>
                <?php
                  $fullName = trim((string)($r['ad'] ?? '') . ' ' . (string)($r['soyad'] ?? ''));
                  $dosyaNo  = (string)($r['dosya_no'] ?? '');
                  $tcNo     = (string)($r['tc_no'] ?? '');
                  $dur      = (string)($r['durum'] ?? '-');
                  $tel1     = (string)($r['telefon1'] ?? '');
                  $tel2     = (string)($r['telefon2'] ?? '');
                  $mail     = (string)($r['email'] ?? '');
                  $yas      = age_from_date($r['dogum_tarihi'] ?? null);
                  $id       = (int)($r['id'] ?? 0);
                  $ilTxt    = (string)($r['il'] ?? '');
                  $ilceTxt  = (string)($r['ilce'] ?? '');
                  $cinsiyet = (string)($r['cinsiyet'] ?? '');
                ?>
                <tr>
                  <td><input type="checkbox" class="row-checkbox" value="<?= $id ?>" aria-label="Hasta <?= e($fullName ?: '-') ?> seç"></td>
                  <td>
                    <div class="patient-info">
                      <h4><?= e($fullName ?: '-') ?></h4>
                      <div class="patient-meta">
                        ID: <?= $id ?>
                        <?php if($yas !== '-'): ?> · Yaş: <b><?= e($yas) ?></b><?php endif; ?>
                        <?php if($cinsiyet): ?> · <?= e($cinsiyet) ?><?php endif; ?>
                      </div>
                    </div>
                  </td>

                  <td>
                    <div style="margin-bottom: 8px;">
                      <div class="patient-meta">Dosya No:</div>
                      <div><b><?= e($dosyaNo ?: '-') ?></b></div>
                    </div>
                    <div>
                      <div class="patient-meta">TC Kimlik:</div>
                      <div><?= $tcNo ? e(substr($tcNo,0,3).'******'.substr($tcNo,-2)) : '-' ?></div>
                    </div>
                  </td>

                  <td>
                    <?php if($tel1): ?>
                    <div class="meta-block">
                      <i class="bi bi-telephone" style="color: var(--secondary);"></i>
                      <div>
                        <div class="value"><?= e($tel1) ?></div>
                        <?php if($tel2): ?><div class="patient-meta"><?= e($tel2) ?></div><?php endif; ?>
                      </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if($mail): ?>
                    <div class="meta-block">
                      <i class="bi bi-envelope" style="color: var(--secondary);"></i>
                      <div class="patient-meta"><?= e($mail) ?></div>
                    </div>
                    <?php endif; ?>
                  </td>

                  <td>
                    <?php if($ilTxt || $ilceTxt): ?>
                    <div class="meta-block">
                      <i class="bi bi-geo-alt" style="color: var(--secondary);"></i>
                      <div>
                        <div class="value"><?= e($ilTxt ?: '') ?></div>
                        <?php if($ilceTxt): ?><div class="patient-meta"><?= e($ilceTxt) ?></div><?php endif; ?>
                      </div>
                    </div>
                    <?php else: ?>
                      <span class="patient-meta">-</span>
                    <?php endif; ?>
                  </td>

                  <td>
                    <span class="nl-badge <?= e(badge_class($dur)) ?>">
                      <?= e($dur) ?>
                    </span>
                  </td>

                  <td>
                    <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                      <a class="nl-btn nl-btn-default" href="<?= e($hrefDetail) ?>?id=<?= $id ?>" title="Detay">
                        <i class="bi bi-eye"></i> Detay
                      </a>
                      <a class="nl-btn nl-btn-primary" href="<?= e($hrefEdit) ?>?id=<?= $id ?>" title="Düzenle">
                        <i class="bi bi-pencil-square"></i> Düzenle
                      </a>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
          </table>
        </div>

        <div class="nl-cards">
          <?php if(!$rows): ?>
            <div class="nl-empty-state" role="status" aria-live="polite">
              <i class="bi bi-people"></i>
              <h3>Kayıt bulunamadı</h3>
              <p>Filtrelerinizi değiştirerek tekrar deneyin</p>
            </div>
          <?php else: ?>
            <?php foreach($rows as $r): ?>
              <?php
                $fullName = trim((string)($r['ad'] ?? '') . ' ' . (string)($r['soyad'] ?? ''));
                $dosyaNo  = (string)($r['dosya_no'] ?? '');
                $tcNo     = (string)($r['tc_no'] ?? '');
                $dur      = (string)($r['durum'] ?? '-');
                $tel1     = (string)($r['telefon1'] ?? '');
                $yas      = age_from_date($r['dogum_tarihi'] ?? null);
                $id       = (int)($r['id'] ?? 0);
                $ilTxt    = (string)($r['il'] ?? '');
                $ilceTxt  = (string)($r['ilce'] ?? '');
              ?>
              <div class="nl-item">
                <div class="nl-item-header">
                  <div>
                    <div class="nl-item-name"><?= e($fullName ?: '-') ?></div>
                    <div class="nl-item-meta">
                      ID: <?= $id ?> · Yaş: <b><?= e($yas) ?></b> · Dosya: <b><?= e($dosyaNo ?: '-') ?></b>
                    </div>
                    <div class="nl-item-meta">
                      TC: <?= $tcNo ? e(substr($tcNo,0,3).'******'.substr($tcNo,-2)) : '-' ?>
                    </div>
                  </div>
                  <span class="nl-badge <?= e(badge_class($dur)) ?>"><?= e($dur) ?></span>
                </div>
                
                <div class="nl-item-meta" style="margin-bottom: 10px;">
                  <div class="meta-block" style="margin-bottom:5px;">
                    <i class="bi bi-telephone" style="color: var(--secondary);"></i>
                    <span><?= e($tel1 ?: '-') ?></span>
                  </div>
                  <?php if($ilTxt || $ilceTxt): ?>
                  <div class="meta-block">
                    <span><?= e(($ilTxt ?: '-') . ($ilceTxt ? ' / ' . $ilceTxt : '')) ?></span>
                  </div>
                  <?php endif; ?>
                </div>

                <div class="nl-item-actions">
                  <a class="nl-btn nl-btn-default" href="<?= e($hrefDetail) ?>?id=<?= $id ?>">
                    <i class="bi bi-eye"></i> Detay
                  </a>
                  <a class="nl-btn nl-btn-primary" href="<?= e($hrefEdit) ?>?id=<?= $id ?>">
                    <i class="bi bi-pencil-square"></i> Düzenle
                  </a>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>

        <?php if($total > 0): ?>
        <div class="nl-pagination">
          <div class="nl-pagination-info">
            <?= $total ? (int)$off+1 : 0 ?>-<?= min($off+$pp, $total) ?> / <?= (int)$total ?> kayıt görüntüleniyor
          </div>

          <div class="nl-pagination-pages">
            <?php
              $start = max(1, $page - 2);
              $end   = min($totalPages, $page + 2);

              $prevQs = $qsBase; $prevQs['p']=max(1,$page-1);
              $nextQs = $qsBase; $nextQs['p']=min($totalPages,$page+1);
            ?>

            <a class="nl-pagebtn" href="<?= e(build_self_url($selfPath, $prevQs)) ?>" title="Önceki">
              <i class="bi bi-chevron-left"></i>
            </a>

            <?php if($start > 1): ?>
              <?php $qs = $qsBase; $qs['p']=1; ?>
              <a class="nl-pagebtn" href="<?= e(build_self_url($selfPath, $qs)) ?>">1</a>
              <?php if($start > 2): ?><span style="display:flex; align-items:center; padding:0 6px; color:var(--text-light);">...</span><?php endif; ?>
            <?php endif; ?>

            <?php for($i=$start; $i<=$end; $i++): ?>
              <?php $qs = $qsBase; $qs['p']=$i; ?>
              <a class="nl-pagebtn <?= $i===$page ? 'active':'' ?>" href="<?= e(build_self_url($selfPath, $qs)) ?>"><?= (int)$i ?></a>
            <?php endfor; ?>

            <?php if($end < $totalPages): ?>
              <?php if($end < $totalPages-1): ?><span style="display:flex; align-items:center; padding:0 6px; color:var(--text-light);">...</span><?php endif; ?>
              <?php $qs = $qsBase; $qs['p']=$totalPages; ?>
              <a class="nl-pagebtn" href="<?= e(build_self_url($selfPath, $qs)) ?>"><?= (int)$totalPages ?></a>
            <?php endif; ?>

            <a class="nl-pagebtn" href="<?= e(build_self_url($selfPath, $nextQs)) ?>" title="Sonraki">
              <i class="bi bi-chevron-right"></i>
            </a>
          </div>
        </div>
        <?php endif; ?>
      </div>

      <div class="nl-footer">
        <div>NephroLink Hasta Yönetim Sistemi &copy; <?= date('Y') ?></div>
        <div style="font-size: 12px; margin-top: 5px; color: var(--gray);">
          Veritabanı: <?= $total ?> kayıt · Son güncelleme: <?= date('d.m.Y H:i') ?>
        </div>
      </div>
    </div>

  </div>
</div>

<script>
  // İl/İlçe dropdown yönetimi
  document.addEventListener('DOMContentLoaded', function() {
    const ilSelect = document.getElementById('ilSelect');
    const ilceSelect = document.getElementById('ilceSelect');
    
    if (ilSelect && ilceSelect) {
      ilSelect.addEventListener('change', function() {
        const selectedIl = this.value;
        if (selectedIl) {
          ilceSelect.disabled = false;
          ilceSelect.innerHTML = '<option value="">Yükleniyor...</option>';
          
          // AJAX ile ilçeleri çek
          fetch('ajax/get_ilceler.php?il=' + encodeURIComponent(selectedIl))
            .then(response => response.json())
            .then(data => {
              ilceSelect.innerHTML = '<option value="">Tüm İlçeler</option>';
              data.forEach(ilce => {
                const option = document.createElement('option');
                option.value = ilce;
                option.textContent = ilce;
                ilceSelect.appendChild(option);
              });
              
              // URL'de ilçe seçiliyse onu işaretle
              const urlParams = new URLSearchParams(window.location.search);
              const selectedIlce = urlParams.get('ilce');
              if (selectedIlce) {
                ilceSelect.value = selectedIlce;
              }
            })
            .catch(error => {
              console.error('Error:', error);
              ilceSelect.innerHTML = '<option value="">Yüklenemedi</option>';
            });
        } else {
          ilceSelect.disabled = true;
          ilceSelect.innerHTML = '<option value="">İl seçiniz</option>';
        }
      });
      
      // Sayfa yüklendiğinde il seçiliyse ilçe dropdown'ını aktif et
      if (ilSelect.value) {
        ilceSelect.disabled = false;
      }
    }
    
    // Mobilde form submit butonu için touch feedback
    const filterButton = document.querySelector('button[type="submit"]');
    if (filterButton) {
      filterButton.addEventListener('touchstart', function() {
        this.style.transform = 'scale(0.98)';
      });
      
      filterButton.addEventListener('touchend', function() {
        this.style.transform = '';
      });
    }
    
    // Mobil kartlarda tıklama alanını büyüt
    const cards = document.querySelectorAll('.nl-item');
    cards.forEach(card => {
      card.style.cursor = 'pointer';
      card.addEventListener('click', function(e) {
        // ignore clicks on buttons or selection checkboxes
        if (!e.target.closest('.nl-btn') && !e.target.closest('.row-checkbox') && !e.target.closest('input[type="checkbox"]')) {
          const detailLink = this.querySelector('a[href*="hastaDetay"]');
          if (detailLink) {
            window.location = detailLink.href;
          }
        }
      });
    });

    // Selection / Bulk action handling
    const selectAll = document.getElementById('selectAll');
    const bulkActions = document.getElementById('bulkActions');
    const selectedCountEl = document.getElementById('selectedCount');
    const bulkForm = document.getElementById('bulkForm');
    const exportTypeInput = document.getElementById('exportTypeInput');

    function getRowCheckboxes(){ return Array.from(document.querySelectorAll('.row-checkbox')); }
    function updateSelection(){
      const chks = getRowCheckboxes();
      const checked = chks.filter(c => c.checked);
      selectedCountEl.textContent = checked.length;
      if (bulkActions) bulkActions.style.display = (checked.length ? 'block' : 'none');
      if (selectAll) selectAll.checked = (chks.length && chks.length === checked.length);
    }

    if (selectAll){
      selectAll.addEventListener('change', function(){
        getRowCheckboxes().forEach(cb => cb.checked = this.checked);
        updateSelection();
      });
    }

    getRowCheckboxes().forEach(cb => cb.addEventListener('change', updateSelection));

    document.getElementById('clearSelection')?.addEventListener('click', function(){
      getRowCheckboxes().forEach(cb => cb.checked = false);
      updateSelection();
    });

    function submitExport(type){
      const checked = getRowCheckboxes().filter(c => c.checked).map(c => c.value);
      if (!checked.length){ alert('Lütfen en az bir kayıt seçin'); return; }
      // remove old inputs
      Array.from(bulkForm.querySelectorAll('input[name="selected_ids[]"]')).forEach(n=>n.remove());
      checked.forEach(id => {
        const i = document.createElement('input'); i.type='hidden'; i.name='selected_ids[]'; i.value = id; bulkForm.appendChild(i);
      });
      exportTypeInput.value = type;
      bulkForm.submit();
    }

    document.getElementById('exportCsvSelected')?.addEventListener('click', function(){ submitExport('csv'); });
    document.getElementById('exportXlsxSelected')?.addEventListener('click', function(){ submitExport('xlsx'); });
    const clearQ = document.getElementById('clearQ');
    let debounceTimer = null;
    if (qInput) {
      qInput.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
          document.getElementById('filterForm').submit();
        }, 450);
      });
      if (clearQ) {
        clearQ.addEventListener('click', function(e) {
          e.preventDefault();
          qInput.value = '';
          document.getElementById('filterForm').submit();
        });
      }
    }
  });
</script>

</body>
</html>