<?php
/**
 * AKTİF SEANS TAKİBİ - CANLI İZLEME
 */
global $pdo;

try {
    // Sadece durumu 'Basladi' olan ve bitiş zamanı olmayan seansları getir
    $sql = "SELECT s.*, h.ad, h.soyad, h.tc_no, h.kan_grubu, c.marka_model, 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.durum = 'Basladi' 
            AND s.bitis_vakti IS NULL 
            ORDER BY s.baslangic_vakti DESC";
    
    $aktif_seanslar = $pdo->query($sql)->fetchAll();
    $aktif_sayi = count($aktif_seanslar);
} catch (PDOException $e) {
    $aktif_seanslar = [];
    $aktif_sayi = 0;
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aktif Seanslar - NEPHRO ERP</title>
    <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@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ===== CSS DEĞİŞKENLERİ (Hasta Listesi ile aynı) ===== */
        :root {
            --primary: #2563eb;
            --primary-light: #dbeafe;
            --primary-dark: #1d4ed8;
            --secondary: #64748b;
            --success: #059669;
            --warning: #d97706;
            --danger: #dc2626;
            --danger-light: #fee2e2;
            --background: #f8fafc;
            --surface: #ffffff;
            --border: #e2e8f0;
            --text: #1e293b;
            --text-light: #64748b;
            --text-muted: #94a3b8;
            --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            --shadow-md: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
            --radius: 8px;
            --radius-lg: 12px;
            --transition: all 0.2s ease;
        }

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

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background: var(--background);
            color: var(--text);
            line-height: 1.5;
            font-size: 14px;
            font-weight: 400;
        }

        /* ===== LAYOUT ===== */
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
            min-height: 100vh;
        }

        /* ===== HEADER ===== */
        .page-header {
            margin-bottom: 32px;
        }

        .page-header h1 {
            font-size: 28px;
            font-weight: 700;
            color: var(--text);
            margin-bottom: 4px;
            letter-spacing: -0.02em;
        }

        .page-header p {
            color: var(--text-light);
            font-size: 15px;
            font-weight: 400;
        }

        /* ===== STATS CARDS ===== */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
            margin-bottom: 32px;
        }

        .stat-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius-lg);
            padding: 20px;
            transition: var(--transition);
        }

        .stat-card:hover {
            border-color: var(--primary);
            box-shadow: var(--shadow);
        }

        .stat-value {
            font-size: 32px;
            font-weight: 700;
            margin-bottom: 8px;
            line-height: 1;
        }

        .stat-label {
            font-size: 13px;
            color: var(--text-light);
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        /* ===== CANLI DURUM İNDİKATÖRÜ ===== */
        .live-indicator {
            background: rgba(5, 150, 105, 0.1);
            border: 1px solid rgba(5, 150, 105, 0.2);
            border-radius: var(--radius);
            padding: 12px 20px;
            display: inline-flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 24px;
        }

        .live-dot {
            width: 10px;
            height: 10px;
            background: var(--success);
            border-radius: 50%;
            animation: blink 1.2s infinite;
        }

        @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.3; }
        }

        .live-text {
            font-weight: 600;
            color: var(--success);
        }

        /* ===== SEANS GRİD ===== */
        .seans-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
            gap: 20px;
        }

        @media (max-width: 768px) {
            .seans-grid {
                grid-template-columns: 1fr;
            }
        }

        /* ===== SEANS KARTI ===== */
        .seans-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: var(--radius-lg);
            padding: 20px;
            transition: var(--transition);
            position: relative;
        }

        .seans-card:hover {
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        /* Card Header */
        .card-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            margin-bottom: 20px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border);
        }

        .room-badge {
            background: var(--text);
            color: white;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .time-badge {
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--text-light);
            font-size: 13px;
            font-weight: 500;
        }

        /* Hasta Bilgileri */
        .patient-section {
            display: flex;
            align-items: center;
            gap: 16px;
            margin-bottom: 20px;
        }

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

        .patient-info {
            flex: 1;
        }

        .patient-name {
            font-size: 18px;
            font-weight: 600;
            color: var(--text);
            margin-bottom: 4px;
        }

        .patient-device {
            font-size: 13px;
            color: var(--text-light);
            font-weight: 400;
        }

        /* Detay Grid */
        .details-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }

        .detail-item {
            background: var(--background);
            border: 1px solid var(--border);
            border-radius: var(--radius);
            padding: 12px;
            text-align: center;
        }

        .detail-label {
            font-size: 11px;
            color: var(--text-muted);
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 4px;
        }

        .detail-value {
            font-size: 14px;
            font-weight: 600;
            color: var(--text);
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .status-active {
            background: rgba(5, 150, 105, 0.1);
            color: var(--success);
            border: 1px solid rgba(5, 150, 105, 0.2);
        }

        /* Action Button */
        .action-btn {
            display: block;
            width: 100%;
            padding: 12px;
            background: var(--primary);
            color: white;
            border: none;
            border-radius: var(--radius);
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            text-decoration: none;
            text-align: center;
        }

        .action-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-1px);
        }

        /* ===== BOŞ DURUM ===== */
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: var(--surface);
            border-radius: var(--radius-lg);
            border: 2px dashed var(--border);
            margin-top: 20px;
        }

        .empty-icon {
            font-size: 48px;
            color: #cbd5e1;
            margin-bottom: 20px;
        }

        .empty-state h2 {
            font-size: 20px;
            font-weight: 600;
            color: var(--text);
            margin-bottom: 8px;
        }

        .empty-state p {
            color: var(--text-light);
            font-size: 15px;
            max-width: 400px;
            margin: 0 auto;
        }

        /* ===== REFRESH BUTTON ===== */
        .refresh-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 50px;
            height: 50px;
            background: var(--primary);
            color: white;
            border-radius: 50%;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            box-shadow: var(--shadow-md);
            transition: var(--transition);
            z-index: 100;
        }

        .refresh-btn:hover {
            background: var(--primary-dark);
            transform: rotate(90deg);
        }

        /* ===== RESPONSIVE ===== */
        @media (max-width: 768px) {
            .container {
                padding: 16px;
            }
            
            .stats-container {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .patient-section {
                flex-direction: column;
                text-align: center;
            }
            
            .details-grid {
                grid-template-columns: 1fr;
            }
            
            .refresh-btn {
                bottom: 20px;
                right: 20px;
                width: 45px;
                height: 45px;
            }
        }

        @media (max-width: 480px) {
            .stats-container {
                grid-template-columns: 1fr;
            }
            
            .seans-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Başlık -->
        <div class="page-header">
            <h1>Aktif Seans Takibi</h1>
            <p>Klinikte şu an tedavi gören hastaların canlı durumu</p>
        </div>

        <!-- İstatistikler -->
        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-value" style="color: var(--primary);"><?= $aktif_sayi ?></div>
                <div class="stat-label">Aktif Seans</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: var(--success);">
                    <?= count($aktif_seanslar) ?>
                </div>
                <div class="stat-label">Hasta Bağlı</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: var(--secondary);">
                    <?php
                        $odalar = array_unique(array_column($aktif_seanslar, 'oda_no'));
                        echo count($odalar);
                    ?>
                </div>
                <div class="stat-label">Aktif Oda</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" style="color: var(--warning);">
                    <?php
                        $cihazlar = array_unique(array_column($aktif_seanslar, 'marka_model'));
                        echo count($cihazlar);
                    ?>
                </div>
                <div class="stat-label">Cihaz Çeşidi</div>
            </div>
        </div>

        <!-- Canlı Durum Göstergesi -->
        <div class="live-indicator">
            <div class="live-dot"></div>
            <span class="live-text">CANLI İZLEME AKTİF • <?= $aktif_sayi ?> HASTA TEDAVİ GÖRÜYOR</span>
        </div>

        <?php if ($aktif_sayi == 0): ?>
            <!-- Boş Durum -->
            <div class="empty-state">
                <div class="empty-icon"><i class="fas fa-bed-pulse"></i></div>
                <h2>Aktif Seans Bulunmuyor</h2>
                <p>Şu anda klinikte tedavi gören hasta bulunmamaktadır. Takvimden hasta başlatıldığında burada görünecektir.</p>
            </div>
        <?php else: ?>
            <!-- Aktif Seanslar Grid -->
            <div class="seans-grid">
                <?php foreach ($aktif_seanslar as $seans): 
                    // Hasta adının baş harfleri
                    $ad = $seans['ad'] ?? '';
                    $soyad = $seans['soyad'] ?? '';
                    $initials = mb_strtoupper(
                        mb_substr($ad, 0, 1, 'UTF-8') . 
                        mb_substr($soyad, 0, 1, 'UTF-8'), 
                        'UTF-8'
                    );
                    
                    if (empty($initials)) {
                        $initials = 'H';
                    }
                    
                    // Başlangıç zamanını formatla
                    $baslangic = strtotime($seans['baslangic_vakti'] ?? '');
                    $baslangic_formatted = $baslangic ? date('H:i', $baslangic) : '-';
                    
                    // Süre hesapla
                    $sure = '';
                    if ($baslangic) {
                        $sure_fark = time() - $baslangic;
                        $sure_saat = floor($sure_fark / 3600);
                        $sure_dakika = floor(($sure_fark % 3600) / 60);
                        
                        if ($sure_saat > 0) {
                            $sure = $sure_saat . 'sa ' . $sure_dakika . 'dk';
                        } else {
                            $sure = $sure_dakika . 'dk';
                        }
                    }
                ?>
                    <div class="seans-card">
                        <!-- Oda ve Zaman Bilgisi -->
                        <div class="card-header">
                            <div class="room-badge">Oda <?= htmlspecialchars($seans['oda_no'] ?? '0') ?></div>
                            <div class="time-badge">
                                <i class="far fa-clock"></i>
                                <span><?= $baslangic_formatted ?> • <?= $sure ?></span>
                            </div>
                        </div>

                        <!-- Hasta Bilgileri -->
                        <div class="patient-section">
                            <div class="patient-avatar"><?= $initials ?></div>
                            <div class="patient-info">
                                <div class="patient-name">
                                    <?= htmlspecialchars(mb_strtoupper($ad . ' ' . $soyad, 'UTF-8')) ?>
                                </div>
                                <div class="patient-device">
                                    <?= htmlspecialchars($seans['marka_model'] ?? 'Cihaz Belirtilmemiş') ?>
                                </div>
                            </div>
                        </div>

                        <!-- Detaylar -->
                        <div class="details-grid">
                            <div class="detail-item">
                                <div class="detail-label">Kan Grubu</div>
                                <div class="detail-value"><?= htmlspecialchars($seans['kan_grubu'] ?? '-') ?></div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-label">Durum</div>
                                <div class="detail-value">
                                    <span class="status-badge status-active">
                                        <i class="fas fa-circle" style="font-size: 8px; margin-right: 4px;"></i>
                                        AKTİF
                                    </span>
                                </div>
                            </div>
                        </div>

                        <!-- Detay Sayfası Butonu -->
                        <a href="?sayfa=aktif-seans-detay&seans_id=<?= (int)($seans['id'] ?? 0) ?>" class="action-btn">
                            <i class="fas fa-chart-line"></i> Gözlem Paneline Git
                        </a>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Refresh Button -->
    <button class="refresh-btn" onclick="window.location.reload()" title="Sayfayı Yenile">
        <i class="fas fa-sync-alt"></i>
    </button>

    <script>
        // Otomatik yenileme (60 saniyede bir)
        let autoRefresh = true;
        let refreshTimer = null;

        function startAutoRefresh() {
            if (autoRefresh) {
                refreshTimer = setTimeout(() => {
                    window.location.reload();
                }, 60000); // 60 saniye
            }
        }

        function stopAutoRefresh() {
            autoRefresh = false;
            if (refreshTimer) {
                clearTimeout(refreshTimer);
            }
        }

        // Sayfa yüklendiğinde otomatik yenilemeyi başlat
        document.addEventListener('DOMContentLoaded', function() {
            startAutoRefresh();
            
            // Kullanıcı sayfada aktifse otomatik yenilemeyi durdur
            let userActive = false;
            
            document.addEventListener('mousemove', function() {
                userActive = true;
                stopAutoRefresh();
            });
            
            document.addEventListener('keydown', function() {
                userActive = true;
                stopAutoRefresh();
            });
            
            // Kullanıcı 30 saniye inaktif kalırsa yeniden başlat
            setInterval(() => {
                if (!userActive) {
                    autoRefresh = true;
                    startAutoRefresh();
                }
            }, 30000);
        });

        // ESC tuşu ile sayfayı yenile
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                window.location.reload();
            }
        });

        // Kartlara tıklama efekti
        document.querySelectorAll('.seans-card').forEach(card => {
            card.addEventListener('click', function(e) {
                // Sadece action butonu değilse
                if (!e.target.closest('.action-btn')) {
                    const link = this.querySelector('.action-btn');
                    if (link) {
                        window.location.href = link.href;
                    }
                }
            });
        });
    </script>
</body>
</html>