<?php
/**
 * NEPHRO ERP - HASTA PORTFÖYÜ (FULL WIDTH + TYPO UPGRADE + RICH STATS)
 */
global $pdo;

if (!function_exists('h')) {
    function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, "UTF-8"); }
}

// Filtreleme değişkenleri
$q     = trim($_GET['q'] ?? '');
$hep   = trim($_GET['hep'] ?? '');
$damar = trim($_GET['damar'] ?? '');
$durum = trim($_GET['durum'] ?? '');
$sort  = trim($_GET['sort'] ?? 'ad');
$dir   = strtolower(trim($_GET['dir'] ?? 'asc')) === 'desc' ? 'desc' : 'asc';

// Sayfalama
$page = max(1, (int)($_GET['p'] ?? 1));
$perPage = (int)($_GET['pp'] ?? 50);
$perPage = min(max($perPage, 50), 100);
$offset = ($page - 1) * $perPage;

// ✅ URL oluşturma fonksiyonu (BU SAYFAYA ÖZEL - isim çakışmasın)
function buildUrlHasta($params = []) {
    $current = $_GET;
    $current['sayfa'] = $current['sayfa'] ?? 'hasta-liste';

    foreach ($params as $key => $value) {
        if ($value === null || $value === '') unset($current[$key]);
        else $current[$key] = $value;
    }
    return '?' . http_build_query($current);
}

// WHERE koşulları
$where = [];
$bindParams = [];

if ($q !== '') {
    $where[] = "(ad LIKE ? OR soyad LIKE ? OR tc_no LIKE ?)";
    $like = "%{$q}%";
    $bindParams[] = $like; $bindParams[] = $like; $bindParams[] = $like;
}

if ($hep === 'Negatif') {
    $where[] = "hepatit_durumu = 'Negatif'";
} elseif ($hep === 'Pozitif') {
    $where[] = "(hepatit_durumu IS NOT NULL AND hepatit_durumu <> '' AND hepatit_durumu <> 'Negatif')";
}

if ($damar !== '') {
    $where[] = "damar_yolu = ?";
    $bindParams[] = $damar;
}

if ($durum !== '') {
    $where[] = "durum = ?";
    $bindParams[] = $durum;
}

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

// =====================
// RICH STATS (GENEL)
// =====================
$stats = [
    'toplam' => 0,
    'aktif' => 0,
    'pasif' => 0,
    'heppoz' => 0,
    'hepneg' => 0,
    'diyabet' => 0,
    'bugun' => 0,
    'ort_yas' => 0,
    'ort_kuru' => 0,
    'avf' => 0,
    'avg' => 0,
    'kateter' => 0,
    'greft' => 0,
];

try {
    $stats = $pdo->query("
        SELECT
            COUNT(*) AS toplam,
            SUM(CASE WHEN durum='aktif' THEN 1 ELSE 0 END) AS aktif,
            SUM(CASE WHEN durum='pasif' THEN 1 ELSE 0 END) AS pasif,

            SUM(CASE WHEN hepatit_durumu='Negatif' THEN 1 ELSE 0 END) AS hepneg,
            SUM(CASE WHEN hepatit_durumu IS NOT NULL AND hepatit_durumu<>'' AND hepatit_durumu<>'Negatif' THEN 1 ELSE 0 END) AS heppoz,

            SUM(CASE
                WHEN diyabet_durumu IN ('Var','Evet','EVET','var','evet','1',1) THEN 1
                ELSE 0
            END) AS diyabet,

            SUM(CASE WHEN kayit_tarihi IS NOT NULL AND DATE(kayit_tarihi)=CURDATE() THEN 1 ELSE 0 END) AS bugun,

            ROUND(AVG(CASE
                WHEN dogum_tarihi IS NOT NULL AND dogum_tarihi <> '0000-00-00'
                THEN TIMESTAMPDIFF(YEAR, dogum_tarihi, CURDATE())
                ELSE NULL
            END), 0) AS ort_yas,

            ROUND(AVG(CASE
                WHEN kuru_agirlik IS NOT NULL AND kuru_agirlik <> 0
                THEN kuru_agirlik
                ELSE NULL
            END), 1) AS ort_kuru,

            SUM(CASE WHEN damar_yolu='AVF' THEN 1 ELSE 0 END) AS avf,
            SUM(CASE WHEN damar_yolu='AVG' THEN 1 ELSE 0 END) AS avg,
            SUM(CASE WHEN damar_yolu='Kateter' THEN 1 ELSE 0 END) AS kateter,
            SUM(CASE WHEN damar_yolu='Greft' THEN 1 ELSE 0 END) AS greft
        FROM hastalar
    ")->fetch(PDO::FETCH_ASSOC) ?: $stats;
} catch (PDOException $e) {}

// Toplam kayıt sayısı (filtreli)
$totalQuery = "SELECT COUNT(*) FROM hastalar" . $whereClause;
$stmt = $pdo->prepare($totalQuery);
$stmt->execute($bindParams);
$totalRecords = (int)$stmt->fetchColumn();

// Hasta listesi (filtreli)
$orderBy = ($sort === 'kayit_tarihi') ? 'kayit_tarihi' : 'ad';
$sql = "
    SELECT id, tc_no, ad, soyad, dogum_tarihi, kan_grubu, cinsiyet,
           hepatit_durumu, damar_yolu, diyabet_durumu, kuru_agirlik, telefon, durum, kayit_tarihi
    FROM hastalar
    {$whereClause}
    ORDER BY {$orderBy} {$dir}, soyad ASC, id DESC
    LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $pdo->prepare($sql);
$stmt->execute($bindParams);
$hastalar = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Sayfa sayısı
$totalPages = max(1, (int)ceil($totalRecords / $perPage));
$page = min($page, $totalPages);

// Damar yolu seçenekleri
$damarOptions = ['AVF', 'AVG', 'Kateter', 'Greft'];

// Sayfa bilgileri
$fromRecord = $totalRecords ? ($offset + 1) : 0;
$toRecord = min($offset + $perPage, $totalRecords);

// Pagination window
$window = 2;
$start = max(1, $page - $window);
$end = min($totalPages, $page + $window);

// Damar dağılımı yüzdeleri (genel)
$damarTotal = max(1, (int)($stats['avf'] + $stats['avg'] + $stats['kateter'] + $stats['greft']));
$prc = function($n) use ($damarTotal) { return (int)round(((int)$n / $damarTotal) * 100); };
$prc_avf = $prc($stats['avf']);
$prc_avg = $prc($stats['avg']);
$prc_kat = $prc($stats['kateter']);
$prc_grf = $prc($stats['greft']);
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">

<style>
/* =========================================================
   ✅ SCOPE FIX: Bu sayfanın CSS'i sadece .page-hasta içinde
   Header/navbar sıkışma ve global reset problemleri bitti.
   ========================================================= */
.page-hasta{
    --primary:#3b82f6;
    --primary-600:#2563eb;
    --primary-light:#eff6ff;
    --success:#10b981;
    --danger:#ef4444;
    --warning:#f59e0b;

    --dark:#0f172a;
    --text:#1e293b;
    --muted:#64748b;

    --light:#f8fafc;
    --border:#e2e8f0;
    --card:#ffffff;

    width:100%;
    min-width:0;
    padding:18px 22px 92px;
    overflow-x:clip;

    background: var(--light);
    color: var(--text);
    font-family:'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    line-height: 1.45;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: geometricPrecision;
}

/* Reset sadece bu sayfa içinde */
.page-hasta, .page-hasta *{ box-sizing:border-box; }

/* ✅ Layout’larda .container max-width yüzünden sağ boşluk olmasın */
.page-hasta .container,
.page-hasta .container-fluid,
.page-hasta .content-container,
.page-hasta .page-container{
    width:100% !important;
    max-width:100% !important;
    margin:0 !important;
    padding-left:0 !important;
    padding-right:0 !important;
}

/* Header (sadece bu sayfa) */
.page-hasta .header{
    display:flex;
    align-items:flex-end;
    justify-content:space-between;
    gap:12px;
    margin-bottom:14px;
}
.page-hasta .header h1{
    font-size: clamp(20px, 2.1vw, 26px);
    font-weight: 800;
    letter-spacing: -0.4px;
    color: var(--dark);
    margin:0 0 6px;
}
.page-hasta .header p{
    font-size: 14px;
    color: var(--muted);
    margin:0;
}

/* Stats */
.page-hasta .stats-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit, minmax(170px, 1fr));
    gap:12px;
    margin-bottom:14px;
}
.page-hasta .stat-item{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:18px;
    padding:16px 16px 14px;
    transition:all .2s ease;
    box-shadow:0 4px 12px rgba(0,0,0,.02);
}
.page-hasta .stat-item:hover{
    transform:translateY(-2px);
    box-shadow:0 10px 24px rgba(2,6,23,.06);
    border-color: rgba(59,130,246,.25);
}
.page-hasta .stat-top{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:10px;
}
.page-hasta .stat-ico{
    width:38px; height:38px;
    border-radius:14px;
    display:flex;
    align-items:center;
    justify-content:center;
    background: var(--primary-light);
    color: var(--primary);
    border:1px solid rgba(59,130,246,.15);
}
.page-hasta .stat-number{
    font-size: 26px;
    font-weight: 900;
    letter-spacing: -0.5px;
    color: var(--dark);
    margin:0;
}
.page-hasta .stat-label{
    font-size: 12px;
    color: var(--muted);
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: .6px;
}
.page-hasta .stat-sub{
    margin-top:6px;
    font-size:12px;
    color: var(--muted);
    font-weight: 700;
    display:flex;
    align-items:center;
    gap:8px;
}

/* Insight card */
.page-hasta .insight{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:18px;
    padding:16px;
    margin-bottom:16px;
    box-shadow:0 4px 12px rgba(0,0,0,.02);
}
.page-hasta .insight-head{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:10px;
    margin-bottom:12px;
}
.page-hasta .insight-title{
    font-size: 13px;
    font-weight: 900;
    color: var(--dark);
    letter-spacing: -0.2px;
    display:flex;
    align-items:center;
    gap:10px;
}
.page-hasta .insight-title i{ color: var(--primary); }
.page-hasta .insight-meta{
    font-size:12px;
    color: var(--muted);
    font-weight:700;
}
.page-hasta .bars{
    display:grid;
    grid-template-columns: 1fr;
    gap:10px;
}
.page-hasta .bar-row{
    display:grid;
    grid-template-columns: 86px 1fr 44px;
    gap:10px;
    align-items:center;
}
.page-hasta .bar-label{
    font-size:12px;
    color: var(--muted);
    font-weight: 800;
}
.page-hasta .bar{
    height:10px;
    border-radius:999px;
    background: #eef2ff;
    border:1px solid rgba(59,130,246,.12);
    overflow:hidden;
}
.page-hasta .bar > span{
    display:block;
    height:100%;
    width: var(--w, 0%);
    background: var(--primary);
}
.page-hasta .bar-val{
    font-size:12px;
    color: var(--dark);
    font-weight:900;
    text-align:right;
}

/* Search + Filters */
.page-hasta .search-container{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:18px;
    padding:18px;
    margin-bottom:18px;
    box-shadow:0 4px 12px rgba(0,0,0,.03);
}
.page-hasta .search-row{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-bottom:12px;
}
.page-hasta .search-box{
    flex:1;
    min-width:320px;
    position:relative;
}
.page-hasta .search-box input{
    width:100%;
    padding:12px 45px 12px 15px;
    border:1px solid var(--border);
    border-radius:12px;
    font-size:14px;
    font-weight:600;
    outline:none;
    transition:.2s;
    background:#fff;
    color: var(--dark);
}
.page-hasta .search-box input:focus{
    border-color:var(--primary);
    box-shadow:0 0 0 3px rgba(59,130,246,.12);
}
.page-hasta .search-box i{
    position:absolute;
    right:15px;
    top:50%;
    transform:translateY(-50%);
    color:var(--muted);
}

.page-hasta .filter-controls{
    display:grid;
    grid-template-columns:repeat(auto-fit, minmax(170px, 1fr));
    gap:12px;
    margin-bottom:12px;
}
.page-hasta .filter-select{
    width:100%;
    padding:12px 14px;
    border:1px solid var(--border);
    border-radius:12px;
    font-size:14px;
    font-weight:650;
    background:#fff;
    color:var(--dark);
    transition:.2s;
}
.page-hasta .filter-select:focus{
    outline:none;
    border-color:var(--primary);
    box-shadow:0 0 0 3px rgba(59,130,246,.12);
}

.page-hasta .filter-chips{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}
.page-hasta .chip{
    padding:9px 14px;
    background:var(--light);
    border:1px solid var(--border);
    border-radius:999px;
    font-size:13px;
    font-weight:900;
    color:var(--muted);
    cursor:pointer;
    transition:.2s;
    display:inline-flex;
    align-items:center;
    gap:8px;
    user-select:none;
}
.page-hasta .chip:hover{ background:#eef2f7; }
.page-hasta .chip.active{
    background:var(--primary-light);
    border-color:rgba(59,130,246,.35);
    color:var(--primary-600);
}

/* Grid */
.page-hasta .hasta-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill, minmax(320px, 1fr));
    gap:16px;
}

/* Card */
.page-hasta .hasta-card{
    background:var(--card);
    border:1px solid var(--border);
    border-radius:18px;
    padding:18px;
    transition:.25s;
}
.page-hasta .hasta-card:hover{
    border-color:rgba(59,130,246,.28);
    box-shadow:0 12px 26px rgba(59,130,246,.08);
}

.page-hasta .patient-top{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    margin-bottom:12px;
}
.page-hasta .patient-avatar{
    width:50px;height:50px;
    border-radius:14px;
    background:var(--primary-light);
    color:var(--primary);
    display:flex;align-items:center;justify-content:center;
    font-weight:900;font-size:18px;
    border:1px solid rgba(59,130,246,.18);
}
.page-hasta .patient-name{
    font-size:16px;
    font-weight:900;
    letter-spacing:-0.2px;
    color: var(--dark);
    margin-bottom:4px;
}
.page-hasta .patient-id{
    font-size:12px;
    color:var(--muted);
    font-weight:850;
    display:flex;
    align-items:center;
    gap:8px;
}
.page-hasta .patient-id i{ color: #94a3b8; }

.page-hasta .status-badges{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin: 10px 0 12px;
}
.page-hasta .badge{
    padding:6px 12px;
    border-radius:999px;
    font-size:11px;
    font-weight:900;
    display:inline-flex;
    align-items:center;
    gap:7px;
}
.page-hasta .badge-aktif{ background:rgba(16,185,129,.10); color:var(--success); border:1px solid rgba(16,185,129,.22); }
.page-hasta .badge-pasif{ background:rgba(148,163,184,.12); color:var(--muted); border:1px solid rgba(148,163,184,.22); }
.page-hasta .badge-hepatit-negatif{ background:rgba(16,185,129,.10); color:var(--success); border:1px solid rgba(16,185,129,.22); }
.page-hasta .badge-hepatit-pozitif{ background:rgba(239,68,68,.10); color:var(--danger); border:1px solid rgba(239,68,68,.22); }

.page-hasta .patient-details{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:10px;
    margin-bottom:12px;
}
.page-hasta .detail-item{
    background:linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
    padding:10px;
    border-radius:12px;
    border:1px solid rgba(226,232,240,.9);
}
.page-hasta .detail-label{
    font-size:10px;
    color:var(--muted);
    font-weight:900;
    text-transform:uppercase;
    margin-bottom:4px;
    letter-spacing:.45px;
}
.page-hasta .detail-value{
    font-size:13px;
    font-weight:900;
    color: var(--dark);
}

.page-hasta .action-bar{
    display:flex;
    gap:8px;
    padding-top:12px;
    border-top:1px solid var(--border);
}
.page-hasta .btn{
    flex:1;
    padding:10px 12px;
    border-radius:12px;
    font-size:12px;
    font-weight:900;
    cursor:pointer;
    border:none;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    transition:.2s;
    text-decoration:none;
    user-select:none;
}
.page-hasta .btn-view{ background:var(--primary-light); color:var(--primary-600); }
.page-hasta .btn-view:hover{ background:var(--primary-600); color:#fff; }
.page-hasta .btn-edit{ background:#ffffff; color:var(--dark); border:1px solid var(--border); }
.page-hasta .btn-edit:hover{ background:#eef2f7; }
.page-hasta .btn-start{ background:var(--success); color:#fff; border:1px solid var(--success); }
.page-hasta .btn-start:hover{ background:#059669; border-color:#059669; }

.page-hasta .results-info{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding-top:14px;
    font-size:13px;
    color:var(--muted);
    border-top:1px solid var(--border);
    margin-top:18px;
    font-weight:700;
}
.page-hasta .results-info strong{ color: var(--dark); font-weight:900; }

/* Pagination */
.page-hasta .pagination{
    display:flex;
    justify-content:center;
    gap:8px;
    flex-wrap:wrap;
    margin-top:18px;
    margin-bottom:60px;
}
.page-hasta .page-btn{
    padding:8px 16px;
    border:1px solid var(--border);
    border-radius:12px;
    background:var(--card);
    color:var(--dark);
    text-decoration:none;
    font-size:14px;
    font-weight:900;
    transition:.2s;
}
.page-hasta .page-btn:hover{ background:var(--light); color:var(--primary-600); border-color:rgba(59,130,246,.35); }
.page-hasta .page-btn.active{ background:var(--primary-600); color:#fff; border-color:var(--primary-600); }
.page-hasta .page-btn.disabled{ opacity:.5; cursor:not-allowed; pointer-events:none; }

/* Empty */
.page-hasta .empty-state{ text-align:center; padding:60px 20px; color:var(--muted); margin-bottom:60px; }
.page-hasta .empty-state i{ font-size:48px; color:#cbd5e1; margin-bottom:20px; }

/* ✅ FAB (scope) */
.page-hasta .fab{
    position:fixed;
    bottom:30px; right:30px;
    width:56px; height:56px;
    background:var(--primary-600);
    color:#fff;
    border-radius:50%;
    border:none;
    cursor:pointer;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:20px;
    box-shadow:0 10px 26px rgba(37,99,235,.28);
    transition:.2s;
    z-index:1000;
}
.page-hasta .fab:hover{ transform:scale(1.06); box-shadow:0 14px 32px rgba(37,99,235,.35); }

/* Mobile */
@media (max-width:768px){
    .page-hasta{ padding:12px 12px 90px; }
    .page-hasta .header{ align-items:flex-start; flex-direction:column; }
    .page-hasta .search-box{ min-width:100%; }
    .page-hasta .filter-controls{ grid-template-columns:1fr; }
    .page-hasta .patient-details{ grid-template-columns:1fr; }
    .page-hasta .action-bar{ flex-direction:column; }
    .page-hasta .results-info{ flex-direction:column; gap:10px; text-align:center; }
    .page-hasta .fab{ bottom:20px; right:20px; width:50px; height:50px; font-size:18px; }
    .page-hasta .bar-row{ grid-template-columns: 76px 1fr 44px; }
}
</style>

<div class="page-hasta">
    <div class="container">

        <div class="header">
            <div>
                <h1>Hasta Listesi</h1>
                <p>Filtrele, sırala, hızlı aksiyon al. (Full width + okunabilir tipografi)</p>
            </div>
        </div>

        <!-- RICH STATS -->
        <div class="stats-grid">

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number"><?= (int)$stats['toplam'] ?></div>
                        <div class="stat-label">Toplam Hasta</div>
                    </div>
                    <div class="stat-ico"><i class="fas fa-users"></i></div>
                </div>
                <div class="stat-sub"><i class="fas fa-database"></i> Kayıtlı portföy</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number" style="color:var(--success)"><?= (int)$stats['aktif'] ?></div>
                        <div class="stat-label">Aktif Tedavi</div>
                    </div>
                    <div class="stat-ico" style="background:rgba(16,185,129,.10);color:var(--success);border-color:rgba(16,185,129,.2);">
                        <i class="fas fa-user-check"></i>
                    </div>
                </div>
                <div class="stat-sub"><i class="fas fa-circle-check"></i> Seans takibi için</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number" style="color:var(--muted)"><?= (int)$stats['pasif'] ?></div>
                        <div class="stat-label">Pasif</div>
                    </div>
                    <div class="stat-ico" style="background:rgba(148,163,184,.12);color:var(--muted);border-color:rgba(148,163,184,.22);">
                        <i class="fas fa-user-clock"></i>
                    </div>
                </div>
                <div class="stat-sub"><i class="fas fa-pause"></i> Beklemede / kapalı</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number" style="color:var(--danger)"><?= (int)$stats['heppoz'] ?></div>
                        <div class="stat-label">Hepatit Pozitif</div>
                    </div>
                    <div class="stat-ico" style="background:rgba(239,68,68,.10);color:var(--danger);border-color:rgba(239,68,68,.22);">
                        <i class="fas fa-triangle-exclamation"></i>
                    </div>
                </div>
                <div class="stat-sub"><i class="fas fa-shield-virus"></i> İzolasyon takibi</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number" style="color:var(--success)"><?= (int)$stats['hepneg'] ?></div>
                        <div class="stat-label">Hepatit Negatif</div>
                    </div>
                    <div class="stat-ico" style="background:rgba(16,185,129,.10);color:var(--success);border-color:rgba(16,185,129,.22);">
                        <i class="fas fa-shield-check"></i>
                    </div>
                </div>
                <div class="stat-sub"><i class="fas fa-check"></i> Güvenli sınıf</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number" style="color:var(--warning)"><?= (int)$stats['diyabet'] ?></div>
                        <div class="stat-label">Diyabet</div>
                    </div>
                    <div class="stat-ico" style="background:rgba(245,158,11,.12);color:var(--warning);border-color:rgba(245,158,11,.22);">
                        <i class="fas fa-syringe"></i>
                    </div>
                </div>
                <div class="stat-sub"><i class="fas fa-notes-medical"></i> Klinik risk grubu</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number"><?= (int)$stats['bugun'] ?></div>
                        <div class="stat-label">Bugün Kayıt</div>
                    </div>
                    <div class="stat-ico"><i class="fas fa-calendar-day"></i></div>
                </div>
                <div class="stat-sub"><i class="fas fa-clock"></i> Günlük hareket</div>
            </div>

            <div class="stat-item">
                <div class="stat-top">
                    <div>
                        <div class="stat-number"><?= (int)$stats['ort_yas'] ?></div>
                        <div class="stat-label">Ortalama Yaş</div>
                    </div>
                    <div class="stat-ico"><i class="fas fa-chart-simple"></i></div>
                </div>
                <div class="stat-sub"><i class="fas fa-user"></i> Nüfus profili</div>
            </div>

        </div>

        <div class="insight">
            <div class="insight-head">
                <div class="insight-title"><i class="fas fa-code-branch"></i> Damar Yolu Dağılımı</div>
                <div class="insight-meta">
                    Ortalama kuru ağırlık: <strong style="color:var(--dark)"><?= h($stats['ort_kuru'] ?? 0) ?> kg</strong>
                </div>
            </div>

            <div class="bars">
                <div class="bar-row">
                    <div class="bar-label">AVF</div>
                    <div class="bar"><span style="--w: <?= (int)$prc_avf ?>%"></span></div>
                    <div class="bar-val"><?= (int)$prc_avf ?>%</div>
                </div>
                <div class="bar-row">
                    <div class="bar-label">AVG</div>
                    <div class="bar"><span style="--w: <?= (int)$prc_avg ?>%"></span></div>
                    <div class="bar-val"><?= (int)$prc_avg ?>%</div>
                </div>
                <div class="bar-row">
                    <div class="bar-label">Kateter</div>
                    <div class="bar"><span style="--w: <?= (int)$prc_kat ?>%"></span></div>
                    <div class="bar-val"><?= (int)$prc_kat ?>%</div>
                </div>
                <div class="bar-row">
                    <div class="bar-label">Greft</div>
                    <div class="bar"><span style="--w: <?= (int)$prc_grf ?>%"></span></div>
                    <div class="bar-val"><?= (int)$prc_grf ?>%</div>
                </div>
            </div>
        </div>

        <div class="search-container">
            <form id="filterForm" method="GET">
                <input type="hidden" name="sayfa" value="hasta-liste">
                <input type="hidden" name="p" value="1">

                <div class="search-row">
                    <div class="search-box">
                        <input type="text" name="q" value="<?= h($q) ?>" placeholder="İsim, soyisim veya T.C. No ile ara...">
                        <i class="fas fa-search"></i>
                    </div>
                </div>

                <div class="filter-controls">
                    <select name="durum" class="filter-select" onchange="this.form.submit()">
                        <option value="">Tüm Durumlar</option>
                        <option value="aktif" <?= $durum=='aktif'?'selected':''; ?>>Aktif</option>
                        <option value="pasif" <?= $durum=='pasif'?'selected':''; ?>>Pasif</option>
                    </select>

                    <select name="hep" class="filter-select" onchange="this.form.submit()">
                        <option value="">Tüm Hepatit</option>
                        <option value="Negatif" <?= $hep=='Negatif'?'selected':''; ?>>Negatif</option>
                        <option value="Pozitif" <?= $hep=='Pozitif'?'selected':''; ?>>Pozitif/Riskli</option>
                    </select>

                    <select name="damar" class="filter-select" onchange="this.form.submit()">
                        <option value="">Tüm Damar Yolları</option>
                        <?php foreach($damarOptions as $opt): ?>
                            <option value="<?= h($opt) ?>" <?= $damar==$opt?'selected':''; ?>><?= h($opt) ?></option>
                        <?php endforeach; ?>
                    </select>

                    <select name="pp" class="filter-select" onchange="this.form.submit()">
                        <option value="50"  <?= $perPage == 50  ? 'selected' : '' ?>>50 / sayfa</option>
                        <option value="60"  <?= $perPage == 60  ? 'selected' : '' ?>>60 / sayfa</option>
                        <option value="70"  <?= $perPage == 70  ? 'selected' : '' ?>>70 / sayfa</option>
                        <option value="80"  <?= $perPage == 80  ? 'selected' : '' ?>>80 / sayfa</option>
                        <option value="100" <?= $perPage == 100 ? 'selected' : '' ?>>100 / sayfa</option>
                    </select>

                    <select name="sort" class="filter-select" onchange="this.form.submit()">
                        <option value="ad" <?= $sort=='ad'?'selected':''; ?>>Ada Göre</option>
                        <option value="kayit_tarihi" <?= $sort=='kayit_tarihi'?'selected':''; ?>>Kayıt Tarihine Göre</option>
                    </select>

                    <select name="dir" class="filter-select" onchange="this.form.submit()">
                        <option value="asc" <?= $dir=='asc'?'selected':''; ?>>Artan</option>
                        <option value="desc" <?= $dir=='desc'?'selected':''; ?>>Azalan</option>
                    </select>
                </div>

                <div class="filter-chips">
                    <div class="chip <?= (empty($q)&&empty($durum)&&empty($hep)&&empty($damar))?'active':''; ?>" onclick="clearFilters()">
                        <i class="fas fa-layer-group"></i> Tümü
                    </div>
                    <div class="chip <?= ($durum=='aktif')?'active':''; ?>" onclick="setFilter('durum','aktif')">
                        <i class="fas fa-user-check"></i> Aktif
                    </div>
                    <div class="chip <?= ($hep=='Negatif')?'active':''; ?>" onclick="setFilter('hep','Negatif')">
                        <i class="fas fa-shield-check"></i> Hepatit Negatif
                    </div>
                    <div class="chip <?= ($hep=='Pozitif')?'active':''; ?>" onclick="setFilter('hep','Pozitif')">
                        <i class="fas fa-triangle-exclamation"></i> Hepatit Pozitif
                    </div>
                </div>
            </form>
        </div>

        <?php if(empty($hastalar)): ?>
            <div class="empty-state">
                <i class="fas fa-user-slash"></i>
                <h3 style="margin:0 0 6px 0; color:var(--dark); font-weight:900;">Hasta Bulunamadı</h3>
                <p style="margin:0;">Filtre kriterlerinize uygun hasta bulunmuyor</p>
            </div>
        <?php else: ?>
            <div class="hasta-grid">
                <?php foreach($hastalar as $hasta):
                    $ad = trim($hasta['ad'] ?? '');
                    $soyad = trim($hasta['soyad'] ?? '');
                    $initials = mb_strtoupper(mb_substr($ad,0,1,'UTF-8').mb_substr($soyad,0,1,'UTF-8'),'UTF-8');
                    if(!$initials) $initials='H';

                    $hepatitDurumu = $hasta['hepatit_durumu'] ?? '';
                    $isNeg = ($hepatitDurumu === 'Negatif');
                    $isPoz = (!empty($hepatitDurumu) && $hepatitDurumu !== 'Negatif');

                    $yas = '';
                    if(!empty($hasta['dogum_tarihi']) && $hasta['dogum_tarihi'] !== '0000-00-00'){
                        try{
                            $dogum = new DateTime($hasta['dogum_tarihi']);
                            $bugun = new DateTime();
                            $yas = $bugun->diff($dogum)->y;
                        }catch(Exception $e){}
                    }
                ?>
                <div class="hasta-card">
                    <div class="patient-top">
                        <div style="display:flex; align-items:center; gap:12px;">
                            <div class="patient-avatar"><?= h($initials) ?></div>
                            <div>
                                <div class="patient-name"><?= h($ad.' '.$soyad) ?></div>
                                <div class="patient-id"><i class="fas fa-id-card"></i> T.C. No: <?= h($hasta['tc_no'] ?? '-') ?></div>
                            </div>
                        </div>
                        <div style="text-align:right; color:var(--muted); font-weight:800; font-size:12px;">
                            <?php if(!empty($hasta['kayit_tarihi'])): ?>
                                <i class="fas fa-calendar-plus"></i>
                                <?= h(date('d.m.Y', strtotime($hasta['kayit_tarihi']))) ?>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="status-badges">
                        <span class="badge <?= ($hasta['durum']=='aktif')?'badge-aktif':'badge-pasif'; ?>">
                            <i class="fas fa-<?= ($hasta['durum']=='aktif')?'check':'pause'; ?>"></i>
                            <?= ($hasta['durum']=='aktif')?'Aktif':'Pasif'; ?>
                        </span>

                        <?php if($isNeg): ?>
                            <span class="badge badge-hepatit-negatif"><i class="fas fa-shield-check"></i> Hepatit Negatif</span>
                        <?php elseif($isPoz): ?>
                            <span class="badge badge-hepatit-pozitif"><i class="fas fa-triangle-exclamation"></i> <?= h($hepatitDurumu) ?></span>
                        <?php endif; ?>

                        <?php
                            $dbt = $hasta['diyabet_durumu'] ?? '';
                            $isDbt = in_array($dbt, ['Var','Evet','EVET','var','evet','1',1], true);
                            if($isDbt):
                        ?>
                            <span class="badge" style="background:rgba(245,158,11,.12); color:var(--warning); border:1px solid rgba(245,158,11,.22);">
                                <i class="fas fa-syringe"></i> Diyabet
                            </span>
                        <?php endif; ?>
                    </div>

                    <div class="patient-details">
                        <div class="detail-item">
                            <div class="detail-label">Kan Grubu</div>
                            <div class="detail-value"><?= h($hasta['kan_grubu'] ?? '-') ?></div>
                        </div>
                        <div class="detail-item">
                            <div class="detail-label">Damar Yolu</div>
                            <div class="detail-value"><?= h($hasta['damar_yolu'] ?? '-') ?></div>
                        </div>
                        <div class="detail-item">
                            <div class="detail-label">Kuru Ağırlık</div>
                            <div class="detail-value"><?= h($hasta['kuru_agirlik'] ?? '0') ?> kg</div>
                        </div>
                        <div class="detail-item">
                            <div class="detail-label">Yaş</div>
                            <div class="detail-value"><?= $yas !== '' ? h($yas).' yaş' : '-' ?></div>
                        </div>
                    </div>

                    <div class="action-bar">
                        <a href="?sayfa=hasta-detay&id=<?= (int)$hasta['id'] ?>" class="btn btn-view"><i class="fas fa-eye"></i> Detay</a>
                        <a href="?sayfa=hasta-duzenle&id=<?= (int)$hasta['id'] ?>" class="btn btn-edit"><i class="fas fa-pen"></i> Düzenle</a>
                        <a href="?sayfa=seans-baslat&id=<?= (int)$hasta['id'] ?>" class="btn btn-start"><i class="fas fa-play"></i> Seans Başlat</a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="results-info">
                <div>Toplam <strong><?= (int)$totalRecords ?></strong> kayıt • <strong><?= (int)$fromRecord ?>-<?= (int)$toRecord ?></strong> arası gösteriliyor</div>
                <div>Sayfa <strong><?= (int)$page ?></strong> / <strong><?= (int)$totalPages ?></strong></div>
            </div>

            <?php if($totalPages > 1): ?>
                <div class="pagination">
                    <?php if($page > 1): ?>
                        <a href="<?= h(buildUrlHasta(['p'=>$page-1])) ?>" class="page-btn"><i class="fas fa-chevron-left"></i></a>
                    <?php else: ?>
                        <span class="page-btn disabled"><i class="fas fa-chevron-left"></i></span>
                    <?php endif; ?>

                    <?php if($start > 1): ?>
                        <a href="<?= h(buildUrlHasta(['p'=>1])) ?>" class="page-btn">1</a>
                        <?php if($start > 2): ?><span class="page-btn" style="cursor:default;background:transparent;border:none;">...</span><?php endif; ?>
                    <?php endif; ?>

                    <?php for($i=$start; $i<=$end; $i++): ?>
                        <a href="<?= h(buildUrlHasta(['p'=>$i])) ?>" class="page-btn <?= ($i==$page)?'active':''; ?>"><?= (int)$i ?></a>
                    <?php endfor; ?>

                    <?php if($end < $totalPages): ?>
                        <?php if($end < $totalPages-1): ?><span class="page-btn" style="cursor:default;background:transparent;border:none;">...</span><?php endif; ?>
                        <a href="<?= h(buildUrlHasta(['p'=>$totalPages])) ?>" class="page-btn"><?= (int)$totalPages ?></a>
                    <?php endif; ?>

                    <?php if($page < $totalPages): ?>
                        <a href="<?= h(buildUrlHasta(['p'=>$page+1])) ?>" class="page-btn"><i class="fas fa-chevron-right"></i></a>
                    <?php else: ?>
                        <span class="page-btn disabled"><i class="fas fa-chevron-right"></i></span>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
        <?php endif; ?>

    </div><!-- /.container -->

    <!-- ✅ KRİTİK FIX: FAB BUTONU page-hasta İÇİNDE (yoksa style yemez ve “bozuk” görünür) -->
    <button class="fab" type="button" onclick="window.location.href='?sayfa=hasta-ekle'">
        <i class="fas fa-plus"></i>
    </button>

</div><!-- /.page-hasta -->

<script>
(function(){
    const form = document.getElementById('filterForm');
    if(!form) return;

    let timeout = null;
    const searchInput = form.querySelector('input[name="q"]');
    if(searchInput){
        searchInput.addEventListener('input', function(){
            clearTimeout(timeout);
            timeout = setTimeout(() => {
                const p = form.querySelector('input[name="p"]');
                if(p) p.value = '1';
                form.submit();
            }, 420);
        });
    }
})();

function setFilter(filter, value){
    const form = document.getElementById('filterForm');
    if(!form) return;
    const input = form.querySelector(`[name="${filter}"]`);
    if(input){
        input.value = value;
        const p = form.querySelector('input[name="p"]');
        if(p) p.value = '1';
        form.submit();
    }
}

function clearFilters(){ window.location.href='?sayfa=hasta-liste'; }

document.addEventListener('keydown', function(e){
    if(e.key === 'Escape') clearFilters();
});

document.addEventListener('keydown', function(e){
    const currentPage = <?= (int)$page ?>;
    const totalPages  = <?= (int)$totalPages ?>;
    if(e.key === 'ArrowLeft' && currentPage > 1) window.location.href = '<?= h(buildUrlHasta(['p'=>$page-1])) ?>';
    if(e.key === 'ArrowRight' && currentPage < totalPages) window.location.href = '<?= h(buildUrlHasta(['p'=>$page+1])) ?>';
});
</script>
