<?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'] ?? 'Dr. Admin';
$user_role = $_SESSION['user_role'] ?? 'Laboratory Manager';

// ==============================================================================
// 1. UNIVERSAL DATE FILTER INITIALIZATION
// ==============================================================================
$date_from_raw = $_GET['date_from'] ?? date('Y-m-d');
$date_to_raw = $_GET['date_to'] ?? date('Y-m-d');

$date_from_sql = $conn->real_escape_string($date_from_raw . ' 00:00:00');
$date_to_sql = $conn->real_escape_string($date_to_raw . ' 23:59:59');

$filter_label = ($date_from_raw === $date_to_raw) ? date('d M Y', strtotime($date_from_raw)) : date('d M', strtotime($date_from_raw)) . ' - ' . date('d M Y', strtotime($date_to_raw));

// ==============================================================================
// 2. DYNAMIC DEMOGRAPHIC KPI ENGINE (FILTERED PERIOD)
// ==============================================================================
function getKPIBreakdown($conn, $date_field, $table_join, $from, $to) {
    $sql = "SELECT 
        COUNT(clr.id) as total,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) >= 18 AND g.gender_name = 'Male' THEN 1 ELSE 0 END) as adult_m,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) >= 18 AND g.gender_name = 'Female' THEN 1 ELSE 0 END) as adult_f,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) < 18 AND g.gender_name = 'Male' THEN 1 ELSE 0 END) as child_m,
        SUM(CASE WHEN TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) < 18 AND g.gender_name = 'Female' THEN 1 ELSE 0 END) as child_f
    FROM clinical_lab_requests clr
    JOIN patient p ON clr.patient_no = p.patient_no
    LEFT JOIN gender g ON p.gender_id = g.id
    $table_join
    WHERE $date_field >= '$from' AND $date_field <= '$to'";
    
    $res = $conn->query($sql);
    return $res ? $res->fetch_assoc() : ['total'=>0, 'adult_m'=>0, 'adult_f'=>0, 'child_m'=>0, 'child_f'=>0];
}

$kpis = [
    'lab_requests' => array_merge(
        ['title' => 'Lab Requests', 'icon' => 'fa-inbox', 'color' => 'var(--text-main)', 'link' => 'lab_request_and_recommendations.php'],
        getKPIBreakdown($conn, 'clr.request_date', '', $date_from_sql, $date_to_sql)
    ),
    'collected' => array_merge(
        ['title' => 'Samples Collected', 'icon' => 'fa-vial', 'color' => 'var(--warning)', 'link' => 'collect_sample.php'],
        getKPIBreakdown($conn, 'csc.collected_at', 'JOIN clinical_sample_collections csc ON clr.id = csc.request_id', $date_from_sql, $date_to_sql)
    ),
    'entered_results' => array_merge(
        ['title' => 'Results Entered', 'icon' => 'fa-microscope', 'color' => 'var(--brand-secondary)', 'link' => 'add_lab_result.php'],
        getKPIBreakdown($conn, 'clr.completed_at', '', $date_from_sql, $date_to_sql)
    ),
    'verified_results' => array_merge(
        ['title' => 'Results Verified', 'icon' => 'fa-user-check', 'color' => 'var(--success)', 'link' => 'verify_lab_results.php'],
        getKPIBreakdown($conn, 'clr.verified_at', '', $date_from_sql, $date_to_sql)
    )
];

$metrics['completed_in_period'] = $kpis['verified_results']['total'];

// ==============================================================================
// 3. 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'];

// ==============================================================================
// 4. FILTERED SUB-DEPARTMENT WORKLOAD
// ==============================================================================
$workload_status = [];
$qWork = "
    SELECT 
        lsd.sub_dept_name,
        COUNT(clr.id) as total_tests,
        SUM(CASE WHEN clr.status = 'Completed' THEN 1 ELSE 0 END) as completed_tests
    FROM clinical_lab_requests clr
    JOIN service_catalog sc ON clr.service_id = sc.id
    JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
    WHERE clr.request_date >= '$date_from_sql' AND clr.request_date <= '$date_to_sql'
    GROUP BY lsd.id
    ORDER BY total_tests DESC
";
$resWork = $conn->query($qWork);
if ($resWork) {
    while($row = $resWork->fetch_assoc()) {
        $workload_status[] = $row;
    }
}

// ==============================================================================
// 5. FILTERED LIVE ACTIVITY FEED
// ==============================================================================
$recent_activity = [];
$qActivity = "
    SELECT 
        clr.id, clr.status, clr.priority, clr.request_date,
        COALESCE(sc.service_name, clr.test_name) AS service_name, 
        p.first_name, p.last_name, p.patient_no
    FROM clinical_lab_requests clr
    LEFT JOIN service_catalog sc ON clr.service_id = sc.id
    JOIN patient p ON clr.patient_no = p.patient_no
    WHERE clr.request_date >= '$date_from_sql' AND clr.request_date <= '$date_to_sql'
    ORDER BY clr.request_date DESC 
    LIMIT 10
";
$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; 
    --c-collection: #f59e0b; 
    --c-testing: #0ea5e9; 
    --c-verify: #10b981; 
    --c-critical: #ef4444; 
    
    --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; }

/* Filter Configuration Bar */
.filter-card { background: #fff; padding: 15px 25px; border-radius: 12px; border: 1px solid var(--border); box-shadow: var(--shadow-sm); margin-bottom: 25px; display: flex; gap: 20px; align-items: flex-end; flex-wrap: wrap;}
.form-group { flex: 1; min-width: 200px; }
.form-group label { display: block; font-size: 11px; font-weight: 700; color: var(--text-muted); margin-bottom: 6px; text-transform: uppercase; letter-spacing: 0.5px; }
.input-control { width: 100%; padding: 10px 12px; border: 1px solid var(--border); border-radius: 6px; font-size: 13px; font-weight: 600; outline: none; background: #fff; font-family: inherit;}
.input-control:focus { border-color: var(--brand-primary); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1); }
.btn { padding: 10px 20px; border-radius: 6px; font-size: 13px; font-weight: 700; cursor: pointer; border: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px; transition: 0.2s;}
.btn-primary { background: var(--brand-primary); color: #fff; }
.btn-primary:hover { background: #1d4ed8; }

/* 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'; 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;}

/* 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; text-decoration:none;}
.kpi-card:hover { transform: translateY(-5px); box-shadow: var(--shadow-md); border-color: var(--brand-primary);}
.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: 12px; 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; margin-bottom: 10px;}

.kpi-demographics { display: flex; flex-direction: column; gap: 4px; border-top: 1px solid var(--border); padding-top: 10px;}
.demo-row { display: flex; font-size: 11px; font-weight: 600; color: var(--text-muted); align-items:center; gap: 8px;}
.demo-row strong { font-size:11px; color: var(--text-main); letter-spacing:0;}

.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); }

/* 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(220px, 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;}

/* Reports Grid */
.reports-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; }
.report-btn { display: flex; align-items: center; gap: 12px; padding: 15px; background: #fff; border: 1px solid var(--border); border-radius: 10px; text-decoration: none; color: var(--text-main); transition: 0.2s; }
.report-btn:hover { border-color: var(--c-reception); box-shadow: var(--shadow-sm); transform: translateX(3px); }
.report-btn i { font-size: 20px; color: var(--text-muted); width: 30px; text-align: center; }
.report-btn:hover i { color: var(--c-reception); }
.report-info strong { display: block; font-size: 14px; font-weight: 700; margin-bottom: 2px;}
.report-info span { font-size: 11px; color: var(--text-muted); font-weight: 500;}

/* 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: #fef08a; color: #b45309; }
.sb-verified { background: #dcfce7; color: #15803d; }

@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;}

/* Workload List */
.telemetry-list { display: flex; flex-direction: column; gap: 15px;}
.telemetry-item { display: flex; justify-content: space-between; align-items: center; padding-bottom: 15px; border-bottom: 1px dashed var(--border); }
.telemetry-item:last-child { border-bottom: none; padding-bottom: 0; }
.machine-info { display: flex; flex-direction: column; }
.machine-name { font-weight: 700; font-size: 13px; color: var(--text-main); }
.machine-dept { font-size: 11px; color: var(--text-muted); margin-top: 2px; font-weight: 600;}
.status-indicator { display: flex; flex-direction: column; align-items: flex-end; font-size: 12px; font-weight: 600; }
.progress-bar-bg { width: 100px; height: 6px; background: var(--border); border-radius: 3px; margin-top: 5px; overflow: hidden;}
.progress-bar-fill { height: 100%; background: var(--success); border-radius: 3px;}

.enterprise-footer { text-align: center; font-size: 12px; color: var(--text-muted); font-weight: 500; padding: 20px 0; margin-top: 20px; }
</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>Welcome back, <?= htmlspecialchars($user_name) ?>. Real-time operations overview.</p>
            </div>
            <div class="clock-widget">
                <i class="fa-regular fa-clock"></i>
                <span id="liveClock">Loading time...</span>
            </div>
        </div>

        <!-- Dynamic Universal Date Filter -->
        <div class="filter-card">
            <div class="form-group">
                <label>Filter Date From</label>
                <input type="date" id="dateFrom" class="input-control" value="<?= htmlspecialchars($date_from_raw) ?>">
            </div>
            <div class="form-group">
                <label>Filter Date To</label>
                <input type="date" id="dateTo" class="input-control" value="<?= htmlspecialchars($date_to_raw) ?>">
            </div>
            <div class="form-group" style="flex: 0 0 auto;">
                <button class="btn btn-primary" onclick="applyDashboardFilter()">
                    <i class="fa-solid fa-filter"></i> Apply Matrix
                </button>
            </div>
        </div>

        <div class="kpi-grid">
            <?php foreach($kpis as $key => $kpi): ?>
            <a href="<?= $kpi['link'] ?>" class="kpi-card">
                <div class="kpi-icon <?= ($key=='lab_requests')?'bg-reception':(($key=='collected')?'bg-collection':(($key=='entered_results')?'bg-testing':'bg-verify')) ?>">
                    <i class="fa-solid <?= $kpi['icon'] ?>"></i>
                </div>
                <div class="kpi-data" style="width: 100%;">
                    <span><?= htmlspecialchars($kpi['title']) ?></span>
                    <strong><?= number_format($kpi['total']) ?></strong>
                    
                    <div class="kpi-demographics">
                        <div class="demo-row">
                            Adults: 
                            <span style="color:var(--brand-primary);">M: <strong><?= number_format($kpi['adult_m']) ?></strong></span> | 
                            <span style="color:#db2777;">F: <strong><?= number_format($kpi['adult_f']) ?></strong></span>
                        </div>
                        <div class="demo-row">
                            Children: 
                            <span style="color:var(--brand-primary);">M: <strong><?= number_format($kpi['child_m']) ?></strong></span> | 
                            <span style="color:#db2777;">F: <strong><?= number_format($kpi['child_f']) ?></strong></span>
                        </div>
                    </div>
                </div>
            </a>
            <?php endforeach; ?>
        </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 remarks.</p>
                            </div>
                        </a>
                        <a href="verify_lab_results.php" class="module-btn">
                            <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>

                <!-- DYNAMIC ANALYTICS & REPORTS -->
                <div class="section-card">
                    <div class="section-title"><i class="fa-solid fa-chart-pie" style="color:var(--c-reception);"></i> Data Analytics, Audits & MoH Returns</div>
                    <div class="reports-grid">
                        
                        <a href="lab_operational_report.php" class="report-btn" style="border: 2px solid var(--brand-primary); background: var(--brand-light);">
                            <i class="fa-solid fa-chart-line" style="color: var(--brand-primary);"></i>
                            <div class="report-info">
                                <strong style="color: var(--brand-primary);">Master Operational Report</strong>
                                <span style="color: var(--brand-dark);">Dynamic Analytics & Matrix</span>
                            </div>
                        </a>

                        <a href="lab_workflow_report.php" class="report-btn" style="border: 2px solid var(--c-collection); background: #fffbeb;">
                            <i class="fa-solid fa-list-check" style="color: var(--c-collection);"></i>
                            <div class="report-info">
                                <strong style="color: var(--c-collection);">Master Workflow Audit</strong>
                                <span style="color: var(--text-main);">Full Pipeline & Stage Logs</span>
                            </div>
                        </a>

                        <a href="lab_performance_analytics.php" class="report-btn">
                            <i class="fa-solid fa-bolt" style="color: #8b5cf6;"></i>
                            <div class="report-info">
                                <strong>Performance Analytics</strong>
                                <span>Turnaround Time & Volume</span>
                            </div>
                        </a>

                        <a href="moh_haematology_report.php" class="report-btn">
                            <i class="fa-solid fa-droplet" style="color: #dc2626;"></i>
                            <div class="report-info">
                                <strong>Haematology Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                        <a href="moh_biochemistry_report.php" class="report-btn">
                            <i class="fa-solid fa-flask-vial" style="color: #be185d;"></i>
                            <div class="report-info">
                                <strong>Biochemistry Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                        <a href="moh_microbiology_report.php" class="report-btn">
                            <i class="fa-solid fa-bugs" style="color: #b45309;"></i>
                            <div class="report-info">
                                <strong>Microbiology Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                        <a href="moh_parasitology_report.php" class="report-btn">
                            <i class="fa-solid fa-mosquito" style="color: #16a34a;"></i>
                            <div class="report-info">
                                <strong>Parasitology Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                        <a href="moh_pathology_report.php" class="report-btn">
                            <i class="fa-solid fa-microscope" style="color: #0f172a;"></i>
                            <div class="report-info">
                                <strong>Pathology Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                        <a href="moh_immunology_report.php" class="report-btn">
                            <i class="fa-solid fa-shield-virus" style="color: #2563eb;"></i>
                            <div class="report-info">
                                <strong>Immunology Returns</strong>
                                <span>MOH Demographics Matrix</span>
                            </div>
                        </a>
                    </div>
                </div>

            </div>

            <div class="right-column" style="display:flex; flex-direction:column; gap:30px;">
                
                <div class="section-card" style="height: fit-content; padding: 20px;">
                    <div class="section-title" style="justify-content:space-between; margin-bottom: 10px;">
                        <span><i class="fa-solid fa-bolt" style="color:var(--c-collection);"></i> Filtered Feed</span>
                        <span style="font-size:11px; background:#f1f5f9; padding:4px 8px; border-radius:20px; color:var(--text-muted); font-weight:700;"><i class="fa-solid fa-check"></i> <?= number_format($metrics['completed_in_period']) ?> Verified</span>
                    </div>
                    
                    <?php if(empty($recent_activity)): ?>
                        <div style="text-align:center; padding:30px 20px; color:var(--text-muted);">
                            <i class="fa-solid fa-wind" style="font-size:24px; margin-bottom:10px; color:#cbd5e1;"></i><br>
                            <span style="font-size:13px;">No activity found in this period.</span>
                        </div>
                    <?php else: ?>
                        <table class="feed-table">
                            <tbody>
                                <?php foreach($recent_activity as $act): ?>
                                    <?php
                                        // Assign Badge Colors based on our actual database status
                                        $sbClass = 'sb-other';
                                        if ($act['status'] == 'Pending') $sbClass = 'sb-pending';
                                        if ($act['status'] == 'Awaiting Sample') $sbClass = 'sb-accepted';
                                        if ($act['status'] == 'Sample Collected') $sbClass = 'sb-collected';
                                        if ($act['status'] == 'Awaiting Verification') $sbClass = 'sb-entered';
                                        if ($act['status'] == 'Completed') $sbClass = 'sb-verified';
                                        
                                        $timeObj = new DateTime($act['request_date']);
                                        $timeStr = $timeObj->format('M d, h:i A');
                                    ?>
                                    <tr>
                                        <td style="padding: 10px 5px;">
                                            <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; padding: 10px 5px;">
                                            <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>

                <!-- Filtered Workload Status -->
                <div class="section-card" style="padding: 20px;">
                    <div class="section-title">
                        <span><i class="fa-solid fa-server" style="color: var(--text-muted); margin-right: 8px;"></i> Filtered Dept Workload</span>
                    </div>
                    <div class="telemetry-list">
                        <?php if(empty($workload_status)): ?>
                            <div style="text-align: center; color: var(--text-muted); font-size: 13px; padding: 20px;">No tests ordered in period.</div>
                        <?php else: ?>
                            <?php foreach($workload_status as $work): ?>
                            <div class="telemetry-item">
                                <div class="machine-info">
                                    <span class="machine-name"><?= htmlspecialchars($work['sub_dept_name']) ?></span>
                                    <span class="machine-dept"><?= number_format($work['total_tests']) ?> Total Tests</span>
                                </div>
                                <div class="status-indicator">
                                    <span style="color: var(--success);"><?= number_format($work['completed_tests']) ?> Completed</span>
                                    <?php $pct = $work['total_tests'] > 0 ? ($work['completed_tests'] / $work['total_tests']) * 100 : 0; ?>
                                    <div class="progress-bar-bg"><div class="progress-bar-fill" style="width: <?= $pct ?>%;"></div></div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="section-card" style="padding: 20px;">
                    <div class="section-title"><i class="fa-solid fa-cogs" style="color:var(--text-muted);"></i> Setup Health</div>
                    <div class="setup-grid" style="margin-top: 10px;">
                        <a href="../system_setup/laboratory/manageLabParameters.php" class="setup-card">
                            <strong><?= number_format($setup_health['active_parameters']) ?></strong>
                            <span>Params</span>
                        </a>
                        <a href="../system_setup/laboratory/manageSamples.php" class="setup-card">
                            <strong><?= number_format($setup_health['active_samples']) ?></strong>
                            <span>Samples</span>
                        </a>
                        <a href="../system_setup/laboratory/mapLabDepartments.php" class="setup-card">
                            <strong><?= number_format($setup_health['active_benches']) ?></strong>
                            <span>Benches</span>
                        </a>
                    </div>
                </div>

            </div>

        </div>

        <div class="enterprise-footer">
            Laboratory Management System v2.4.1 | 21 CFR Part 11 Compliant | Powered by Afritechs Gh Ltd
        </div>

    </div>
</div>

<script>
// Filter Application
function applyDashboardFilter() {
    const from = document.getElementById('dateFrom').value;
    const to = document.getElementById('dateTo').value;
    if(!from || !to) {
        alert("Please ensure both dates are selected.");
        return;
    }
    window.location.href = `?date_from=${from}&date_to=${to}`;
}

// 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' };
    const clk = document.getElementById('liveClock');
    if(clk) clk.textContent = now.toLocaleDateString('en-US', options);
}
setInterval(updateClock, 1000);
updateClock();
</script>

<script src="../../assets/js/lab_dashboard.js"></script>

</body>
</html>