<?php
/**
 * NEPHRO ERP - GÜNLÜK OPERASYON PANELİ (v3.2 - EKSİKSİZ FİNAL)
 */
global $pdo;

$bugun = date('Y-m-d');
$gunler_tr = ["Sunday"=>"Pazar","Monday"=>"Pazartesi","Tuesday"=>"Sali","Wednesday"=>"Carsamba","Thursday"=>"Persembe","Friday"=>"Cuma","Saturday"=>"Cumartesi"];
$bugun_adi = $gunler_tr[date('l')];

// VERİ ÇEKME
$sql = "SELECT s.*, h.ad, h.soyad, h.tc_no, c.oda_no 
        FROM seans_programi s
        JOIN hastalar h ON s.hasta_id = h.id
        JOIN cihazlar c ON s.cihaz_id = c.id
        WHERE (s.plan_tarihi = ? OR (s.plan_tarihi IS NULL AND s.gun = ?))
        AND s.bitis_vakti IS NULL
        ORDER BY s.durum DESC, s.planlanan_saat ASC";

$stmt = $pdo->prepare($sql);
$stmt->execute([$bugun, $bugun_adi]);
$liste = $stmt->fetchAll();

// İSTATİSTİKLERİ HESAPLA
$stats = ['toplam' => count($liste), 'aktif' => 0, 'bekleyen' => 0];
foreach($liste as $l) {
    if(($l['durum'] ?? '') == 'Basladi') $stats['aktif']++;
    else if(($l['durum'] ?? '') == 'Randevu') $stats['bekleyen']++;
}

$odalar = array_values(array_unique(array_column($liste, 'oda_no')));

// ZAMAN ANALİZ FONKSİYONU
function analiz($baslangic) {
    if (empty($baslangic)) return null;
    $bas = new DateTime($baslangic);
    $simdi = new DateTime();
    $diff = $bas->diff($simdi);
    $gecen_dk = ($diff->h * 60) + $diff->i;
    $toplam_dk = 240; 
    $kalan_dk = $toplam_dk - $gecen_dk;
    return [
        'gecen' => ($diff->h > 0 ? $diff->h . "s " : "") . $diff->i . "dk",
        'kalan' => ($kalan_dk > 0) ? floor($kalan_dk/60)."s ".($kalan_dk%60)."dk" : "Bitti",
        'yuzde' => min(round(($gecen_dk / 240) * 100), 100),
        'kritik' => ($kalan_dk <= 30 && $kalan_dk > 0)
    ];
}
?>

<style>
    .op-wrap { padding: 15px; font-family: 'Inter', sans-serif; background: #f8fafc; }
    
    /* İSTATİSTİK KARTLARI */
    .op-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 20px; }
    .s-card { background: #fff; padding: 20px; border-radius: 20px; border: 1px solid #e2e8f0; display: flex; align-items: center; gap: 12px; }
    .s-card i { width: 45px; height: 45px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; }
    .s-val { display: block; font-size: 1.6rem; font-weight: 900; color: #1e293b; line-height: 1; }
    .s-tit { font-size: 0.6rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; }

    /* KONTROL PANELİ */
    .ctrl-panel { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; margin-bottom: 20px; background: #fff; padding: 20px; border-radius: 20px; border: 1px solid #e2e8f0; }
    .search-in { flex: 1; min-width: 250px; padding: 12px 20px; border-radius: 12px; border: 2px solid #f1f5f9; outline: none; font-weight: 600; }
    .oda-btn { padding: 8px 16px; border-radius: 10px; border: 1px solid #e2e8f0; background: #fff; cursor: pointer; font-weight: 800; font-size: 0.75rem; transition: 0.2s; }
    .oda-btn.active { background: #0f172a; color: #fff; border-color: #0f172a; }

    /* TABLO */
    .op-card-box { background: #fff; border-radius: 25px; border: 1px solid #e2e8f0; overflow: hidden; }
    .op-table { width: 100%; border-collapse: collapse; }
    .op-table th { background: #f8fafc; padding: 15px; text-align: left; font-size: 0.75rem; color: #94a3b8; border-bottom: 2px solid #f1f5f9; }
    .op-table td { padding: 15px; border-bottom: 1px solid #f1f5f9; }

    /* BUTONLAR */
    .btn-act { padding: 10px 15px; border-radius: 12px; font-weight: 800; font-size: 0.75rem; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
    .btn-start { background: #2563eb; color: #fff; }
    .btn-stop { background: #fee2e2; color: #ef4444; border: 1px solid #fecaca; }
    .btn-view { background: #f1f5f9; color: #1e293b; border: 1px solid #e2e8f0; }

    @media (max-width: 992px) {
        .op-table thead { display: none; }
        .op-table tr { display: block; border-bottom: 8px solid #f1f5f9; padding: 15px; background: #fff; }
        .op-table td { display: block; padding: 10px 0; border: none; }
        .op-table td::before { content: attr(data-label); display: block; font-size: 0.65rem; color: #94a3b8; font-weight: 800; margin-bottom: 4px; }
    }
</style>

<div class="op-wrap">
    <div class="op-stats">
        <div class="s-card">
            <i class="fas fa-users" style="background:#eff6ff; color:#2563eb;"></i>
            <div><span class="s-val"><?php echo $stats['toplam']; ?></span><span class="s-tit">Planlanan</span></div>
        </div>
        <div class="s-card">
            <i class="fas fa-play" style="background:#f0fdf4; color:#10b981;"></i>
            <div><span class="s-val"><?php echo $stats['aktif']; ?></span><span class="s-tit">Bağlı</span></div>
        </div>
        <div class="s-card">
            <i class="fas fa-hourglass" style="background:#fff7ed; color:#ea580c;"></i>
            <div><span class="s-val"><?php echo $stats['bekleyen']; ?></span><span class="s-tit">Bekleyen</span></div>
        </div>
    </div>

    <div class="ctrl-panel">
        <input type="text" id="h-ara" class="search-in" placeholder="Hasta adı veya TC ile ara..." onkeyup="filtrele()">
        <div class="oda-filter">
            <button class="oda-btn active" onclick="odaSec(this, 'all')">TÜMÜ</button>
            <?php foreach($odalar as $o): ?>
                <button class="oda-btn" onclick="odaSec(this, '<?php echo $o; ?>')">ODA <?php echo $o; ?></button>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="op-card-box">
        <table class="op-table" id="ana-liste">
            <thead>
                <tr>
                    <th>Saat</th>
                    <th>Hasta</th>
                    <th>Yatak</th>
                    <th>Zaman Takibi</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($liste as $row): 
                    $isLive = ($row['durum'] == 'Basladi');
                    $an = analiz($row['baslangic_vakti'] ?? null);
                    $plan_saat = (string)($row['planlanan_saat'] ?? '');
                ?>
                <tr class="h-row" data-oda="<?php echo $row['oda_no']; ?>" data-isim="<?php echo strtolower($row['ad'].' '.$row['soyad']); ?>">
                    <td data-label="Saat">
                        <div style="font-size:0.6rem; color:#94a3b8; font-weight:800;">PLAN: <?php echo !empty($plan_saat) ? substr($plan_saat,0,5) : '--:--'; ?></div>
                        <b style="font-size:1.1rem; color:#1e293b;"><?php echo $isLive ? date('H:i', strtotime($row['baslangic_vakti'])) : '--:--'; ?></b>
                    </td>
                    <td data-label="Hasta">
                        <b style="display:block; font-size:1rem;"><?php echo mb_strtoupper(($row['ad'] ?? '').' '.($row['soyad'] ?? ''), 'UTF-8'); ?></b>
                        <small style="color:#94a3b8;">TC: <?php echo substr((string)($row['tc_no'] ?? ''),0,3); ?>***</small>
                    </td>
                    <td data-label="Yatak">
                        <span style="background:#0f172a; color:#fff; padding:6px 12px; border-radius:10px; font-weight:900;">#<?php echo $row['oda_no']; ?></span>
                    </td>
                    <td data-label="Zaman">
                        <?php if($isLive && $an): ?>
                            <div style="font-weight:900; font-size:0.8rem; color:<?php echo $an['kritik'] ? 'red':'#10b981'; ?>;">
                                G: <?php echo $an['gecen']; ?> | K: <?php echo $an['kalan']; ?>
                            </div>
                            <div style="width:100px; height:6px; background:#f1f5f9; border-radius:3px; margin-top:5px;">
                                <div style="width:<?php echo $an['yuzde']; ?>%; height:100%; background:#10b981; border-radius:3px;"></div>
                            </div>
                        <?php else: ?>
                            <span style="color:#cbd5e1; font-weight:800; font-size:0.7rem;">HASTA BEKLENİYOR</span>
                        <?php endif; ?>
                    </td>
                    <td data-label="İşlemler">
                        <div style="display:flex; gap:8px;">
                            <?php if(!$isLive): ?>
                                <a href="?sayfa=seans-baslat&id=<?php echo $row['hasta_id']; ?>&plan_id=<?php echo $row['id']; ?>" class="btn-act btn-start"><i class="fas fa-play"></i> BAŞLAT</a>
                            <?php else: ?>
                                <a href="?sayfa=aktif-seans-detay&seans_id=<?php echo $row['id']; ?>" class="btn-act btn-view"><i class="fas fa-eye"></i> İZLE</a>
                                <a href="islem.php?seans_bitir=<?php echo $row['id']; ?>" class="btn-act btn-stop" onclick="return confirm('Seansı Bitirilsin mi?')"><i class="fas fa-power-off"></i> BİTİR</a>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
let aktifOda = 'all';
function odaSec(btn, oda) {
    document.querySelectorAll('.oda-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    aktifOda = oda;
    filtrele();
}
function filtrele() {
    let arama = document.getElementById('h-ara').value.toLowerCase();
    document.querySelectorAll('.h-row').forEach(row => {
        let oda = row.getAttribute('data-oda');
        let isim = row.getAttribute('data-isim');
        let odaUyum = (aktifOda === 'all' || aktifOda === oda);
        let isimUyum = (isim.includes(arama));
        row.style.display = (odaUyum && isimUyum) ? '' : 'none';
    });
}
</script>