<?php 
session_start();
// Enterprise safeguards for handling massive datasets (5000+ records)
ini_set('memory_limit', '1024M');
set_time_limit(300);
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// ==============================================================================
// 1. FETCH FACILITY PROFILE & LOOKUPS
// ==============================================================================
$facility = ['hospital_name' => 'Enterprise LIS Facility', 'address' => 'Central Lab Location', 'primary_phone' => 'N/A'];
$resFacility = $conn->query("SELECT hospital_name, address, primary_phone FROM facility_profile LIMIT 1");
if ($resFacility && $resFacility->num_rows > 0) {
    $facility = $resFacility->fetch_assoc();
}

$sub_departments = [];
$resSub = $conn->query("SELECT id, sub_dept_name FROM lab_sub_departments WHERE is_active = 1 ORDER BY sub_dept_name");
if ($resSub) {
    while($row = $resSub->fetch_assoc()) { $sub_departments[] = $row; }
}

// Fallback session enforcement for unauthenticated testing environments
if (!isset($_SESSION['user_full_name'])) {
    $qUser = "SELECT CONCAT(first_name, ' ', last_name) AS full_name FROM staff WHERE is_active = 1 LIMIT 1";
    $resUser = $conn->query($qUser);
    $_SESSION['user_full_name'] = ($resUser && $resUser->num_rows > 0) ? $resUser->fetch_assoc()['full_name'] : 'System Admin';
}
$userName = $_SESSION['user_full_name'];

// ==============================================================================
// 2. CAPTURE & SANITIZE ADVANCED FILTERS
// ==============================================================================
$date_from = $_GET['date_from'] ?? date('Y-m-d');
$date_to = $_GET['date_to'] ?? date('Y-m-d');
$filter_stage = $_GET['stage'] ?? 'ALL'; 
$filter_dept = $_GET['dept'] ?? 'ALL';
$filter_priority = $_GET['priority'] ?? 'ALL';

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

// Dynamic Workflow Stage Logic
$stage_sql = "1=1";
$stage_label = "Complete Laboratory Pipeline";
$date_field_sql = "clr.request_date";

switch($filter_stage) {
    case 'ALL': 
        $stage_sql = "1=1"; 
        $stage_label = "Complete Laboratory Pipeline"; 
        $date_field_sql = "COALESCE(clr.verified_at, clr.completed_at, csc.collected_at, clr.request_date)";
        break;
    case 'RECEPTION': 
        $stage_sql = "clr.status IN ('Pending', 'Rejected', 'Awaiting Sample', 'Accepted')"; 
        $stage_label = "Reception & Billing Register"; 
        $date_field_sql = "clr.request_date";
        break;
    case 'COLLECTION': 
        $stage_sql = "clr.status IN ('Sample Collected', 'Awaiting Verification', 'Completed') AND csc.collected_at IS NOT NULL"; 
        $stage_label = "Phlebotomy & Sample Collection Log"; 
        $date_field_sql = "csc.collected_at";
        break;
    case 'TESTING': 
        $stage_sql = "clr.status IN ('Results Entered', 'Awaiting Verification', 'Completed') AND clr.completed_at IS NOT NULL"; 
        $stage_label = "Bench Testing & Results Entry Log"; 
        $date_field_sql = "clr.completed_at";
        break;
    case 'VERIFICATION': 
        $stage_sql = "clr.status = 'Completed' AND clr.verified_at IS NOT NULL"; 
        $stage_label = "Pathologist Verification & EMR Release Log"; 
        $date_field_sql = "clr.verified_at";
        break;
}

$dept_sql = ($filter_dept !== 'ALL') ? "AND sc.lab_sub_dept_id = " . intval($filter_dept) : "";
$priority_sql = ($filter_priority !== 'ALL') ? "AND clr.priority = '" . $conn->real_escape_string($filter_priority) . "'" : "";

// ==============================================================================
// 3. SECURE AUDIT LOGGING
// ==============================================================================
$staff_id = isset($_SESSION['staff_id']) ? intval($_SESSION['staff_id']) : 1;
$ip_addr = $_SERVER['REMOTE_ADDR'];
$audit_json = json_encode(['action' => 'Viewed Workflow Audit Report', 'from' => $date_from, 'to' => $date_to, 'stage' => $filter_stage]);
$stmtAudit = $conn->prepare("INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, new_values, ip_address) VALUES (?, 'VIEW', 'clinical_lab_requests', 'WORKFLOW-AUDIT', ?, ?)");
if ($stmtAudit) { $stmtAudit->bind_param("iss", $staff_id, $audit_json, $ip_addr); $stmtAudit->execute(); $stmtAudit->close(); }

// ==============================================================================
// 4. FETCH HIGH-PERFORMANCE WORKFLOW LINE LISTING
// ==============================================================================
$report_data = [];
$qData = "
    SELECT 
        clr.id, clr.status, clr.priority, clr.reject_reason,
        clr.request_date, clr.completed_at, clr.verified_at,
        csc.collected_at, csc.barcode,
        p.first_name, p.last_name, p.patient_no, p.dob, g.gender_name,
        sc.service_name,
        COALESCE(lsd.sub_dept_name, 'Uncategorized') AS sub_dept_name,
        $date_field_sql AS stage_timestamp,
        CONCAT(st_test.first_name, ' ', st_test.last_name) as tester_name,
        CONCAT(st_ver.first_name, ' ', st_ver.last_name) as verifier_name
    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
    LEFT JOIN service_catalog sc ON clr.service_id = sc.id
    LEFT JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
    LEFT JOIN clinical_sample_collections csc ON clr.id = csc.request_id
    LEFT JOIN staff st_test ON st_test.staff_id = clr.completed_by
    LEFT JOIN staff st_ver ON st_ver.staff_id = clr.verified_by
    WHERE ($date_field_sql >= '$date_from_sql' AND $date_field_sql <= '$date_to_sql')
      AND ($stage_sql)
      $dept_sql
      $priority_sql
    ORDER BY stage_timestamp DESC
";

$resData = $conn->query($qData);
if($resData) {
    while ($row = $resData->fetch_assoc()) {
        $report_data[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clinical Workflow Audit Report | <?= htmlspecialchars($facility['hospital_name']) ?></title>

<!-- Fonts & Frameworks -->
<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">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

<!-- DataTables Core & Buttons CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.dataTables.min.css">

<style>
:root {
  --sidebar-width: 280px;
  --bg-app: #f4f7f9;
  --bg-card: #ffffff;
  --brand-primary: #0284c7; /* Medical Blue */
  --brand-dark: #075985;
  --success: #059669;
  --warning: #d97706;
  --danger: #dc2626;
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #475569;
  --shadow-sm: 0 1px 3px rgba(0,0,0,0.05);
  --shadow-md: 0 4px 6px -1px rgba(0,0,0,0.1);
}

* { 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: 25px 35px; display: flex; flex-direction: column; min-height: 100vh; }
@media (max-width: 1024px) { .main-content { margin-left: 0; padding: 15px; } }
.container { max-width: 1600px; margin: 0 auto; width: 100%; display: flex; flex-direction: column; flex: 1;}

.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; }
.page-header h1 { font-size: 24px; color: var(--text-main); font-weight: 900; display: flex; align-items: center; gap: 12px; }

/* Filter Configuration Panel */
.filter-card { background: var(--bg-card); padding: 25px; border-radius: 12px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); margin-bottom: 25px; position: relative;}
.filter-card::before { content: ''; position: absolute; left: 0; top: 0; height: 100%; width: 4px; background: var(--brand-primary); border-radius: 12px 0 0 12px; }
.filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 20px; align-items: end;}
.form-group label { display: block; font-size: 11px; font-weight: 800; color: var(--text-muted); margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
.input-control { width: 100%; padding: 10px 14px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 13px; font-weight: 600; outline: none; background: #f8fafc; transition: 0.2s;}
.input-control:focus { border-color: var(--brand-primary); background: #fff; box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.1); }
.select2-container--default .select2-selection--single { height: 40px; border: 1px solid var(--border-light); border-radius: 6px; display: flex; align-items: center; background: #f8fafc;}
.select2-container--default .select2-selection--single .select2-selection__rendered { font-size: 13px; font-weight: 600; color: var(--text-main); }
.select2-container--default.select2-container--focus .select2-selection--single { border-color: var(--brand-primary); background: #fff; box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.1); }

.btn { padding: 11px 20px; border-radius: 6px; font-size: 13px; font-weight: 800; cursor: pointer; border: none; display: inline-flex; align-items: center; justify-content: center; gap: 8px; transition: 0.2s;}
.btn-primary { background: linear-gradient(135deg, var(--brand-primary), var(--brand-dark)); color: #fff; box-shadow: 0 4px 10px rgba(2, 132, 199, 0.3); }
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 15px rgba(2, 132, 199, 0.4); }

/* Report Canvas */
.report-canvas { background: var(--bg-card); border-radius: 12px; border: 1px solid var(--border-light); box-shadow: var(--shadow-sm); padding: 30px; margin-bottom: 25px; width: 100%; overflow: hidden;}
.facility-header { text-align: center; margin-bottom: 25px; padding-bottom: 20px; border-bottom: 2px solid var(--border-light); }
.facility-header h2 { font-size: 26px; color: var(--text-main); font-weight: 900; margin-bottom: 5px; text-transform: uppercase; letter-spacing: 1px;}
.facility-header p { font-size: 13px; color: var(--text-muted); font-weight: 600; }
.report-title { font-size: 18px; color: var(--brand-primary); font-weight: 800; margin-top: 15px; text-transform: uppercase;}
.report-subtitle { font-size: 13px; color: var(--text-main); font-weight: 700; margin-top: 10px; display: flex; justify-content: center; gap: 15px;}
.report-subtitle span { background: #f1f5f9; padding: 6px 12px; border-radius: 20px; border: 1px solid var(--border-light); }

/* DataTable Header & Styling */
.top-panel { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; background: #f8fafc; padding: 12px 20px; border-radius: 8px; border: 1px solid var(--border-light); flex-wrap: wrap; gap: 15px;}
.dataTables_filter input { border-radius: 6px; padding: 6px 12px; border: 1px solid var(--border-light); outline: none; font-weight: 600; font-size: 13px;}

/* Unified Export Buttons */
.dt-buttons { display: flex; gap: 8px; }
.dt-btn-excel, .dt-btn-pdf, .dt-btn-print, .btn-word { background: #fff !important; border: 1px solid var(--border-light) !important; border-radius: 6px !important; font-size: 13px !important; font-weight: 700 !important; padding: 8px 16px !important; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; transition: 0.2s !important; text-decoration: none;}
.dt-btn-excel { color: #16a34a !important; } .dt-btn-excel:hover { background: #f0fdf4 !important; border-color: #bbf7d0 !important; }
.dt-btn-pdf { color: #dc2626 !important; } .dt-btn-pdf:hover { background: #fef2f2 !important; border-color: #fecaca !important; }
.dt-btn-print { color: #475569 !important; } .dt-btn-print:hover { background: #f8fafc !important; border-color: #cbd5e1 !important; }
.btn-word { color: #2563eb !important; } .btn-word:hover { background: #eff6ff !important; border-color: #bfdbfe !important; }

/* Table Aesthetics */
.audit-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.audit-table th, .audit-table td { border-bottom: 1px solid var(--border-light); padding: 12px 10px; text-align: left; vertical-align: middle; }
.audit-table th { background: #f8fafc; font-weight: 800; color: var(--text-muted); text-transform: uppercase; font-size: 11px; letter-spacing: 0.5px; border-top: 1px solid var(--border-light);}
.audit-table tbody tr:hover td { background: #f1f5f9 !important; }

.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; }
.sb-rejected { background: #fee2e2; color: #b91c1c; }

.priority-high { color: var(--danger); font-weight: 800; }
@keyframes pulseRed { 0% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0.4); } 70% { box-shadow: 0 0 0 6px rgba(220, 38, 38, 0); } 100% { box-shadow: 0 0 0 0 rgba(220, 38, 38, 0); } }
.critical-dot { display:inline-block; width:8px; height:8px; background:var(--danger); border-radius:50%; margin-right:5px; animation: pulseRed 2s infinite;}

.col-patient { font-weight: 800; color: var(--text-main); font-size: 13px; display: block; margin-bottom: 2px;}
.col-sub { font-size: 11px; color: var(--text-muted); font-weight: 600;}
.col-actor { font-weight: 700; color: var(--brand-primary); }

/* Loader */
#loaderOverlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 9999; justify-content: center; align-items: center; flex-direction: column; }
.spinner { width: 50px; height: 50px; border: 4px solid #e2e8f0; border-top-color: var(--brand-primary); border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 15px;}
@keyframes spin { to { transform: rotate(360deg); } }

.dataTables_wrapper .dataTables_paginate .paginate_button.current { background: var(--brand-primary) !important; color: #fff !important; border: none !important; border-radius: 6px; font-weight: 800;}
.dataTables_info { font-weight: 600; color: var(--text-muted); font-size: 13px;}
.dataTables_length select { border-radius: 6px; padding: 4px 8px; border: 1px solid var(--border-light); outline: none; font-weight: 600;}

.enterprise-footer { text-align: center; font-size: 12px; color: var(--text-muted); font-weight: 600; padding: 20px 0; margin-top: auto;}
</style>
</head>
<body>

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

<div id="loaderOverlay">
    <div class="spinner"></div>
    <h2 style="color: var(--text-main); font-weight: 800;">Aggregating Workflow Audit...</h2>
    <p style="color: var(--text-muted); font-weight: 600;">Extracting targeted line-listing for selected parameters.</p>
</div>

<div class="main-content" id="mainContent">
  <div class="container">
    
    <div class="page-header">
      <h1><i class="fa-solid fa-list-check" style="color: var(--brand-primary);"></i> Master Clinical Workflow Audit</h1>
    </div>

    <!-- Configuration Filter -->
    <div class="filter-card">
        <div class="filter-grid">
            <div class="form-group">
                <label>Date From</label>
                <input type="date" id="f_dateFrom" class="input-control" value="<?= htmlspecialchars($date_from) ?>">
            </div>
            <div class="form-group">
                <label>Date To</label>
                <input type="date" id="f_dateTo" class="input-control" value="<?= htmlspecialchars($date_to) ?>">
            </div>
            <div class="form-group">
                <label>Workflow Module Filter</label>
                <select id="f_stage" class="input-control select2">
                    <option value="ALL" <?= $filter_stage=='ALL'?'selected':'' ?>>Complete Pipeline Overview</option>
                    <option value="RECEPTION" <?= $filter_stage=='RECEPTION'?'selected':'' ?>>1. Reception & Billing</option>
                    <option value="COLLECTION" <?= $filter_stage=='COLLECTION'?'selected':'' ?>>2. Sample Collection</option>
                    <option value="TESTING" <?= $filter_stage=='TESTING'?'selected':'' ?>>3. Testing & Bench Entry</option>
                    <option value="VERIFICATION" <?= $filter_stage=='VERIFICATION'?'selected':'' ?>>4. Pathologist Verification</option>
                </select>
            </div>
            <div class="form-group">
                <label>Sub-Department</label>
                <select id="f_dept" class="input-control select2">
                    <option value="ALL">-- All Departments --</option>
                    <?php foreach($sub_departments as $dept): ?>
                        <option value="<?= $dept['id'] ?>" <?= $filter_dept==$dept['id']?'selected':'' ?>><?= htmlspecialchars($dept['sub_dept_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Priority Filter</label>
                <select id="f_priority" class="input-control select2">
                    <option value="ALL" <?= $filter_priority=='ALL'?'selected':'' ?>>-- All Priorities --</option>
                    <option value="Routine" <?= $filter_priority=='Routine'?'selected':'' ?>>Routine</option>
                    <option value="High" <?= $filter_priority=='High'?'selected':'' ?>>High Priority</option>
                    <option value="Critical" <?= $filter_priority=='Critical'?'selected':'' ?>>Critical (STAT)</option>
                </select>
            </div>
            <div class="form-group">
                <button class="btn btn-primary" onclick="generateReport()" style="width: 100%; height: 40px;">
                    <i class="fa-solid fa-bolt"></i> Run Audit
                </button>
            </div>
        </div>
    </div>

    <!-- Report Canvas -->
    <div class="report-canvas" id="exportableRegion">
        
        <div class="facility-header">
            <h2><?= htmlspecialchars($facility['hospital_name']) ?></h2>
            <p><i class="fa-solid fa-location-dot" style="color:var(--brand-primary);"></i> <?= htmlspecialchars($facility['address']) ?> &nbsp;|&nbsp; <i class="fa-solid fa-phone" style="color:var(--brand-primary);"></i> <?= htmlspecialchars($facility['primary_phone']) ?></p>
            <div class="report-title">Laboratory Workflow Audit Line-Listing</div>
            <div class="report-subtitle">
                <span><i class="fa-regular fa-calendar"></i> <?= date('d M Y', strtotime($date_from)) ?> - <?= date('d M Y', strtotime($date_to)) ?></span>
                <span><i class="fa-solid fa-filter"></i> <?= htmlspecialchars($stage_label) ?></span>
            </div>
        </div>

        <div class="table-wrapper">
            <table id="auditTable" class="audit-table display nowrap" style="width:100%">
                <thead>
                    <?php if ($filter_stage == 'COLLECTION'): ?>
                        <tr>
                            <th>#</th>
                            <th>Collection Time</th>
                            <th>Patient Details</th>
                            <th>Test & Dept</th>
                            <th>Sample Barcode</th>
                            <th>Collected By</th>
                            <th>Current Status</th>
                        </tr>
                    <?php elseif ($filter_stage == 'TESTING'): ?>
                        <tr>
                            <th>#</th>
                            <th>Bench Completion Time</th>
                            <th>Patient Details</th>
                            <th>Test & Dept</th>
                            <th>Tested By (Scientist)</th>
                            <th>Priority</th>
                            <th>Current Status</th>
                        </tr>
                    <?php elseif ($filter_stage == 'RECEPTION'): ?>
                        <tr>
                            <th>#</th>
                            <th>Order Received Time</th>
                            <th>Patient Details</th>
                            <th>Investigation Requested</th>
                            <th>Priority</th>
                            <th>Order Status</th>
                            <th>Remarks / Rejection</th>
                        </tr>
                    <?php elseif ($filter_stage == 'VERIFICATION'): ?>
                        <tr>
                            <th>#</th>
                            <th>Final Auth Time</th>
                            <th>Patient Details</th>
                            <th>Investigation</th>
                            <th>Verified By (Pathologist)</th>
                            <th>Initial Tester</th>
                            <th>Final Status</th>
                        </tr>
                    <?php else: ?>
                        <!-- ALL OVERVIEW -->
                        <tr>
                            <th>#</th>
                            <th>Latest Timestamp</th>
                            <th>Patient Details</th>
                            <th>Investigation & Dept</th>
                            <th>Responsible Actor</th>
                            <th>Priority</th>
                            <th>Status & Details</th>
                        </tr>
                    <?php endif; ?>
                </thead>
                <tbody>
                    <?php if(empty($report_data)): ?>
                        <!-- DataTables empty state will handle this -->
                    <?php else: ?>
                        <?php $row_num = 1; foreach($report_data as $row): ?>
                        <?php 
                            // Age Calculation
                            $age_str = "";
                            if($row['dob']) {
                                $dob = new DateTime($row['dob']);
                                $now = new DateTime($row['stage_timestamp'] ?? $row['request_date']);
                                $age_str = $now->diff($dob)->y . "y";
                            }
                            
                            $patient_block = "<span class='col-patient'>" . ($row['priority'] == 'Critical' ? "<span class='critical-dot' title='STAT Priority'></span>" : "") . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . "</span><span class='col-sub'>ID: " . htmlspecialchars($row['patient_no']) . " | " . htmlspecialchars($row['gender_name']) . " (" . $age_str . ")</span>";
                            $test_block = "<span style='font-weight:800; color:var(--brand-primary); display:block; margin-bottom:2px;'>" . htmlspecialchars($row['service_name']) . "</span><span class='col-sub'>" . htmlspecialchars($row['sub_dept_name']) . "</span>";
                            $time_block = "<span style='font-weight:800; color:var(--text-main); display:block;'>" . ($row['stage_timestamp'] ? date('d M Y', strtotime($row['stage_timestamp'])) : 'Pending') . "</span><span style='font-size:11px; color:var(--text-muted); font-weight:700;'>" . ($row['stage_timestamp'] ? date('h:i A', strtotime($row['stage_timestamp'])) : '') . "</span>";
                            $priority_block = "<div class='" . (($row['priority'] == 'Critical' || $row['priority'] == 'High') ? 'priority-high' : 'col-sub') . "'>" . htmlspecialchars($row['priority']) . "</div>";

                            // Status Badge Logic
                            $sbClass = 'sb-other';
                            if ($row['status'] == 'Pending') $sbClass = 'sb-pending';
                            if ($row['status'] == 'Accepted' || $row['status'] == 'Awaiting Sample') $sbClass = 'sb-accepted';
                            if ($row['status'] == 'Sample Collected') $sbClass = 'sb-collected';
                            if ($row['status'] == 'Results Entered' || $row['status'] == 'Awaiting Verification') $sbClass = 'sb-entered';
                            if ($row['status'] == 'Completed') $sbClass = 'sb-verified';
                            if ($row['status'] == 'Rejected') $sbClass = 'sb-rejected';
                            $status_badge = "<span class='status-badge {$sbClass}'>" . htmlspecialchars($row['status']) . "</span>";
                        ?>

                        <!-- DYNAMIC ROW RENDERING BASED ON STAGE -->
                        <?php if ($filter_stage == 'COLLECTION'): ?>
                            <tr>
                                <td style="font-weight: 800; color: var(--text-muted);"><?= $row_num++ ?></td>
                                <td><?= $time_block ?></td>
                                <td><?= $patient_block ?></td>
                                <td><?= $test_block ?></td>
                                <td><span style="font-family: monospace; font-weight:800; font-size:13px; color:var(--text-main);">BC-<?= htmlspecialchars($row['barcode'] ?? 'N/A') ?></span></td>
                                <td><span class="col-actor">Phlebotomy Unit</span></td>
                                <td><?= $status_badge ?></td>
                            </tr>
                        <?php elseif ($filter_stage == 'TESTING'): ?>
                            <tr>
                                <td style="font-weight: 800; color: var(--text-muted);"><?= $row_num++ ?></td>
                                <td><?= $time_block ?></td>
                                <td><?= $patient_block ?></td>
                                <td><?= $test_block ?></td>
                                <td><span class="col-actor"><?= htmlspecialchars($row['tester_name'] ?? 'Pending') ?></span></td>
                                <td><?= $priority_block ?></td>
                                <td><?= $status_badge ?></td>
                            </tr>
                        <?php elseif ($filter_stage == 'RECEPTION'): ?>
                            <tr>
                                <td style="font-weight: 800; color: var(--text-muted);"><?= $row_num++ ?></td>
                                <td><?= $time_block ?></td>
                                <td><?= $patient_block ?></td>
                                <td><?= $test_block ?></td>
                                <td><?= $priority_block ?></td>
                                <td><?= $status_badge ?></td>
                                <td>
                                    <?php if($row['status'] == 'Rejected'): ?>
                                        <span style="color:var(--danger); font-size:11px; font-weight:700;"><?= htmlspecialchars($row['reject_reason']) ?></span>
                                    <?php else: ?>
                                        <span style="color:var(--success); font-size:11px; font-weight:700;">Order Accepted</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php elseif ($filter_stage == 'VERIFICATION'): ?>
                            <tr>
                                <td style="font-weight: 800; color: var(--text-muted);"><?= $row_num++ ?></td>
                                <td><?= $time_block ?></td>
                                <td><?= $patient_block ?></td>
                                <td><?= $test_block ?></td>
                                <td><span class="col-actor"><?= htmlspecialchars($row['verifier_name'] ?? 'Pending') ?></span></td>
                                <td><span style="color:var(--text-muted); font-weight:600; font-size:11px;"><?= htmlspecialchars($row['tester_name'] ?? 'N/A') ?></span></td>
                                <td><?= $status_badge ?></td>
                            </tr>
                        <?php else: ?>
                            <!-- ALL OVERVIEW -->
                            <?php 
                                $action_by = 'System / Doctor';
                                $stage_details = "";
                                if ($row['status'] == 'Rejected') {
                                    $stage_details = "<span style='color:var(--danger); font-weight:700;'>Rejected:</span> " . htmlspecialchars($row['reject_reason']);
                                } elseif ($row['status'] == 'Completed' && $row['verified_at']) {
                                    $action_by = $row['verifier_name'] ?? 'Pathologist';
                                    $stage_details = "<span style='color:var(--success); font-weight:700;'>Verified & Released</span>";
                                } elseif (($row['status'] == 'Results Entered' || $row['status'] == 'Awaiting Verification') && $row['completed_at']) {
                                    $action_by = $row['tester_name'] ?? 'Scientist';
                                    $stage_details = "<span style='color:var(--brand-primary); font-weight:700;'>Bench Testing Completed</span>";
                                } elseif ($row['status'] == 'Sample Collected' && $row['collected_at']) {
                                    $action_by = 'Phlebotomy Unit';
                                    $stage_details = "<span style='color:var(--warning); font-weight:700;'>Sample Barcode: BC-".$row['barcode']."</span>";
                                } else {
                                    $stage_details = "<span style='color:var(--text-muted); font-weight:600;'>Order Received in LIS</span>";
                                }
                            ?>
                            <tr>
                                <td style="font-weight: 800; color: var(--text-muted);"><?= $row_num++ ?></td>
                                <td><?= $time_block ?></td>
                                <td><?= $patient_block ?></td>
                                <td><?= $test_block ?></td>
                                <td><span class="col-actor"><?= htmlspecialchars($action_by) ?></span></td>
                                <td><?= $priority_block ?></td>
                                <td>
                                    <div style="margin-bottom:4px;"><?= $status_badge ?></div>
                                    <div style="font-size:11px;"><?= $stage_details ?></div>
                                </td>
                            </tr>
                        <?php endif; ?>

                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="enterprise-footer">
      Laboratory Management System v2.4.1 | Enterprise Audit Engine | Powered by Afritechs Gh Ltd
    </div>

  </div>
</div>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<!-- DataTables High Performance Export Suite -->
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$(document).ready(function() {
    $('.select2').select2();

    const facilityName = "<?= htmlspecialchars($facility['hospital_name']) ?>";
    const reportTitle = `Workflow Audit Log - <?= htmlspecialchars($stage_label) ?> (<?= date('d-M-Y', strtotime($date_from)) ?> to <?= date('d-M-Y', strtotime($date_to)) ?>)`;

    // Define Custom MS Word Button HTML
    const wordBtnHtml = `<button class="btn-word" onclick="exportToWord('exportableRegion', 'Lab_Workflow_Audit_Report')"><i class="fa-solid fa-file-word"></i> Word</button>`;

    // High Performance DataTable Initialization
    const table = $('#auditTable').DataTable({
        dom: '<"top-panel"Bf>rt<"bottom-panel"lip>',
        deferRender: true,
        pageLength: 50,
        lengthMenu: [ [25, 50, 100, 500, 1000], [25, 50, 100, 500, 1000] ],
        ordering: true, 
        scrollX: true,
        language: { search: "", searchPlaceholder: "Filter Log Entries..." },
        buttons: [
            {
                extend: 'excelHtml5',
                text: '<i class="fa-solid fa-file-excel"></i> Excel',
                title: reportTitle,
                messageTop: facilityName + '\n' + '<?= htmlspecialchars($facility['address']) ?>',
                className: 'dt-btn-excel'
            },
            {
                extend: 'pdfHtml5',
                text: '<i class="fa-solid fa-file-pdf"></i> PDF',
                title: facilityName + '\n' + reportTitle,
                orientation: 'landscape',
                pageSize: 'A4',
                className: 'dt-btn-pdf',
                customize: function(doc) {
                    doc.styles.title = { color: '#0f172a', fontSize: '16', bold: true, alignment: 'center', margin: [0, 0, 0, 10] }
                    doc.styles.tableHeader = { bold: true, fontSize: 10, color: '#0f172a', fillColor: '#f8fafc', alignment: 'left' }
                }
            },
            {
                extend: 'print',
                text: '<i class="fa-solid fa-print"></i> Print',
                title: '', 
                className: 'dt-btn-print'
            }
        ]
    });

    // Append Word button to the end of the DataTable buttons group
    $('.dt-buttons').append(wordBtnHtml);
});

function generateReport() {
    const from = document.getElementById('f_dateFrom').value;
    const to = document.getElementById('f_dateTo').value;
    const stage = document.getElementById('f_stage').value;
    const dept = document.getElementById('f_dept').value;
    const priority = document.getElementById('f_priority').value;

    if(!from || !to) { alert("Please ensure both dates are selected."); return; }
    
    document.getElementById('loaderOverlay').style.display = 'flex';
    window.location.href = `?date_from=${from}&date_to=${to}&stage=${stage}&dept=${dept}&priority=${priority}`;
}

// Enterprise Microsoft Word Generator
function exportToWord(elementId, filename = '') {
    const preHtml = `<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
    <head><meta charset='utf-8'><title>Audit Report</title>
    <style>
        table { border-collapse: collapse; width: 100%; font-family: 'Segoe UI', Arial, sans-serif; font-size: 11px;}
        th, td { border: 1px solid #cbd5e1; padding: 8px; text-align: left; vertical-align: middle;}
        th { background-color: #f8fafc; font-weight: bold; color: #0f172a;}
        h2 { text-align: center; font-family: Arial, sans-serif; color: #0f172a; margin-bottom: 5px; font-size: 20px;}
        p, .report-title, .report-subtitle { text-align: center; font-family: Arial, sans-serif; color: #64748b; font-size: 12px; margin: 2px 0;}
        .report-title { color: #2563eb; font-weight: bold; font-size: 16px; margin-top: 15px;}
        .top-panel, .bottom-panel, .dt-buttons, .dataTables_info, .dataTables_paginate, .dataTables_length, .dataTables_filter { display: none !important; }
    </style></head><body>`;
    
    const postHtml = "</body></html>";
    const html = preHtml + document.getElementById(elementId).innerHTML + postHtml;

    const blob = new Blob(['\ufeff', html], { type: 'application/msword' });
    const url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html);
    filename = filename ? filename + '.doc' : 'document.doc';

    const downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob ){
        navigator.msSaveOrOpenBlob(blob, filename);
    } else {
        downloadLink.href = url; downloadLink.download = filename; downloadLink.click();
    }
    document.body.removeChild(downloadLink);
}
</script>

</body>
</html>