<?php 
session_start();
// Enterprise safeguards for handling massive datasets (5000+ records)
ini_set('memory_limit', '512M');
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 Hospital', 'address' => '', 'primary_phone' => ''];
$resFacility = $conn->query("SELECT hospital_name, address, primary_phone FROM facility_profile LIMIT 1");
if ($resFacility && $resFacility->num_rows > 0) $facility = $resFacility->fetch_assoc();

// Fetch Sub-Departments for Filter Dropdown
$sub_departments = [];
$resSub = $conn->query("SELECT id, sub_dept_name FROM lab_sub_departments WHERE is_active = 1 ORDER BY sub_dept_name");
while($row = $resSub->fetch_assoc()) { $sub_departments[] = $row; }

// Fetch All Services for Filter Dropdown 
$all_services = [];
$resServ = $conn->query("SELECT id, service_name, lab_sub_dept_id FROM service_catalog WHERE is_active = 1 ORDER BY service_name");
while($row = $resServ->fetch_assoc()) { $all_services[] = $row; }

// ==============================================================================
// 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'] ?? 'VERIFIED'; 
$filter_dept = $_GET['dept'] ?? 'ALL';
$filter_test = $_GET['test'] ?? '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');

// Build Workflow Stage Logic
$stage_sql = "";
$stage_label = "";
switch($filter_stage) {
    case 'ALL': $stage_sql = "1=1"; $stage_label = "All Workflow Stages"; break;
    case 'ACCEPTED': $stage_sql = "clr.status != 'Pending'"; $stage_label = "Accepted & Beyond"; break;
    case 'COLLECTED': $stage_sql = "clr.status IN ('Sample Collected', 'Awaiting Verification', 'Completed')"; $stage_label = "Specimen Collected"; break;
    case 'TESTED': $stage_sql = "clr.status IN ('Awaiting Verification', 'Completed')"; $stage_label = "Results Entered"; break;
    case 'VERIFIED': $stage_sql = "clr.status = 'Completed'"; $stage_label = "Strictly Verified Labs"; break;
}

// Build Department & Test Logic
$dept_sql = ($filter_dept !== 'ALL') ? "AND sc.lab_sub_dept_id = " . intval($filter_dept) : "";
$test_sql = ($filter_test !== 'ALL') ? "AND sc.id = " . intval($filter_test) : "";

// ==============================================================================
// 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' => 'Generated Master Operational 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', 'OPERATIONAL-REPORT', ?, ?)");
if ($stmtAudit) { $stmtAudit->bind_param("iss", $staff_id, $audit_json, $ip_addr); $stmtAudit->execute(); $stmtAudit->close(); }

// ==============================================================================
// 4. HIGH-PERFORMANCE DATA AGGREGATION
// ==============================================================================
$age_buckets = ['<29 days', '1-11mths', '1-4', '5-9', '10-14', '15-17', '18-19', '20-34', '35-49', '50-59', '60-69', '70+'];
$report_data = [];

// Pre-fill array matrix
$qPre = "SELECT service_name FROM service_catalog sc WHERE is_active = 1 $dept_sql $test_sql ORDER BY service_name ASC";
$resPre = $conn->query($qPre);
while ($row = $resPre->fetch_assoc()) {
    $report_data[$row['service_name']] = [
        'Male' => array_fill_keys($age_buckets, 0),
        'Female' => array_fill_keys($age_buckets, 0)
    ];
}

// Execute optimized analytical query
$qData = "
    SELECT 
        sc.service_name, g.gender_name,
        TIMESTAMPDIFF(DAY, p.dob, COALESCE(clr.verified_at, clr.completed_at, clr.request_date)) AS age_days,
        TIMESTAMPDIFF(MONTH, p.dob, COALESCE(clr.verified_at, clr.completed_at, clr.request_date)) AS age_months,
        TIMESTAMPDIFF(YEAR, p.dob, COALESCE(clr.verified_at, clr.completed_at, clr.request_date)) AS age_years
    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
    JOIN service_catalog sc ON clr.service_id = sc.id
    WHERE clr.request_date >= '$date_from_sql' AND clr.request_date <= '$date_to_sql' AND ($stage_sql) $dept_sql $test_sql
";

$resData = $conn->query($qData);
if($resData) {
    while ($row = $resData->fetch_assoc()) {
        $test_name = $row['service_name'];
        $gender = ($row['gender_name'] === 'Male') ? 'Male' : 'Female';
        $days = (int)$row['age_days']; $months = (int)$row['age_months']; $years = (int)$row['age_years'];
        $bucket = '';

        if ($days < 29) { $bucket = '<29 days'; } 
        elseif ($months >= 1 && $years < 1) { $bucket = '1-11mths'; } 
        elseif ($years >= 1 && $years <= 4) { $bucket = '1-4'; } 
        elseif ($years >= 5 && $years <= 9) { $bucket = '5-9'; } 
        elseif ($years >= 10 && $years <= 14) { $bucket = '10-14'; } 
        elseif ($years >= 15 && $years <= 17) { $bucket = '15-17'; } 
        elseif ($years >= 18 && $years <= 19) { $bucket = '18-19'; } 
        elseif ($years >= 20 && $years <= 34) { $bucket = '20-34'; } 
        elseif ($years >= 35 && $years <= 49) { $bucket = '35-49'; } 
        elseif ($years >= 50 && $years <= 59) { $bucket = '50-59'; } 
        elseif ($years >= 60 && $years <= 69) { $bucket = '60-69'; } 
        elseif ($years >= 70) { $bucket = '70+'; } 
        else { $bucket = '20-34'; }

        if(isset($report_data[$test_name][$gender][$bucket])) {
            $report_data[$test_name][$gender][$bucket]++;
        }
    }
}
$userName = $_SESSION['user_full_name'] ?? 'Dr. Admin';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Master Operational Report | 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">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<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: #f1f5f9;
  --bg-card: #ffffff;
  --brand-primary: #2563eb;
  --brand-dark: #1e3a8a;
  --success: #10b981;
  --border-light: #e2e8f0;
  --text-main: #0f172a;
  --text-muted: #64748b;
  --shadow-sm: 0 4px 6px -1px rgba(0,0,0,0.05);
  --shadow-md: 0 10px 25px -5px 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: 30px; display: flex; flex-direction: column; min-height: 100vh; }
@media (max-width: 1024px) { .main-content { margin-left: 0; padding: 15px; } }
.container { max-width: 100%; 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: 26px; color: var(--text-main); font-weight: 900; display: flex; align-items: center; gap: 10px; }

/* 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: 5px; background: var(--brand-primary); border-radius: 12px 0 0 12px; }
.filter-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; align-items: end;}
.form-group label { display: block; font-size: 12px; font-weight: 800; color: var(--text-muted); margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.5px; }
.input-control { width: 100%; padding: 12px; border: 1px solid var(--border-light); border-radius: 8px; font-size: 14px; 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 4px rgba(37, 99, 235, 0.1); }
.select2-container--default .select2-selection--single { height: 46px; border: 1px solid var(--border-light); border-radius: 8px; display: flex; align-items: center; background: #f8fafc;}
.select2-container--default .select2-selection--single .select2-selection__rendered { font-size: 14px; 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 4px rgba(37, 99, 235, 0.1); }

.btn { padding: 14px 24px; border-radius: 8px; font-size: 14px; 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 15px rgba(37, 99, 235, 0.3); }
.btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(37, 99, 235, 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;}
.facility-header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 2px solid var(--border-light); }
.facility-header h2 { font-size: 28px; color: var(--text-main); font-weight: 900; margin-bottom: 5px; text-transform: uppercase; letter-spacing: 1px;}
.facility-header p { font-size: 14px; color: var(--text-muted); font-weight: 600; }
.report-title { font-size: 20px; color: var(--brand-primary); font-weight: 800; margin-top: 20px; text-transform: uppercase;}
.report-subtitle { font-size: 14px; color: var(--text-main); font-weight: 700; margin-top: 8px; display: flex; justify-content: center; gap: 20px;}
.report-subtitle span { background: #f1f5f9; padding: 6px 15px; border-radius: 20px; border: 1px solid var(--border-light); }

/* DataTable Enhancements */
.table-wrapper { width: 100%; overflow: hidden; border-radius: 8px; border: 1px solid var(--border-light); }
.matrix-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.matrix-table th, .matrix-table td { border: 1px solid var(--border-light); padding: 12px 8px; text-align: center; vertical-align: middle; }
.matrix-table th { background: #f8fafc; font-weight: 800; color: var(--text-main); text-transform: uppercase; font-size: 12px; }
.matrix-table th.male-hdr { background: #eff6ff; color: #1d4ed8; border-bottom: 2px solid #1d4ed8;}
.matrix-table th.female-hdr { background: #fdf2f8; color: #be185d; border-bottom: 2px solid #be185d;}

/* Sticky Columns for large datasets */
.matrix-table td.col-idx { font-weight: 800; color: var(--text-muted); background: #f8fafc; position: sticky; left: 0; z-index: 2; width: 50px; }
.matrix-table td.col-test { text-align: left; font-weight: 700; background: #fff; min-width: 250px; position: sticky; left: 50px; z-index: 2; border-right: 2px solid var(--border-light);}
.matrix-table th.col-idx, .matrix-table th.col-test { position: sticky; left: 0; z-index: 3; background: #f8fafc; }
.matrix-table th.col-test { left: 50px; border-right: 2px solid var(--border-light); }

.matrix-table tbody tr:hover td { background: #f1f5f9 !important; }
.matrix-table td.zero-val { color: #cbd5e1; font-weight: 500;} 
.matrix-table td.has-val { font-weight: 900; color: var(--brand-primary); font-size: 15px;}
.matrix-table td.col-total { font-weight: 900; font-size: 16px; color: #fff; background: var(--text-main) !important; }

/* Export Panel */
.export-panel { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; background: #f8fafc; padding: 15px 25px; border-radius: 8px; border: 1px solid var(--border-light); }
.export-title { font-weight: 800; font-size: 14px; color: var(--text-main); display: flex; align-items: center; gap: 8px;}
.dt-buttons { display: flex; gap: 10px; flex-wrap: wrap;}

/* Unified Export Button Styles */
.export-btn { background: #fff !important; border: 1px solid var(--border-light) !important; color: var(--text-main) !important; border-radius: 6px !important; font-size: 13px !important; font-weight: 700 !important; padding: 10px 18px !important; transition: 0.2s !important; display: inline-flex; align-items: center; gap: 8px; text-decoration: none;}
.export-btn:hover { background: var(--bg-app) !important; border-color: var(--brand-primary) !important; color: var(--brand-primary) !important; transform: translateY(-2px); box-shadow: var(--shadow-sm);}
.export-btn.btn-word { color: #2563eb !important; border-color: #bfdbfe !important; background: #eff6ff !important;}
.export-btn.btn-excel { color: #16a34a !important; border-color: #bbf7d0 !important; background: #f0fdf4 !important;}
.export-btn.btn-pdf { color: #dc2626 !important; border-color: #fecaca !important; background: #fef2f2 !important;}

/* 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: 5px 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_wrapper .dataTables_info { font-weight: 600; color: var(--text-muted); }
.dataTables_length select { border-radius: 6px; padding: 6px; border: 1px solid var(--border-light); outline: none; font-weight: 600;}

.enterprise-footer { text-align: center; font-size: 13px; color: var(--text-muted); font-weight: 600; padding: 30px 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;">Processing Analytics Engine...</h2>
    <p style="color: var(--text-muted); font-weight: 600;">Aggregating demographic matrix across massive datasets.</p>
</div>

<div class="main-content" id="mainContent">
  <div class="container">
    
    <div class="page-header">
      <h1><i class="fa-solid fa-chart-line" style="color: var(--brand-primary);"></i> Master Operational Analytics</h1>
    </div>

    <!-- Configuration Filter -->
    <div class="filter-card">
        <div class="filter-grid">
            <div class="form-group">
                <label>Filter Date From</label>
                <input type="date" id="f_dateFrom" class="input-control" value="<?= htmlspecialchars($date_from) ?>">
            </div>
            <div class="form-group">
                <label>Filter Date To</label>
                <input type="date" id="f_dateTo" class="input-control" value="<?= htmlspecialchars($date_to) ?>">
            </div>
            <div class="form-group">
                <label>Workflow Integrity Stage</label>
                <select id="f_stage" class="input-control select2">
                    <option value="ALL" <?= $filter_stage=='ALL'?'selected':'' ?>>All Stages (Incl. Pending)</option>
                    <option value="ACCEPTED" <?= $filter_stage=='ACCEPTED'?'selected':'' ?>>Accepted & Beyond</option>
                    <option value="COLLECTED" <?= $filter_stage=='COLLECTED'?'selected':'' ?>>Sample Collected & Beyond</option>
                    <option value="TESTED" <?= $filter_stage=='TESTED'?'selected':'' ?>>Results Entered</option>
                    <option value="VERIFIED" <?= $filter_stage=='VERIFIED'?'selected':'' ?>>Strictly Verified (MOH Default)</option>
                </select>
            </div>
            <div class="form-group">
                <label>Target Sub-Department</label>
                <select id="f_dept" class="input-control select2" onchange="filterTestsByDept()">
                    <option value="ALL">-- Entire Laboratory System --</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>Target Test / Investigation</label>
                <select id="f_test" class="input-control select2">
                    <option value="ALL">-- Analyze All Tests --</option>
                    <?php foreach($all_services as $srv): ?>
                        <option value="<?= $srv['id'] ?>" data-dept="<?= $srv['lab_sub_dept_id'] ?>" <?= $filter_test==$srv['id']?'selected':'' ?>><?= htmlspecialchars($srv['service_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <button class="btn btn-primary" onclick="generateReport()" style="width: 100%; height: 46px;">
                    <i class="fa-solid fa-bolt"></i> Generate Matrix
                </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 Operations & Demographics Matrix</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="export-panel">
            <div class="export-title"><i class="fa-solid fa-download" style="color: var(--brand-primary);"></i> Export Engine</div>
            <div id="dtButtonsContainer" class="dt-buttons">
                <!-- Custom Word Export appended here, DataTables buttons prepended -->
                <button class="export-btn btn-word" onclick="exportToWord('exportableRegion', 'Lab_Operational_Report')">
                    <i class="fa-solid fa-file-word" style="font-size: 16px;"></i> Word Document
                </button>
            </div>
        </div>

        <div class="table-wrapper">
            <table id="masterReportTable" class="matrix-table display nowrap" style="width:100%">
                <thead>
                    <tr>
                        <th rowspan="2" class="col-idx">#</th>
                        <th rowspan="2" class="col-test">Test / Investigation Name</th>
                        <th colspan="12" class="gender-header male-hdr">Gender Male Analytics</th>
                        <th colspan="12" class="gender-header female-hdr">Gender Female Analytics</th>
                        <th rowspan="2" style="background:#0f172a; color:#fff;">Grand<br>Total</th>
                    </tr>
                    <tr>
                        <?php foreach($age_buckets as $bucket): ?> <th><?= htmlspecialchars($bucket) ?></th> <?php endforeach; ?>
                        <?php foreach($age_buckets as $bucket): ?> <th><?= htmlspecialchars($bucket) ?></th> <?php endforeach; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($report_data)): ?>
                        <tr><td colspan="27" style="padding:40px; font-size:15px; font-weight:700;">No data matches your selected criteria.</td></tr>
                    <?php else: ?>
                        <?php $row_num = 1; foreach($report_data as $test_name => $genders): ?>
                        <?php 
                            $row_total = array_sum($genders['Male']) + array_sum($genders['Female']);
                            if ($row_total == 0 && $filter_test === 'ALL') continue; 
                        ?>
                        <tr>
                            <td class="col-idx"><?= $row_num++ ?></td>
                            <td class="col-test"><?= htmlspecialchars($test_name) ?></td>
                            
                            <!-- Output Male Data -->
                            <?php foreach($age_buckets as $bucket): ?>
                                <?php $val = $genders['Male'][$bucket]; ?>
                                <td class="<?= $val == 0 ? 'zero-val' : 'has-val' ?>"><?= $val ?></td>
                            <?php endforeach; ?>

                            <!-- Output Female Data -->
                            <?php foreach($age_buckets as $bucket): ?>
                                <?php $val = $genders['Female'][$bucket]; ?>
                                <td class="<?= $val == 0 ? 'zero-val' : 'has-val' ?>"><?= $val ?></td>
                            <?php endforeach; ?>
                            
                            <td class="col-total"><?= number_format($row_total) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="enterprise-footer">
      Laboratory Management System v2.4.1 | High-Performance Analytics 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 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>
$(document).ready(function() {
    $('.select2').select2();
    filterTestsByDept(false); 

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

    // High Performance DataTable Initialization (Limited to Excel and PDF)
    const table = $('#masterReportTable').DataTable({
        deferRender: true,
        pageLength: 25,
        lengthMenu: [10, 25, 50, 100, 500],
        ordering: false, 
        scrollX: true,
        language: { search: "Filter Matrix Results:" },
        buttons: [
            {
                extend: 'excelHtml5',
                text: '<i class="fa-solid fa-file-excel" style="font-size: 16px;"></i> Excel Spreadsheet',
                title: reportTitle,
                messageTop: facilityName + '\n' + '<?= htmlspecialchars($facility['address']) ?>',
                className: 'export-btn btn-excel'
            },
            {
                extend: 'pdfHtml5',
                text: '<i class="fa-solid fa-file-pdf" style="font-size: 16px;"></i> PDF Document',
                title: facilityName + '\n' + reportTitle,
                orientation: 'landscape',
                pageSize: 'A3',
                className: 'export-btn btn-pdf',
                customize: function(doc) {
                    doc.styles.title = { color: '#0f172a', fontSize: '16', bold: true, alignment: 'center', margin: [0, 0, 0, 10] }
                }
            }
        ]
    });

    // Move DT buttons into our custom panel BEFORE the Word button
    table.buttons().container().prependTo('#dtButtonsContainer');
});

function filterTestsByDept(resetTest = true) {
    const deptId = document.getElementById('f_dept').value;
    const testSelect = document.getElementById('f_test');
    
    Array.from(testSelect.options).forEach(opt => {
        if (opt.value === 'ALL') return; 
        const optDept = opt.getAttribute('data-dept');
        if (deptId === 'ALL' || optDept === deptId) {
            opt.style.display = 'block'; opt.disabled = false;
        } else {
            opt.style.display = 'none'; opt.disabled = true;
        }
    });

    if (resetTest) $(testSelect).val('ALL').trigger('change');
}

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 test = document.getElementById('f_test').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}&test=${test}`;
}

// 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>Operational Report</title>
    <style>
        table { border-collapse: collapse; width: 100%; font-family: 'Segoe UI', Arial, sans-serif; font-size: 10px;}
        th, td { border: 1px solid #94a3b8; padding: 6px; text-align: center; vertical-align: middle;}
        th { background-color: #f8fafc; font-weight: bold; color: #0f172a;}
        .col-idx { width: 30px; }
        .col-test { text-align: left; font-weight: bold; width: 250px;}
        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;}
        .export-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>