<?php
ob_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
include('includes/db.php');
include('includes/header.php');

/* ================= CSRF ================= */
if(empty($_SESSION['csrf_token'])){
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf = $_SESSION['csrf_token'];
/* ================= Auto Logout ================= */
$timeout_duration = 43200;

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}
/* ================= HELPER ================= */
function calculate_age($dob) {
    if (!$dob || $dob === '0000-00-00') {
        return '';
    }

    try {
        $dobDate = new DateTime($dob);
        $now     = new DateTime();
        $diff    = $now->diff($dobDate);

        // 1 year or more → years only
        if ($diff->y >= 1) {
            return $diff->y . ' Year' . ($diff->y > 1 ? 's' : '');
        }

        // Less than 1 year but at least 1 month → months only
        if ($diff->m >= 1) {
            return $diff->m . ' Month' . ($diff->m > 1 ? 's' : '');
        }

        // Less than 1 month → days
        return $diff->d . ' Day' . ($diff->d > 1 ? 's' : '');

    } catch (Exception $e) {
        return '';
    }
}


/* ================= Logged in user + facility ================= */
$user_id = $_SESSION['user_id'] ?? 0;
if(!$user_id) die("User not logged in");

$stmtUser = $pdo->prepare("SELECT username, facility_id FROM users WHERE id=?");
$stmtUser->execute([$user_id]);
$user = $stmtUser->fetch(PDO::FETCH_ASSOC);

$facility_id = $user['facility_id'] ?? 0;
$stmtFac = $pdo->prepare("SELECT * FROM facility WHERE id=?");
$stmtFac->execute([$facility_id]);
$facility = $stmtFac->fetch(PDO::FETCH_ASSOC);

/* ================= LAB ORDER ID ================= */
$lab_order_id = intval($_GET['id'] ?? 0);
if($lab_order_id <= 0) die("Invalid lab order ID");

/* ================= Fetch corresponding ticket ================= */
$stmt = $pdo->prepare("SELECT visit_ticket_id FROM lab_orders WHERE id=?");
$stmt->execute([$lab_order_id]);
$r = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$r) die("Lab order not found");

$ticket_id = $r['visit_ticket_id'];

/* ================= Patient & Visit ================= */
$stmt = $pdo->prepare("
SELECT vt.*, v.id AS visit_id, v.status AS visit_status, p.first_name, p.last_name, p.file_id, p.d_o_b, p.gender,
       u.username doctor_name
FROM visit_tickets vt
JOIN patients p ON p.id = vt.patient_id
LEFT JOIN visits v ON v.id = vt.visit_id
LEFT JOIN users u ON u.id = v.treated_by
WHERE vt.id = ?
");
$stmt->execute([$ticket_id]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

if(!$ticket) die("Ticket not found");

// 🔒 Check if visit is closed
$visit_closed = ($ticket['visit_status'] ?? '') === 'closed';

/* ================= Lab Orders ================= */
$q = $pdo->prepare("
SELECT lo.id lab_order_id, lo.result_value, lo.status,
       lt.lab_test_name, lt.sub_tests,
       lo.created_at
FROM lab_orders lo
JOIN products pr ON pr.id = lo.product_id
JOIN lab_test lt ON lt.id = pr.category_id
WHERE lo.visit_ticket_id = ?
ORDER BY lo.created_at DESC
");
$q->execute([$ticket_id]);
$labOrders = $q->fetchAll(PDO::FETCH_ASSOC);


/* ================= FINAL SAVE ================= */
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['final_data'])){
    if($visit_closed){
        // Block all edits if visit is closed
        $_SESSION['flash'] = ['message' => 'Cannot save results. Visit is closed.', 'color' => '#dc3545'];
        header("Location:view_lab_order.php?id=".$lab_order_id);
        exit;
    }

    if(!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])){
        die("Invalid CSRF");
    }

    $data = json_decode($_POST['final_data'], true);

    if($data){
        foreach($data as $labOrderId => $newResult){
            // Force edit or delete even if result is numeric
            $finalValue = null;

            if(is_array($newResult)){
                // Merge with existing JSON if array
                $stmt = $pdo->prepare("SELECT result_value FROM lab_orders WHERE id=?");
                $stmt->execute([$labOrderId]);
                $existing = json_decode($stmt->fetchColumn(), true) ?? [];
                $merged = array_merge($existing, $newResult);
                $finalValue = json_encode($merged);
            } else {
                // Use new result directly (numeric or string)
                $finalValue = $newResult !== '' ? $newResult : null;
            }

            $stmt = $pdo->prepare("
                UPDATE lab_orders
                SET result_value = ?, status = 'completed'
                WHERE id = ?
            ");
            $stmt->execute([$finalValue, $labOrderId]);
        }

        $_SESSION['flash'] = ['message' => 'Lab results saved successfully', 'color' => '#28a745'];
    } else {
        $_SESSION['flash'] = ['message' => 'No results submitted', 'color' => '#dc3545'];
    }

    header("Location:view_lab_order.php?id=".$lab_order_id);
    exit;
}
?>

<!-- ================= HTML + LAB TABLE ================= -->
<nav class="header-navbar navbar navbar-with-menu navbar-fixed-top navbar-semi-dark navbar-shadow">
    <?php include('includes/navbar.php'); ?>
</nav>

<div data-scroll-to-active="true" class="main-menu menu-fixed menu-dark menu-accordion menu-shadow">
    <?php include('includes/sidebar.php'); ?>
</div>

<div class="app-content content container-fluid">
    <div class="content-wrapper">

        <h4 class="text-center">Lab Results – Ticket #<?= $ticket_id ?></h4>

        <div class="card mb-2">
            <div class="card-body">
            <b>File:</b> <?= $ticket['file_id'] ?> |
            <b>Patient:</b> <?= $ticket['first_name'].' '.$ticket['last_name'] ?> |
            <b>Age:</b> <?= calculate_age($ticket['d_o_b']) ?> |
            <b>Gender:</b> <?= $ticket['gender'] ?>
            </div>
        </div>

        <div class="card">
            <div class="card-body table-responsive">
            <table class="table table-bordered">
    <thead>
        <tr>
            <th>#</th> <!-- Numbering column -->
            <th>Lab Test</th>
            <th>Result</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <?php 
        if (!empty($labOrders)):
            $counter = count($labOrders); // Start numbering from total
            foreach ($labOrders as $lo): 
                // FIXED: Check for null/empty before json_decode
                $subTestsJson = $lo['sub_tests'] ?? '';
                $hasSub = !empty($subTestsJson) && $subTestsJson !== 'null' && $subTestsJson !== '' && json_decode($subTestsJson, true); 
        ?>
        <tr>
            <td><?= $counter-- ?></td> <!-- Display counter, then decrement -->
            <td><?= htmlspecialchars($lo['lab_test_name']) ?></td>
            <td>
                <?php if($hasSub): ?>
                <button class="btn btn-primary btn-sm openModal"
                    data-id="<?= htmlspecialchars($lo['lab_order_id']) ?>"
                    data-sub='<?= htmlspecialchars($subTestsJson, ENT_QUOTES) ?>'
                    data-old='<?= htmlspecialchars($lo['result_value'] ?? '', ENT_QUOTES) ?>'>
                    Enter/View Sub Tests
                </button>
                <?php else: ?>
                <input type="text" 
                    class="form-control form-control-sm single-result" 
                    data-id="<?= htmlspecialchars($lo['lab_order_id']) ?>" 
                    value="<?= htmlspecialchars($lo['result_value'] ?? '') ?>" 
                    placeholder="Enter result">
                <?php endif; ?>
            </td>
            <td>
                <button class="btn btn-sm status-btn <?= $lo['status']=='completed' ? 'btn-success' : 'btn-warning' ?>" disabled>
                    <?= ucfirst($lo['status']) ?>
                </button>
            </td>
        </tr>
        <?php 
            endforeach; 
        else: 
        ?>
        <tr>
            <td colspan="4" class="text-center">No lab orders found</td>
        </tr>
        <?php endif; ?>
    </tbody>
</table>

            </div>
        </div>

        <form method="POST" id="finalForm">
            <input type="hidden" name="csrf_token" value="<?= $csrf ?>">
            <input type="hidden" name="final_data" id="finalData">

            <button class="btn btn-primary btn-block mt-2">Save All Results</button>
            <button type="button" onclick="window.print()" class="btn btn-secondary btn-block mt-1">🖨️ Print Lab Report</button>
        </form>
    </div>
</div>

<!-- ================= MODAL ================= -->
<div class="modal fade" id="labModal">
    <div class="modal-dialog modal-md">
        <div class="modal-content">
            <div class="modal-header">
                <h5>Sub Lab Tests</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="currentLab">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            <th>Test</th>
                            <th>Min</th>
                            <th>Max</th>
                            <th>Unit</th>
                            <th>Result</th>
                        </tr>
                    </thead>
                    <tbody id="modalBody"></tbody>
                </table>
            </div>
            <div class="modal-footer">
            <button class="btn btn-primary btn-sm" id="saveTemp">Save Sub Tests</button>
            </div>
        </div>
    </div>
</div>

<!-- ================= PRINTABLE REPORT ================= -->
<div id="print-area">
<h2 style="text-align:center;"><?= htmlspecialchars($facility['name']) ?></h2>
<p style="text-align:center;">
<?= htmlspecialchars($facility['street'].', '.$facility['sector'].', '.$facility['district'].', '.$facility['province']) ?><br>
Phone: <?= htmlspecialchars($facility['facility_phone']) ?>
</p>
<hr>
<h3 style="text-align:center;">LABORATORY REPORT</h3>

<table width="100%" style="margin-bottom:10px;">
<tr>
<td><b>File ID:</b> <?= $ticket['file_id'] ?></td>
<td><b>Patient:</b> <?= $ticket['first_name'].' '.$ticket['last_name'] ?></td>
</tr>
<tr>
<td><b>Age:</b> <?= calculate_age($ticket['d_o_b']) ?></td>
<td><b>Gender:</b> <?= $ticket['gender'] ?></td>
</tr>
<tr>
<td colspan="2"><b>Requested By:</b> <?= $ticket['doctor_name'] ?? 'N/A' ?></b></td>
</tr>
</table>

<table border="1" width="100%" cellpadding="6" cellspacing="0">
<thead>
<tr>
<th>Test</th>
<th>Min</th>
<th>Max</th>
<th>Unit</th>
<th>Result</th>
<th>Status</th>
</tr>
</thead>
<tbody>

<?php foreach($labOrders as $lo):
    // FIXED: Check for null/empty before json_decode
    $subTestsJson = $lo['sub_tests'] ?? '';
    $resultJson = $lo['result_value'] ?? '';
    
    $subs = (!empty($subTestsJson) && $subTestsJson !== 'null' && $subTestsJson !== '') ? json_decode($subTestsJson, true) : [];
    $res = (!empty($resultJson) && $resultJson !== 'null' && $resultJson !== '') ? json_decode($resultJson, true) : [];
?>
<?php if(!empty($subs)): ?>
<tr style="background:#f1f1f1;"><td colspan="6"><b><?= $lo['lab_test_name'] ?></b></td></tr>
<?php foreach($subs as $s):
$v = $res[$s['name']] ?? '';
$ok = is_numeric($v) && $v>=$s['min'] && $v<=$s['max'];
$statusText = is_numeric($v) ? ($ok ? 'Normal' : 'Abnormal') : '';
?>
<tr>
<td><?= $s['name'] ?></td>
<td><?= $s['min'] ?></td>
<td><?= $s['max'] ?></td>
<td><?= $s['unit'] ?? '' ?></td>
<td><?= htmlspecialchars($v) ?></td>
<td style="color:<?= $ok?'green':'red' ?>"><?= htmlspecialchars($statusText) ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td><?= $lo['lab_test_name'] ?></td>
<td>-</td>
<td>-</td>
<td>-</td>
<td><?= htmlspecialchars($lo['result_value'] ?? '') ?></td>
<td>
<button class="btn btn-sm <?= $lo['status']=='completed'?'btn-success':'btn-warning' ?>" disabled>
<?= ucfirst($lo['status']) ?>
</button>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>

<p style="margin-top:20px;">
<b>Facility:</b> <?= htmlspecialchars($facility['name']) ?><br>
<b>Lab Technician:</b> <?= htmlspecialchars($user['username']) ?><br>
<?php 
$visitDate = !empty($labOrders[0]['created_at']) ? date('d/m/Y', strtotime($labOrders[0]['created_at'])) : '';
?>
<b>Date:</b> <?= htmlspecialchars($visitDate) ?>

</p>
</div>

<style>
#print-area{display:none;}
@media print{
body *{visibility:hidden;}
#print-area,#print-area *{visibility:visible;}
#print-area{display:block;position:absolute;left:0;top:0;width:100%;}
button, nav, .main-menu{display:none!important;}
table{border-collapse:collapse;font-size:12px;}
th{background:#eee;}
}
.modal-dialog.modal-md{max-width:600px;}
.form-control-sm{height:32px;font-size:12px;padding:4px;}
</style>

<script>
let allResults = {};

// ================= MODAL SUB-TESTS =================
document.addEventListener('DOMContentLoaded', function() {
    // Attach click handlers to modal buttons
    document.querySelectorAll('.openModal').forEach(btn => {
        btn.onclick = function() {
            let lab = this.dataset.id;
            let subs = [];
            let old = {};
            
            try {
                // Handle empty/null JSON strings
                let subData = this.dataset.sub || '[]';
                let oldData = this.dataset.old || '{}';
                
                if (subData && subData !== 'null' && subData.trim() !== '') {
                    subs = JSON.parse(subData);
                }
                
                if (oldData && oldData !== 'null' && oldData.trim() !== '') {
                    old = JSON.parse(oldData);
                }
            } catch (e) {
                console.error('Error parsing JSON:', e);
                subs = [];
                old = {};
            }

            if(allResults[lab] && typeof allResults[lab] === 'object'){
                old = {...old, ...allResults[lab]};
            }

            document.getElementById('currentLab').value = lab;

            let h = '';
            if (subs && Array.isArray(subs)) {
                subs.forEach(s => {
                    let val = old[s.name] ?? '';
                    h += `<tr>
<td>${s.name}</td>
<td>${s.min}</td>
<td>${s.max}</td>
<td>${s.unit || ''}</td>
<td>
<input type="text" class="form-control form-control-sm res"
data-name="${s.name}" data-min="${s.min}" data-max="${s.max}" value="${val}">
</td>
</tr>`;
                });
            }

            document.getElementById('modalBody').innerHTML = h;
            
            // Show modal using Bootstrap
            if (typeof jQuery !== 'undefined' && jQuery.fn.modal) {
                jQuery('#labModal').modal('show');
            } else {
                // Fallback: manually show modal
                document.getElementById('labModal').style.display = 'block';
                document.getElementById('labModal').classList.add('show');
                document.body.classList.add('modal-open');
            }
            
            // Add colorization to inputs
            setTimeout(colorize, 100);
        };
    });

    // ================= COLORIZE MODAL =================
    function colorize() {
        document.querySelectorAll('.res').forEach(i => {
            let val = i.value.trim();
            let v = parseFloat(val);
            let min = parseFloat(i.dataset.min);
            let max = parseFloat(i.dataset.max);

            if (val === '') {
                i.style.background = '';
            } else if (!isNaN(v)) {
                i.style.background = (v >= min && v <= max) ? '#d4edda' : '#f8d7da';
            } else {
                i.style.background = '';
            }
        });
    }

    // Listen for input in modal
    document.addEventListener('input', function(e) {
        if (e.target.classList.contains('res')) {
            colorize();
        }
    });

    // ================= SAVE SUB =================
    document.getElementById('saveTemp').onclick = function() {
        let lab = document.getElementById('currentLab').value;
        allResults[lab] = {};
        let abnormal = false;

        document.querySelectorAll('.res').forEach(i => {
            let val = i.value.trim();
            allResults[lab][i.dataset.name] = val;

            let v = parseFloat(val);
            let min = parseFloat(i.dataset.min);
            let max = parseFloat(i.dataset.max);

            if (!isNaN(v) && (v < min || v > max)) {
                abnormal = true;
                i.style.border = '2px solid red';
            } else {
                i.style.border = '';
            }
        });

        // Hide modal
        if (typeof jQuery !== 'undefined' && jQuery.fn.modal) {
            jQuery('#labModal').modal('hide');
        } else {
            // Fallback: manually hide modal
            document.getElementById('labModal').style.display = 'none';
            document.getElementById('labModal').classList.remove('show');
            document.body.classList.remove('modal-open');
        }
        
        updateStatusButton(lab, abnormal);
    };

    // ================= INLINE TEXT INPUT =================
    document.querySelectorAll('.single-result').forEach(i => {
        i.onchange = function() {
            allResults[this.dataset.id] = this.value.trim();
            updateStatusButton(this.dataset.id, false);
        };
    });

    // ================= FINAL FORM =================
    document.getElementById('finalForm').onsubmit = function(e) {
        e.preventDefault();
        document.getElementById('finalData').value = JSON.stringify(allResults);
        this.submit();
    };

    // ================= LIVE STATUS UPDATE =================
    function updateStatusButton(labId, abnormal = false) {
        let row = document.querySelector(`.single-result[data-id='${labId}']`)?.closest('tr');
        if (!row) row = document.querySelector(`.openModal[data-id='${labId}']`)?.closest('tr');
        if (!row) return;

        let btn = row.querySelector('button.status-btn');
        if (!btn) {
            btn = document.createElement('button');
            btn.className = 'btn btn-sm status-btn';
            btn.disabled = true;
            row.cells[3].appendChild(btn); // Status column is 3
        }

        btn.classList.remove('btn-success', 'btn-warning', 'btn-danger');

        if (abnormal) {
            btn.classList.add('btn-danger');
            btn.textContent = 'Abnormal';
        } else {
            btn.classList.add('btn-success');
            btn.textContent = 'Completed';
        }
    }
});

// Flash message
<?php if(isset($_SESSION['flash'])): ?>
document.addEventListener('DOMContentLoaded', function() {
    alert("<?= addslashes($_SESSION['flash']['message']) ?>");
});
<?php unset($_SESSION['flash']); endif; ?>
</script>

<?php include('includes/footer.php'); ?>