<?php
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../../dripend/includes/db.php'; 

// User Context
$user_name = $_SESSION['user_full_name'] ?? 'Laboratory User';
$user_role = $_SESSION['user_role'] ?? 'Lab Personnel';

// ==============================================================================
// 1. FETCH REAL-TIME WORKFLOW METRICS (KPIs)
// ==============================================================================
$metrics = [
    'pending_reception' => 0,
    'pending_collection' => 0,
    'pending_testing' => 0,
    'pending_verification' => 0,
    'completed_today' => 0
];

// Query all active requests and group them by status to build the live KPI board
$qMetrics = "SELECT status, COUNT(*) as count FROM clinical_lab_requests GROUP BY status";
$resMetrics = $conn->query($qMetrics);
if ($resMetrics) {
    while ($row = $resMetrics->fetch_assoc()) {
        switch ($row['status']) {
            case 'Pending': $metrics['pending_reception'] = $row['count']; break;
            case 'Accepted': $metrics['pending_collection'] = $row['count']; break;
            case 'Sample Collected': $metrics['pending_testing'] = $row['count']; break;
            case 'Results Entered': $metrics['pending_verification'] = $row['count']; break;
        }
    }
}

// Completed Today (Fixed: Switched 'updated_at' to 'request_date' to match your schema)
$qCompleted = "SELECT COUNT(*) as count FROM clinical_lab_requests WHERE status = 'Verified' AND DATE(request_date) = CURDATE()";
$resCompleted = $conn->query($qCompleted);
if ($resCompleted && $row = $resCompleted->fetch_assoc()) {
    $metrics['completed_today'] = $row['count'];
}

// ==============================================================================
// 2. FETCH SYSTEM SETUP INTEGRITY (Health Check)
// ==============================================================================
$setup_health = [
    'active_parameters' => 0,
    'active_samples' => 0,
    'active_benches' => 0
];

$resParams = $conn->query("SELECT COUNT(*) as count FROM lab_parameters WHERE is_active = 1");
if ($resParams) $setup_health['active_parameters'] = $resParams->fetch_assoc()['count'];

$resSamples = $conn->query("SELECT COUNT(*) as count FROM lab_sample_types WHERE is_active = 1");
if ($resSamples) $setup_health['active_samples'] = $resSamples->fetch_assoc()['count'];

$resBenches = $conn->query("SELECT COUNT(*) as count FROM lab_sub_departments WHERE is_active = 1");
if ($resBenches) $setup_health['active_benches'] = $resBenches->fetch_assoc()['count'];

// ==============================================================================
// 3. FETCH LIVE ACTIVITY FEED (Recent Requests)
// ==============================================================================
$recent_activity = [];
$qActivity = "
    SELECT 
        clr.id, clr.status, clr.priority, clr.request_date,
        sc.service_name, p.first_name, p.last_name, p.patient_no
    FROM clinical_lab_requests clr
    JOIN service_catalog sc ON clr.service_id = sc.id
    JOIN patient p ON clr.patient_no = p.patient_no
    ORDER BY clr.request_date DESC 
    LIMIT 6
";
$resAct = $conn->query($qActivity);
if ($resAct) {
    while ($row = $resAct->fetch_assoc()) {
        $recent_activity[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laboratory Command Center | Tier 1 LIS</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root {
    --sidebar-width: 280px;
    --bg-app: #f1f5f9;
    --card-bg: #ffffff;
    --text-main: #0f172a;
    --text-muted: #64748b;
    --brand-dark: #0f172a;
    --brand-primary: #2563eb;
    --brand-light: #eff6ff;
    
    /* Semantic Colors */
    --c-reception: #8b5cf6; /* Purple */
    --c-collection: #f59e0b; /* Amber */
    --c-testing: #0ea5e9; /* Light Blue */
    --c-verify: #10b981; /* Emerald */
    --c-critical: #ef4444; /* Red */
    
    --border: #e2e8f0;
    --shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
    --shadow-md: 0 10px 25px -5px rgba(0,0,0,0.05);
}

* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: var(--bg-app); color: var(--text-main); -webkit-font-smoothing: antialiased; }

.main-content { margin-left: var(--sidebar-width); padding: 30px; min-height: 100vh; transition: margin-left 0.35s ease;}
@media (max-width: 1024px) { .main-content { margin-left: 0; padding: 20px;} }

.container { max-width: 1400px; margin: 0 auto; }

/* 1. Welcome Banner */
.welcome-banner { 
    background: linear-gradient(135deg, #1e3a8a, #3b82f6); 
    border-radius: 16px; 
    padding: 30px 40px; 
    color: #fff; 
    display: flex; 
    justify-content: space-between; 
    align-items: center; 
    box-shadow: 0 10px 30px rgba(37, 99, 235, 0.2);
    margin-bottom: 30px;
    position: relative;
    overflow: hidden;
}
.welcome-banner::after {
    content: '\f0c3'; /* fa-flask */
    font-family: 'Font Awesome 6 Free';
    font-weight: 900;
    position: absolute;
    right: -20px;
    bottom: -40px;
    font-size: 150px;
    opacity: 0.1;
    transform: rotate(-15deg);
}
.welcome-text h1 { font-size: 28px; font-weight: 800; margin-bottom: 5px; letter-spacing: -0.5px; z-index: 2; position: relative;}
.welcome-text p { font-size: 15px; color: #bfdbfe; font-weight: 500; z-index: 2; position: relative;}
.clock-widget { background: rgba(255,255,255,0.1); backdrop-filter: blur(10px); padding: 10px 20px; border-radius: 10px; font-size: 14px; font-weight: 600; display:flex; align-items:center; gap:10px; border:1px solid rgba(255,255,255,0.2); z-index: 2; position: relative;}

/* 2. Live KPI Grid */
.kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin-bottom: 30px; }
.kpi-card { background: var(--card-bg); padding: 25px; border-radius: 12px; border: 1px solid var(--border); box-shadow: var(--shadow-sm); display: flex; align-items: center; gap: 20px; transition: 0.3s; position: relative; overflow: hidden; }
.kpi-card:hover { transform: translateY(-5px); box-shadow: var(--shadow-md); }
.kpi-icon { width: 60px; height: 60px; border-radius: 12px; display: flex; align-items: center; justify-content: center; font-size: 24px; color: #fff; flex-shrink:0;}
.kpi-data { display: flex; flex-direction: column; }
.kpi-data span { font-size: 13px; font-weight: 700; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 5px; }
.kpi-data strong { font-size: 28px; font-weight: 900; color: var(--text-main); line-height: 1; }

.bg-reception { background: var(--c-reception); box-shadow: 0 4px 15px rgba(139, 92, 246, 0.3); }
.bg-collection { background: var(--c-collection); box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3); }
.bg-testing { background: var(--c-testing); box-shadow: 0 4px 15px rgba(14, 165, 233, 0.3); }
.bg-verify { background: var(--c-verify); box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3); }

/* 3. Main Split Layout */
.layout-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 30px; }
@media (max-width: 1200px) { .layout-grid { grid-template-columns: 1fr; } }

/* Modules Section */
.section-card { background: var(--card-bg); border-radius: 16px; border: 1px solid var(--border); box-shadow: var(--shadow-sm); padding: 25px; }
.section-title { font-size: 18px; font-weight: 800; color: var(--text-main); margin-bottom: 20px; display: flex; align-items: center; gap: 10px; padding-bottom:15px; border-bottom:1px solid var(--border);}

.module-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px; }
.module-btn { background: #f8fafc; border: 1px solid var(--border); border-radius: 12px; padding: 20px; text-decoration: none; color: var(--text-main); display: flex; flex-direction: column; gap: 12px; transition: 0.2s; position:relative;}
.module-btn:hover { background: var(--brand-light); border-color: #bfdbfe; transform: translateY(-2px); }
.module-btn i { font-size: 28px; color: var(--brand-primary); }
.module-btn h4 { font-size: 16px; font-weight: 700; margin:0;}
.module-btn p { font-size: 12px; color: var(--text-muted); font-weight: 500; line-height: 1.4; margin:0;}

.setup-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-top: 20px; }
.setup-card { background: #fff; border: 1px dashed #cbd5e1; padding: 15px; border-radius: 8px; text-align: center; text-decoration:none; transition:0.2s;}
.setup-card:hover { border-color: var(--brand-primary); background:#eff6ff;}
.setup-card i { font-size: 20px; color: var(--text-muted); margin-bottom: 8px; display:block;}
.setup-card strong { display:block; font-size: 18px; color: var(--text-main); font-weight: 900;}
.setup-card span { font-size: 11px; color: var(--text-muted); font-weight: 600; text-transform:uppercase;}

/* Live Feed Table */
.feed-table { width: 100%; border-collapse: collapse; }
.feed-table td { padding: 12px 5px; border-bottom: 1px solid #f1f5f9; vertical-align: middle; }
.feed-table tr:last-child td { border-bottom: none; }
.ft-patient { font-weight: 700; color: var(--text-main); font-size: 14px; display:block; margin-bottom:2px;}
.ft-test { font-size: 12px; color: var(--text-muted); font-weight: 500; }
.ft-time { font-size: 11px; color: #94a3b8; font-weight: 600; }

.status-badge { padding: 4px 8px; border-radius: 6px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; display:inline-block;}
.sb-pending { background: #f3e8ff; color: #6b21a8; }
.sb-accepted { background: #fef3c7; color: #b45309; }
.sb-collected { background: #e0f2fe; color: #0369a1; }
.sb-entered { background: #dcfce7; color: #15803d; }
.sb-other { background: #f1f5f9; color: #475569; }

/* Pulse animation for critical requests */
@keyframes pulseRed { 0% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); } 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }
.critical-dot { display:inline-block; width:8px; height:8px; background:var(--c-critical); border-radius:50%; margin-right:5px; animation: pulseRed 2s infinite;}

</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="main-content" id="mainContent">
    <div class="container">
        
        <div class="welcome-banner">
            <div class="welcome-text">
                <h1> Laboratory Panel </h1>
                <p> </p>
            </div>
            <div class="clock-widget">
                <i class="fa-regular fa-clock"></i>
                <span id="liveClock">Loading time...</span>
            </div>
        </div>

        <div class="kpi-grid">
            <div class="kpi-card">
                <div class="kpi-icon bg-reception"><i class="fa-solid fa-inbox"></i></div>
                <div class="kpi-data">
                    <span>Pending Reception</span>
                    <strong><?= number_format($metrics['pending_reception']) ?></strong>
                </div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon bg-collection"><i class="fa-solid fa-vial"></i></div>
                <div class="kpi-data">
                    <span>Pending Collection</span>
                    <strong><?= number_format($metrics['pending_collection']) ?></strong>
                </div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon bg-testing"><i class="fa-solid fa-microscope"></i></div>
                <div class="kpi-data">
                    <span>Pending Results</span>
                    <strong><?= number_format($metrics['pending_testing']) ?></strong>
                </div>
            </div>
            <div class="kpi-card">
                <div class="kpi-icon bg-verify"><i class="fa-solid fa-user-check"></i></div>
                <div class="kpi-data">
                    <span>Pending Verify</span>
                    <strong><?= number_format($metrics['pending_verification']) ?></strong>
                </div>
            </div>
        </div>

        <div class="layout-grid">
            
            <div class="left-column" style="display:flex; flex-direction:column; gap:30px;">
                
                <div class="section-card">
                    <div class="section-title"><i class="fa-solid fa-network-wired" style="color:var(--brand-primary);"></i>  Clinical Workflows</div>
                    <div class="module-grid">
                        <a href="lab_request_and_recommendations.php" class="module-btn">
                            <i class="fa-solid fa-clipboard-list" style="color:var(--c-reception);"></i>
                            <div>
                                <h4>Reception & Billing</h4>
                                <p>Accept or reject Doctor's lab orders based on clinical requirements.</p>
                            </div>
                        </a>
                        <a href="collect_sample.php" class="module-btn">
                            <i class="fa-solid fa-flask" style="color:var(--c-collection);"></i>
                            <div>
                                <h4>Sample Collection</h4>
                                <p>Generate barcodes, confirm containers, and draw physical samples.</p>
                            </div>
                        </a>
                        <a href="add_lab_result.php" class="module-btn">
                            <i class="fa-solid fa-microscope" style="color:var(--c-testing);"></i>
                            <div>
                                <h4>Result Entry (Testing)</h4>
                                <p>Scientist workbench to enter analytical parameters and clinical remarks.</p>
                            </div>
                        </a>
                        <a href="#" class="module-btn" style="opacity:0.6; pointer-events:none;" title="Module coming soon">
                            <i class="fa-solid fa-file-signature" style="color:var(--c-verify);"></i>
                            <div>
                                <h4>Pathologist Verification</h4>
                                <p>Final approval and digital signature before releasing to EMR.</p>
                            </div>
                        </a>
                    </div>
                </div>

                <div class="section-card">
                    <div class="section-title"><i class="fa-solid fa-cogs" style="color:var(--text-muted);"></i> LIS Configuration Health</div>
                    <p style="font-size:13px; color:var(--text-muted); margin-bottom:10px;">Monitor the integrity of the database dictionaries that drive the automated workflows.</p>
                    
                    <div class="setup-grid">
                        <a href="../system_setup/laboratory/manageLabParameters.php" class="setup-card">
                            <i class="fa-solid fa-vials"></i>
                            <strong><?= number_format($setup_health['active_parameters']) ?></strong>
                            <span>Active Params</span>
                        </a>
                        <a href="../system_setup/laboratory/manageSamples.php" class="setup-card">
                            <i class="fa-solid fa-box-archive"></i>
                            <strong><?= number_format($setup_health['active_samples']) ?></strong>
                            <span>Sample Types</span>
                        </a>
                        <a href="../system_setup/laboratory/mapLabDepartments.php" class="setup-card">
                            <i class="fa-solid fa-sitemap"></i>
                            <strong><?= number_format($setup_health['active_benches']) ?></strong>
                            <span>Lab Benches</span>
                        </a>
                    </div>
                </div>

            </div>

            <div class="section-card" style="height: fit-content;">
                <div class="section-title" style="justify-content:space-between;">
                    <span><i class="fa-solid fa-bolt" style="color:var(--c-collection);"></i> Live Activity Feed</span>
                    <span style="font-size:12px; background:#f1f5f9; padding:4px 10px; border-radius:20px; color:var(--text-muted); font-weight:700;"><i class="fa-solid fa-check"></i> <?= number_format($metrics['completed_today']) ?> Completed Today</span>
                </div>
                
                <?php if(empty($recent_activity)): ?>
                    <div style="text-align:center; padding:40px 20px; color:var(--text-muted);">
                        <i class="fa-solid fa-wind" style="font-size:30px; margin-bottom:10px; color:#cbd5e1;"></i><br>
                        No recent laboratory activity found.
                    </div>
                <?php else: ?>
                    <table class="feed-table">
                        <tbody>
                            <?php foreach($recent_activity as $act): ?>
                                <?php
                                    // Assign Badge Colors based on status
                                    $sbClass = 'sb-other';
                                    if ($act['status'] == 'Pending') $sbClass = 'sb-pending';
                                    if ($act['status'] == 'Accepted') $sbClass = 'sb-accepted';
                                    if ($act['status'] == 'Sample Collected') $sbClass = 'sb-collected';
                                    if ($act['status'] == 'Results Entered') $sbClass = 'sb-entered';
                                    
                                    // Time formatting
                                    $timeObj = new DateTime($act['request_date']);
                                    $timeStr = $timeObj->format('M d, h:i A');
                                ?>
                                <tr>
                                    <td>
                                        <span class="ft-patient">
                                            <?php if($act['priority'] == 'Critical') echo '<span class="critical-dot" title="STAT Priority"></span>'; ?>
                                            <?= htmlspecialchars($act['first_name'].' '.$act['last_name']) ?> <span style="color:#94a3b8; font-weight:500; font-size:12px;">(<?= htmlspecialchars($act['patient_no']) ?>)</span>
                                        </span>
                                        <span class="ft-test"><?= htmlspecialchars($act['service_name']) ?></span>
                                    </td>
                                    <td style="text-align:right;">
                                        <span class="status-badge <?= $sbClass ?>" style="margin-bottom:4px;"><?= htmlspecialchars($act['status']) ?></span><br>
                                        <span class="ft-time"><i class="fa-regular fa-clock"></i> <?= $timeStr ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
                
                <div style="text-align:center; margin-top:20px;">
                    <a href="lab_request_and_recommendations.php" style="font-size:13px; font-weight:700; color:var(--brand-primary); text-decoration:none;">View Full Master Logs <i class="fa-solid fa-arrow-right"></i></a>
                </div>
            </div>

        </div>

    </div>
</div>

<script>
// Simple Live Clock
function updateClock() {
    const now = new Date();
    const options = { weekday: 'short', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' };
    document.getElementById('liveClock').textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateClock, 1000);
updateClock();
</script>

</body>
</html>