<?php
/**
 * NEPHRO ERP - MASTER COMMAND CENTER "GOD MODE" (v35)
 * Tüm tıbbi, operasyonel ve teknik istatistikler tek ekranda.
 */
global $pdo;

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

// 1. ÜST METRİKLER (Genişletilmiş)
$st = [
    'hasta'   => $pdo->query("SELECT COUNT(*) FROM hastalar WHERE durum='aktif'")->fetchColumn(),
    'seans'   => $pdo->query("SELECT COUNT(*) FROM seans_programi WHERE bitis_vakti IS NULL AND durum='Basladi'")->fetchColumn(),
    'cihaz'   => $pdo->query("SELECT COUNT(*) FROM cihazlar WHERE durum='aktif'")->fetchColumn(),
    'stok'    => $pdo->query("SELECT COUNT(*) FROM stok WHERE stok_miktari <= kritik_seviye")->fetchColumn(),
    'bugun'   => $pdo->query("SELECT COUNT(*) FROM seans_programi WHERE DATE(plan_tarihi) = CURDATE()")->fetchColumn(),
    'bitti'   => $pdo->query("SELECT COUNT(*) FROM seans_programi WHERE DATE(plan_tarihi) = CURDATE() AND durum='Bitti'")->fetchColumn(),
    'bakim'   => $pdo->query("SELECT COUNT(*) FROM cihazlar WHERE son_bakim_tarihi < DATE_SUB(NOW(), INTERVAL 3 MONTH) OR son_bakim_tarihi IS NULL")->fetchColumn()
];

// 2. CANLI VİTAL ANOMALİLERİ
$kritik_sql = "SELECT h.ad, h.soyad, g.tansiyon_sys, g.nabiz, c.oda_no, s.id as seans_id
               FROM seans_gozlemleri g
               JOIN seans_programi s ON g.seans_id = s.id
               JOIN hastalar h ON s.hasta_id = h.id
               JOIN cihazlar c ON s.cihaz_id = c.id
               WHERE s.bitis_vakti IS NULL 
               AND g.id IN (SELECT MAX(id) FROM seans_gozlemleri GROUP BY seans_id)
               AND (g.tansiyon_sys < 100 OR g.tansiyon_sys > 175 OR g.nabiz > 115)
               LIMIT 4";
$kritikler = $pdo->query($kritik_sql)->fetchAll(PDO::FETCH_ASSOC);

// 3. DAĞILIM ANALİZLERİ (Hepatit & Damar Yolu)
$hepatit_dist = $pdo->query("SELECT hepatit_durumu, COUNT(*) as sayi FROM hastalar WHERE durum='aktif' GROUP BY hepatit_durumu")->fetchAll(PDO::FETCH_ASSOC);
$damar_dist = $pdo->query("SELECT damar_yolu, COUNT(*) as sayi FROM hastalar WHERE durum='aktif' GROUP BY damar_yolu")->fetchAll(PDO::FETCH_ASSOC);

// 4. GÜNLÜK AKIŞ VE LOGLAR
$randevular = $pdo->query("SELECT s.*, h.ad, h.soyad, c.oda_no FROM seans_programi s JOIN hastalar h ON s.hasta_id = h.id LEFT JOIN cihazlar c ON s.cihaz_id = c.id WHERE DATE(s.plan_tarihi) = CURDATE() ORDER BY s.planlanan_saat ASC LIMIT 6")->fetchAll(PDO::FETCH_ASSOC);
$logs = $pdo->query("SELECT sl.*, k.ad_soyad FROM sistem_loglari sl LEFT JOIN kullanicilar k ON sl.kullanici_id = k.id ORDER BY sl.id DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

// Hesaplamalar
$doluluk = ($st['cihaz'] > 0) ? round(($st['seans'] / $st['cihaz']) * 100) : 0;
?>

<style>
    :root { --p: #2563eb; --danger: #ef4444; --success: #10b981; --warn: #f59e0b; --bg: #f8fafc; --dark: #0f172a; }
    .mega-dash { background: var(--bg); padding: 20px; font-family: 'Inter', sans-serif; }
    
    /* Grid Sistemleri */
    .top-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 25px; }
    .main-layout { display: grid; grid-template-columns: 1fr 350px; gap: 25px; }
    @media (max-width: 1200px) { .main-layout { grid-template-columns: 1fr; } }

    /* Kart Tasarımları */
    .card-mini { background: #fff; padding: 20px; border-radius: 20px; border: 1px solid #e2e8f0; text-align: center; transition: 0.3s; }
    .card-mini:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.05); }
    .card-mini b { display: block; font-size: 1.6rem; font-weight: 900; color: var(--dark); margin-top: 5px; }
    .card-mini small { font-size: 10px; font-weight: 800; color: #64748b; text-transform: uppercase; }

    .panel-lux { background: #fff; border-radius: 28px; padding: 25px; border: 1px solid #e2e8f0; margin-bottom: 25px; }
    .panel-h { font-size: 1rem; font-weight: 900; color: var(--dark); margin-bottom: 20px; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #f1f5f9; padding-bottom: 15px; }

    /* Hızlı Aksiyonlar */
    .action-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 10px; margin-bottom: 25px; }
    .btn-act { background: #fff; border: 1px solid #e2e8f0; padding: 15px; border-radius: 18px; text-align: center; text-decoration: none; transition: 0.2s; }
    .btn-act:hover { border-color: var(--p); background: #f0f7ff; }
    .btn-act i { font-size: 1.4rem; color: var(--p); display: block; margin-bottom: 8px; }
    .btn-act span { font-size: 11px; font-weight: 800; color: var(--dark); }

    /* Pulse Animasyon */
    .pulse-red { width: 10px; height: 10px; background: var(--danger); border-radius: 50%; animation: p-red 1.5s infinite; }
    @keyframes p-red { 0% { box-shadow: 0 0 0 0 rgba(239,68,68,0.7); } 70% { box-shadow: 0 0 0 10px rgba(239,68,68,0); } 100% { box-shadow: 0 0 0 0 rgba(239,68,68,0); } }

    .prog-bar { height: 6px; background: #f1f5f9; border-radius: 10px; overflow: hidden; margin: 8px 0; }
    .prog-val { height: 100%; border-radius: 10px; }
</style>

<div class="mega-dash">
    <div class="top-stats">
        <div class="card-mini" style="border-top: 4px solid var(--p);">
            <small>Aktif Hasta</small><b><?= $st['hasta'] ?></b>
        </div>
        <div class="card-mini" style="border-top: 4px solid var(--success);">
            <small>Canlı Seans</small><b><?= $st['seans'] ?></b>
        </div>
        <div class="card-mini" style="border-top: 4px solid var(--warn);">
            <small>Bugün Plan</small><b><?= $st['bitti'] ?>/<?= $st['bugun'] ?></b>
        </div>
        <div class="card-mini" style="border-top: 4px solid var(--danger);">
            <small>Kritik Stok</small><b><?= $st['stok'] ?></b>
        </div>
        <div class="card-mini" style="border-top: 4px solid #64748b;">
            <small>Bakım Bekleyen</small><b><?= $st['bakim'] ?></b>
        </div>
    </div>

    <div class="action-grid">
        <a href="index.php?sayfa=seans-baslat" class="btn-act"><i class="fas fa-play"></i><span>Seans Başlat</span></a>
        <a href="index.php?sayfa=hasta-ekle" class="btn-act"><i class="fas fa-user-plus"></i><span>Hasta Ekle</span></a>
        <a href="index.php?sayfa=stok-hareket" class="btn-act"><i class="fas fa-box"></i><span>Stok Çıkış</span></a>
        <a href="index.php?sayfa=vizit-notlari" class="btn-act"><i class="fas fa-notes-medical"></i><span>Vizit Yaz</span></a>
        <a href="index.php?sayfa=test-tanimlari" class="btn-act"><i class="fas fa-vials"></i><span>Testler</span></a>
        <a href="index.php?sayfa=ayarlar" class="btn-act"><i class="fas fa-cog"></i><span>Ayarlar</span></a>
    </div>

    <div class="main-layout">
        <div class="col-left">
            <div class="panel-lux" style="border-left: 5px solid var(--danger);">
                <div class="panel-h"><i class="fas fa-heartbeat" style="color:var(--danger)"></i> ACİL VİTAL TAKİBİ</div>
                <?php if(empty($kritikler)): ?>
                    <p style="text-align:center; color:var(--success); font-weight:700;"><i class="fas fa-check-circle"></i> Şu an tüm değerler normal.</p>
                <?php else: ?>
                    <?php foreach($kritikler as $k): ?>
                    <div style="display:flex; align-items:center; justify-content:space-between; padding:15px; background:#fef2f2; border-radius:15px; margin-bottom:10px;">
                        <div style="display:flex; align-items:center; gap:12px;">
                            <div class="pulse-red"></div>
                            <div><b><?= h($k['ad'].' '.$k['soyad']) ?></b><br><small><?= h($k['oda_no']) ?> No'lu Cihaz</small></div>
                        </div>
                        <div style="text-align:right;">
                            <b style="font-size:1.3rem; color:var(--danger);"><?= $k['tansiyon_sys'] ?>/<?= $k['nabiz'] ?></b>
                            <div style="font-size:9px; font-weight:800; color:#ef4444;">TANS / NABIZ</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="panel-lux">
                <div class="panel-h"><i class="fas fa-calendar-alt" style="color:var(--p)"></i> BUGÜNKÜ RANDEVU AKIŞI</div>
                <?php foreach($randevular as $r): ?>
                <div style="display:flex; align-items:center; justify-content:space-between; padding:12px 0; border-bottom:1px solid #f1f5f9;">
                    <div style="display:flex; align-items:center; gap:15px;">
                        <b style="color:var(--p); width:50px;"><?= substr($r['planlanan_saat'],0,5) ?></b>
                        <span><?= h($r['ad'].' '.$r['soyad']) ?> <small style="color:#64748b;">(<?= h($r['oda_no'] ?? 'Bekliyor') ?>)</small></span>
                    </div>
                    <span style="font-size:10px; font-weight:800; color:<?= $r['durum']=='Bitti' ? 'var(--s)':'var(--success)' ?>"><?= $r['durum'] ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="col-right">
            <div class="panel-lux">
                <div class="panel-h"><i class="fas fa-chart-pie" style="color:var(--warn)"></i> TIBBİ ANALİZ</div>
                <small style="font-weight:800; color:#64748b; display:block; margin-bottom:10px;">İzolasyon Dağılımı</small>
                <?php foreach($hepatit_dist as $h): ?>
                    <div style="font-size:12px; margin-bottom:8px;">
                        <div style="display:flex; justify-content:space-between;"><span><?= $h['hepatit_durumu'] ?></span><b><?= $h['sayi'] ?></b></div>
                        <div class="prog-bar"><div class="prog-val" style="width:<?= ($h['sayi']/$st['hasta'])*100 ?>%; background:var(--warn)"></div></div>
                    </div>
                <?php endforeach; ?>
                
                <small style="font-weight:800; color:#64748b; display:block; margin:20px 0 10px 0;">Damar Yolu Dağılımı</small>
                <?php foreach($damar_dist as $d): ?>
                    <div style="font-size:12px; margin-bottom:8px;">
                        <div style="display:flex; justify-content:space-between;"><span><?= h($d['damar_yolu'] ?: 'Belirtilmedi') ?></span><b><?= $d['sayi'] ?></b></div>
                        <div class="prog-bar"><div class="prog-val" style="width:<?= ($d['sayi']/$st['hasta'])*100 ?>%; background:var(--p)"></div></div>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="panel-lux">
                <div class="panel-h"><i class="fas fa-fingerprint" style="color:var(--p)"></i> SİSTEM DENETİMİ</div>
                <?php foreach($logs as $l): ?>
                <div style="padding:10px 0; border-bottom:1px solid #f1f5f9;">
                    <small style="display:block; font-size:9px; color:#64748b; font-weight:800;"><?= date('H:i', strtotime($l['islem_tarihi'])) ?> • <?= h($l['ad_soyad']) ?></small>
                    <span style="font-size:11px; font-weight:600; color:var(--dark);"><?= h($l['islem_detay']) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>