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

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

$msg = '';
$error = '';

// ==============================================================================
// 1. PROCESS RESULT SUBMISSION
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_results'])) {
    $request_id = (int)$_POST['request_id'];
    $scientist_remarks = $_POST['scientist_remarks'] ?? '';
    $results = $_POST['results'] ?? [];
    $flags = $_POST['flags'] ?? [];
    $ref_ranges = $_POST['ref_ranges'] ?? [];

    if ($request_id > 0 && !empty($results)) {
        $conn->begin_transaction();
        try {
            // A. Insert each individual parameter result
            $stmtRes = $conn->prepare("INSERT INTO clinical_lab_results (request_id, parameter_id, result_value, reference_range_used, result_flag) VALUES (?, ?, ?, ?, ?)");
            
            foreach ($results as $param_id => $val) {
                $p_id = (int)$param_id;
                $val = trim($val);
                $flag = $flags[$p_id] ?? 'Normal';
                $ref = $ref_ranges[$p_id] ?? '';

                $stmtRes->bind_param("iisss", $request_id, $p_id, $val, $ref, $flag);
                $stmtRes->execute();
            }

            // B. Update the main request status
            $stmtUpdate = $conn->prepare("UPDATE clinical_lab_requests SET status = 'Results Entered', scientist_remarks = ? WHERE id = ?");
            $stmtUpdate->bind_param("si", $scientist_remarks, $request_id);
            $stmtUpdate->execute();

            $conn->commit();
            header("Location: add_lab_result.php?msg=success");
            exit;
        } catch (Exception $e) {
            $conn->rollback();
            $error = "Failed to save results: " . $e->getMessage();
        }
    } else {
        $error = "No results were provided.";
    }
}

// ==============================================================================
// 2. FETCH DYNAMIC FILTERS & PENDING WORKLIST (ZERO HARDCODES)
// ==============================================================================

// A. Fetch Lab Sub-Departments dynamically for the filter dropdown
$lab_departments = [];
$qDepts = "SELECT sub_dept_name FROM lab_sub_departments WHERE is_active = 1 ORDER BY sub_dept_name ASC";
$resDept = $conn->query($qDepts);
if ($resDept) while($row = $resDept->fetch_assoc()) $lab_departments[] = $row['sub_dept_name'];

// B. Fetch Rejection Reasons dynamically
$dynamic_flags = [];
$resFlags = $conn->query("SELECT flag_name FROM lab_result_flags ORDER BY id ASC");
if($resFlags) while($row = $resFlags->fetch_assoc()) $dynamic_flags[] = $row['flag_name'];

// C. Fetch the entire Pending Results Queue (Samples Collected but no results yet)
$worklist = [];
$qQueue = "
    SELECT 
        clr.id AS request_id,
        clr.request_date,
        clr.priority,
        sc.service_name AS test_name,
        COALESCE(lsd.sub_dept_name, d.department_name, 'Laboratory') AS department,
        p.patient_no,
        p.first_name,
        p.last_name,
        csc.barcode,
        csc.collected_at
    FROM clinical_lab_requests clr
    JOIN service_catalog sc ON clr.service_id = sc.id
    LEFT JOIN departments d ON sc.department_id = d.id
    LEFT JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
    JOIN patient p ON clr.patient_no = p.patient_no
    LEFT JOIN clinical_sample_collections csc ON csc.request_id = clr.id
    WHERE clr.status = 'Sample Collected'
    ORDER BY 
        CASE clr.priority WHEN 'Critical' THEN 1 WHEN 'High' THEN 2 ELSE 3 END ASC, 
        csc.collected_at ASC
";
$resQueue = $conn->query($qQueue);
if ($resQueue) {
    while ($row = $resQueue->fetch_assoc()) {
        $worklist[] = $row;
    }
}

// ==============================================================================
// 3. FETCH SELECTED TEST DETAILS & PARAMETERS (If selected)
// ==============================================================================
$target_request_id = $_GET['request_id'] ?? 0;
$lab_test_data = null;
$parameters = [];

if ($target_request_id > 0) {
    // Fetch Clinical & Patient Context
    $qContext = "
        SELECT 
            clr.id AS request_id, clr.service_id, clr.priority,
            p.first_name, p.last_name, p.patient_no,
            TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
            g.gender_name AS gender,
            sc.service_name AS test_name,
            COALESCE(lsd.sub_dept_name, d.department_name, 'Laboratory') AS department,
            csc.barcode AS sample_id,
            lst.container_type AS sample_type,
            csc.collected_at AS collection_time,
            CONCAT('Dr. ', s.first_name, ' ', s.last_name) AS doctor,
            clr.notes AS diagnosis_notes
        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
        LEFT JOIN departments d ON sc.department_id = d.id
        LEFT JOIN lab_sub_departments lsd ON sc.lab_sub_dept_id = lsd.id
        LEFT JOIN clinical_sample_collections csc ON csc.request_id = clr.id
        LEFT JOIN lab_sample_types lst ON csc.sample_id = lst.id
        LEFT JOIN visit_master vm ON clr.visit_id = vm.id
        LEFT JOIN staff s ON vm.primary_doctor_id = s.staff_id
        WHERE clr.id = ? LIMIT 1
    ";
    
    $stmtCtx = $conn->prepare($qContext);
    $stmtCtx->bind_param("i", $target_request_id);
    $stmtCtx->execute();
    $lab_test_data = $stmtCtx->get_result()->fetch_assoc();
    $stmtCtx->close();

    if ($lab_test_data) {
        // Fetch the exact mapped parameters and dynamically match Reference Ranges!
        $qParams = "
            SELECT 
                p.id AS param_id, p.parameter_name, p.unit_of_measure, p.result_type, p.options_list,
                (SELECT CONCAT(min_value, ' - ', max_value) 
                 FROM lab_reference_ranges r 
                 WHERE r.parameter_id = p.id 
                 AND (r.gender_target = 'Universal' OR r.gender_target = ?) 
                 AND ? BETWEEN r.min_age_years AND r.max_age_years 
                 LIMIT 1) AS active_ref_range
            FROM lab_test_parameter_mapping m
            JOIN lab_parameters p ON m.parameter_id = p.id
            WHERE m.service_id = ?
            ORDER BY m.display_order ASC
        ";
        $stmtParams = $conn->prepare($qParams);
        $stmtParams->bind_param("sii", $lab_test_data['gender'], $lab_test_data['age'], $lab_test_data['service_id']);
        $stmtParams->execute();
        $resParams = $stmtParams->get_result();
        while($row = $resParams->fetch_assoc()) {
            $parameters[] = $row;
        }
        $stmtParams->close();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Enter Lab Results | 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&display=swap" rel="stylesheet">
<style>
:root {
  --sidebar-width: 280px;
  --bg-app: #f4f7f9; --bg-card: #ffffff;
  --brand-primary: #1e3a8a; --brand-secondary: #2563eb;
  --success: #10b981; --danger: #ef4444; --warning: #f59e0b;
  --text-main: #0f172a; --text-muted: #64748b;
  --border-light: #e2e8f0;
}

* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Inter', sans-serif; background: var(--bg-app); color: var(--text-main); }
.main-content { margin-left: var(--sidebar-width); padding: 25px; min-height: 100vh; display: flex; flex-direction: column;}
.container { max-width: 1600px; margin: 0 auto; width: 100%; display: flex; flex-direction: column; flex: 1; }

.workflow-tracker { display: flex; align-items: center; gap: 15px; margin-bottom: 20px; background: var(--bg-card); padding: 12px 20px; border-radius: 8px; border: 1px solid var(--border-light); }
.step { display: flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600; color: var(--text-muted); }
.step.completed { color: var(--success); }
.step.active { color: var(--brand-secondary); }
.step-divider { color: var(--border-light); font-size: 12px; }

/* Split Layout */
.split-layout { display: flex; gap: 25px; flex: 1; align-items: stretch; }
.left-pane { width: 380px; display: flex; flex-direction: column; gap: 15px; flex-shrink: 0; }
.right-pane { flex: 1; background: var(--bg-card); border-radius: 10px; border: 1px solid var(--border-light); padding: 25px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }

/* Filters & Queue */
.filter-box { background: var(--bg-card); padding: 15px; border-radius: 10px; border: 1px solid var(--border-light); display: flex; flex-direction: column; gap: 10px; }
.input-control { width: 100%; padding: 10px 12px; border: 1px solid var(--border-light); border-radius: 6px; font-size: 13px; outline: none; background: #f8fafc; font-family: inherit; }
.input-control:focus { border-color: var(--brand-secondary); background: #fff; box-shadow: 0 0 0 3px rgba(37,99,235,0.1); }

.queue-list { display: flex; flex-direction: column; gap: 10px; max-height: calc(100vh - 250px); overflow-y: auto; padding-right: 5px;}
.queue-list::-webkit-scrollbar { width: 6px; }
.queue-list::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

.queue-card { background: #fff; border: 1px solid var(--border-light); padding: 15px; border-radius: 8px; cursor: pointer; transition: 0.2s; text-decoration: none; color: inherit; display: block; }
.queue-card:hover { border-color: var(--brand-secondary); box-shadow: 0 4px 6px rgba(0,0,0,0.05); transform: translateY(-2px); }
.queue-card.active { border-color: var(--brand-secondary); background: #eff6ff; border-left: 4px solid var(--brand-secondary); }

.qc-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.qc-name { font-weight: 700; font-size: 14px; color: var(--brand-primary); }
.qc-priority { font-size: 10px; font-weight: 700; padding: 3px 8px; border-radius: 12px; text-transform: uppercase; }
.prio-critical { background: #fee2e2; color: #dc2626; }
.prio-high { background: #fef3c7; color: #d97706; }
.prio-routine { background: #e0f2fe; color: #0284c7; }

.qc-test { font-size: 13px; font-weight: 600; margin-bottom: 4px; }
.qc-meta { font-size: 11px; color: var(--text-muted); display: flex; justify-content: space-between; align-items: center; }

/* Workbench */
.wb-header { border-bottom: 2px solid var(--border-light); padding-bottom: 15px; margin-bottom: 20px; }
.wb-title { font-size: 20px; font-weight: 800; color: var(--brand-primary); margin-bottom: 5px; }
.wb-subtitle { font-size: 13px; color: var(--text-muted); font-weight: 500; }

.info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; background: #f8fafc; padding: 15px; border-radius: 8px; border: 1px dashed #cbd5e1; margin-bottom: 25px; }
.ig-item { display: flex; flex-direction: column; gap: 4px; }
.ig-label { font-size: 11px; text-transform: uppercase; font-weight: 700; color: var(--text-muted); }
.ig-value { font-size: 14px; font-weight: 600; color: var(--text-main); }

.parameter-row { display: grid; grid-template-columns: 2fr 1.5fr 1fr 1fr; gap: 15px; align-items: center; padding: 15px; border: 1px solid var(--border-light); border-radius: 8px; margin-bottom: 10px; background: #fff; }
.param-name { font-weight: 700; font-size: 14px; color: var(--text-main); display: flex; flex-direction: column; gap: 4px; }
.param-unit { font-size: 12px; color: var(--text-muted); font-weight: 600; }
.param-ref { font-size: 12px; color: var(--brand-secondary); background: #e0f2fe; padding: 8px; border-radius: 6px; text-align: center; font-weight: 700; }

.actions-bar { display: flex; justify-content: flex-end; gap: 15px; margin-top: 30px; padding-top: 20px; border-top: 1px solid var(--border-light); }
.btn { padding: 12px 25px; border: none; border-radius: 8px; font-weight: 700; font-size: 14px; cursor: pointer; transition: 0.2s; display: inline-flex; align-items: center; gap: 8px; }
.btn-primary { background: var(--success); color: #fff; }
.btn-primary:hover { background: #059669; }

.alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-size: 14px; font-weight: 600; display:flex; align-items:center; gap:10px;}
.alert-success { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
.alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
</style>
</head>
<body>

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

<div class="main-content">
  <div class="container">

    <div class="workflow-tracker">
      <div class="step completed"><i class="fa-solid fa-check-circle"></i> Reception</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step completed"><i class="fa-solid fa-check-circle"></i> Sample Collection</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step active"><i class="fa-solid fa-microscope"></i> Testing & Results</div>
      <i class="fa-solid fa-chevron-right step-divider"></i>
      <div class="step"><i class="fa-solid fa-user-check"></i> Verification</div>
    </div>

    <?php if(isset($_GET['msg']) && $_GET['msg'] == 'success'): ?>
        <div class="alert alert-success"><i class="fa-solid fa-check-circle"></i> Results saved successfully! Pending verification.</div>
    <?php endif; ?>
    <?php if(!empty($error)): ?>
        <div class="alert alert-error"><i class="fa-solid fa-triangle-exclamation"></i> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div class="split-layout">
        
        <div class="left-pane">
            <div class="filter-box">
                <div style="position:relative;">
                    <i class="fa-solid fa-search" style="position:absolute; left:12px; top:12px; color:var(--text-muted);"></i>
                    <input type="text" id="queueSearch" class="input-control" placeholder="Search patient, barcode, test..." style="padding-left:35px;" onkeyup="filterQueue()">
                </div>
                <div style="display:flex; gap:10px;">
                    <input type="date" id="queueDate" class="input-control" onchange="filterQueue()">
                    <select id="queueDept" class="input-control" onchange="filterQueue()">
                        <option value="ALL">All Benches</option>
                        <?php foreach($lab_departments as $dept): ?>
                            <option value="<?= htmlspecialchars($dept) ?>"><?= htmlspecialchars($dept) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="queue-list" id="queueList">
                <?php if(empty($worklist)): ?>
                    <div style="text-align:center; padding:30px; background:#fff; border-radius:8px; border:1px dashed var(--border-light); color:var(--text-muted);">
                        <i class="fa-solid fa-vial-circle-check" style="font-size:30px; margin-bottom:10px; color:#cbd5e1;"></i><br>
                        No pending samples waiting for results.
                    </div>
                <?php else: ?>
                    <?php foreach($worklist as $item): ?>
                        <?php 
                            $p_class = 'prio-routine';
                            if($item['priority'] == 'Critical') $p_class = 'prio-critical';
                            if($item['priority'] == 'High') $p_class = 'prio-high';
                            
                            $isActive = ($target_request_id == $item['request_id']) ? 'active' : '';
                            $dateOnly = date('Y-m-d', strtotime($item['collected_at']));
                        ?>
                        <a href="?request_id=<?= $item['request_id'] ?>" 
                           class="queue-card <?= $isActive ?>" 
                           data-search="<?= strtolower($item['first_name'].' '.$item['last_name'].' '.$item['barcode'].' '.$item['test_name']) ?>"
                           data-dept="<?= htmlspecialchars($item['department']) ?>"
                           data-date="<?= $dateOnly ?>">
                            
                            <div class="qc-header">
                                <span class="qc-name"><?= htmlspecialchars($item['first_name'].' '.$item['last_name']) ?></span>
                                <span class="qc-priority <?= $p_class ?>"><?= htmlspecialchars($item['priority']) ?></span>
                            </div>
                            <div class="qc-test"><?= htmlspecialchars($item['test_name']) ?></div>
                            <div class="qc-meta">
                                <span><i class="fa-solid fa-barcode"></i> <?= htmlspecialchars($item['barcode'] ?? 'N/A') ?></span>
                                <span><?= date('h:i A', strtotime($item['collected_at'])) ?></span>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>

        <div class="right-pane">
            <?php if(empty($lab_test_data)): ?>
                <div style="height:100%; display:flex; flex-direction:column; justify-content:center; align-items:center; color:var(--text-muted); text-align:center;">
                    <i class="fa-solid fa-microscope" style="font-size:60px; color:#e2e8f0; margin-bottom:20px;"></i>
                    <h2>Result Entry Workbench</h2>
                    <p>Select a collected sample from the worklist queue on the left<br>to begin entering analytical results.</p>
                </div>
            <?php else: ?>
                <div class="wb-header">
                    <div class="wb-title"><?= htmlspecialchars($lab_test_data['test_name']) ?></div>
                    <div class="wb-subtitle">Assigned Bench: <?= htmlspecialchars($lab_test_data['department']) ?></div>
                </div>

                <div class="info-grid">
                    <div class="ig-item">
                        <span class="ig-label">Patient</span>
                        <span class="ig-value"><?= htmlspecialchars($lab_test_data['first_name'].' '.$lab_test_data['last_name']) ?> (<?= htmlspecialchars($lab_test_data['patient_no']) ?>)</span>
                    </div>
                    <div class="ig-item">
                        <span class="ig-label">Age / Gender</span>
                        <span class="ig-value"><?= $lab_test_data['age'] ?> Yrs / <?= htmlspecialchars($lab_test_data['gender']) ?></span>
                    </div>
                    <div class="ig-item">
                        <span class="ig-label">Sample Barcode</span>
                        <span class="ig-value"><i class="fa-solid fa-barcode" style="color:var(--brand-secondary);"></i> <?= htmlspecialchars($lab_test_data['sample_id']) ?></span>
                    </div>
                    <div class="ig-item">
                        <span class="ig-label">Requesting Physician</span>
                        <span class="ig-value"><?= htmlspecialchars($lab_test_data['doctor']) ?></span>
                    </div>
                </div>

                <?php if(!empty($lab_test_data['diagnosis_notes']) && $lab_test_data['diagnosis_notes'] !== 'No clinical notes provided.'): ?>
                    <div style="background:#fffbeb; border-left:4px solid #f59e0b; padding:12px 15px; border-radius:6px; margin-bottom:25px; font-size:13px; color:#854d0e;">
                        <strong><i class="fa-solid fa-user-doctor"></i> Clinical Notes:</strong> <?= htmlspecialchars($lab_test_data['diagnosis_notes']) ?>
                    </div>
                <?php endif; ?>

                <form method="POST" action="">
                    <input type="hidden" name="submit_results" value="1">
                    <input type="hidden" name="request_id" value="<?= $lab_test_data['request_id'] ?>">

                    <div style="font-size:16px; font-weight:800; color:var(--text-main); margin-bottom:15px; border-bottom:1px solid var(--border-light); padding-bottom:10px;">Analytical Parameters</div>
                    
                    <?php if(empty($parameters)): ?>
                        <div style="color:var(--danger); font-weight:bold; padding:20px; background:#fef2f2; border-radius:8px; border:1px solid #fecaca;">
                            <i class="fa-solid fa-triangle-exclamation"></i> Error: No analytical parameters are mapped to this test! Please configure the test in the mapping engine.
                        </div>
                    <?php else: ?>
                        <?php foreach($parameters as $param): ?>
                        <div class="parameter-row">
                            <div class="param-name">
                                <?= htmlspecialchars($param['parameter_name']) ?>
                                <span class="param-unit"><?= htmlspecialchars($param['unit_of_measure'] ?? '') ?></span>
                            </div>
                            
                            <div>
                                <?php if($param['result_type'] === 'Options'): ?>
                                    <select name="results[<?= $param['param_id'] ?>]" class="input-control" required>
                                        <option value="">-- Select Result --</option>
                                        <?php 
                                            $opts = explode(',', $param['options_list']);
                                            foreach($opts as $opt) echo "<option value='".trim($opt)."'>".trim($opt)."</option>"; 
                                        ?>
                                    </select>
                                <?php elseif($param['result_type'] === 'Numeric'): ?>
                                    <input type="number" step="0.01" name="results[<?= $param['param_id'] ?>]" class="input-control" required placeholder="Enter number...">
                                <?php else: ?>
                                    <input type="text" name="results[<?= $param['param_id'] ?>]" class="input-control" required placeholder="Enter text...">
                                <?php endif; ?>
                            </div>

                            <div>
                                <select name="flags[<?= $param['param_id'] ?>]" class="input-control" style="font-weight:600;">
                                    <?php foreach($dynamic_flags as $flag): ?>
                                        <option value="<?= htmlspecialchars($flag) ?>" <?= ($flag === 'Normal') ? 'selected' : '' ?>><?= htmlspecialchars($flag) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <?php if($param['result_type'] === 'Numeric'): ?>
                                    <?php $active_ref = $param['active_ref_range'] ?? 'No Range Set'; ?>
                                    <div class="param-ref" title="Age/Gender matched range">Ref: <?= htmlspecialchars($active_ref) ?></div>
                                    <input type="hidden" name="ref_ranges[<?= $param['param_id'] ?>]" value="<?= htmlspecialchars($active_ref) ?>">
                                <?php else: ?>
                                    <div style="color:var(--muted); font-size:12px; text-align:center;">N/A</div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                    <div style="margin-top:25px;">
                        <div style="font-size:14px; font-weight:700; color:var(--text-main); margin-bottom:10px;">Scientist Remarks / Conclusion</div>
                        <textarea name="scientist_remarks" class="input-control" rows="3" placeholder="Enter clinical interpretations, machine warnings, or final conclusions..."></textarea>
                    </div>

                    <div class="actions-bar">
                        <?php if(!empty($parameters)): ?>
                            <button type="submit" class="btn btn-primary" onclick="this.innerHTML='<i class=\'fa-solid fa-circle-notch fa-spin\'></i> Saving...';"><i class="fa-solid fa-check-double"></i> Submit Results for Verification</button>
                        <?php endif; ?>
                    </div>
                </form>
            <?php endif; ?>
        </div>
    </div>
  </div>
</div>

<script>
function filterQueue() {
    let searchTxt = document.getElementById('queueSearch').value.toLowerCase();
    let filterDate = document.getElementById('queueDate').value;
    let filterDept = document.getElementById('queueDept').value;
    
    let cards = document.querySelectorAll('.queue-card');
    
    cards.forEach(card => {
        let textData = card.getAttribute('data-search');
        let cardDept = card.getAttribute('data-dept');
        let cardDate = card.getAttribute('data-date');
        
        let matchSearch = textData.includes(searchTxt);
        let matchDept = (filterDept === 'ALL' || cardDept === filterDept);
        let matchDate = (filterDate === '' || cardDate === filterDate);
        
        if (matchSearch && matchDept && matchDate) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}
</script>

</body>
</html>