<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$test_id = $_GET['test_id'] ?? 0;
$msg = "";

// Handle Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $result_value = $_POST['result_value'];
    $reference_range = $_POST['reference_range'];
    $abnormal_flag = $_POST['abnormal_flag'];
    $interpretation = $_POST['interpretation'];

    // Determine status (Save as Draft or Complete)
    $status = isset($_POST['complete']) ? 'COMPLETED' : 'IN_PROGRESS';
    $completed_at = isset($_POST['complete']) ? date('Y-m-d H:i:s') : NULL;
    $started_at = date('Y-m-d H:i:s'); // Assuming we start now if not already

    // Check if previously started
    $check_sql = "SELECT started_at FROM lab_order_tests WHERE order_test_id = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("i", $test_id);
    $check_stmt->execute();
    $check = $check_stmt->get_result()->fetch_assoc();
    if ($check && $check['started_at']) {
        $started_at = $check['started_at'];
    }

    $sql = "UPDATE lab_order_tests SET 
            result_value = ?, reference_range = ?, abnormal_flag = ?, interpretation = ?,
            status = ?, started_at = ?, completed_at = ?, tested_by = ?
            WHERE order_test_id = ?";

    $stmt = $conn->prepare($sql);
    $user_id = $_SESSION['user_id'];
    $stmt->bind_param("sssssssii", $result_value, $reference_range, $abnormal_flag, $interpretation, $status, $started_at, $completed_at, $user_id, $test_id);

    if ($stmt->execute()) {
        if ($status == 'COMPLETED') {
            header("Location: view_test_results.php?test_id=" . $test_id);
            exit();
        } else {
            $msg = "Results saved as draft.";
        }
    } else {
        $msg = "Error: " . $conn->error;
    }
}

// Fetch Test Details
$sql = "SELECT t.*, tt.test_name, tt.test_code, tt.category, tt.normal_range,
               o.order_number, p.patient_number, u.full_name as patient_name,
               u.date_of_birth, u.gender
        FROM lab_order_tests t
        JOIN lab_orders o ON t.order_id = o.order_id
        JOIN patients p ON o.patient_id = p.patient_id
        JOIN users u ON p.user_id = u.user_id
        INNER JOIN ent_test_types tt ON t.test_type_id = tt.test_type_id
        WHERE t.order_test_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $test_id);
$stmt->execute();
$row = $stmt->get_result()->fetch_assoc();

if (!$row) {
    die("Test not found");
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Enter Test Results')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <div class="row">
                        <div class="col-lg-8 offset-lg-2">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Enter Results:
                                        <?php echo htmlspecialchars($row['test_name']); ?></h4>
                                </div>
                                <div class="card-body">

                                    <!-- Patient Info -->
                                    <div class="alert alert-light border">
                                        <strong>Patient:</strong>
                                        <?php echo htmlspecialchars($row['patient_name']); ?>
                                        (<?php echo htmlspecialchars($row['gender']); ?>)<br>
                                        <strong>Order #:</strong> <?php echo htmlspecialchars($row['order_number']); ?><br>
                                        <strong>Test:</strong> <?php echo htmlspecialchars($row['test_name']); ?> (<?php echo htmlspecialchars($row['test_code']); ?>)
                                        <?php if ($row['normal_range']): ?>
                                            <br><strong>Reference Range:</strong> <?php echo htmlspecialchars($row['normal_range']); ?>
                                        <?php endif; ?>
                                    </div>

                                    <?php if ($msg): ?>
                                        <div class="alert alert-info"><?php echo $msg; ?></div>
                                    <?php endif; ?>

                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Result Value</label>
                                            <textarea class="form-control" name="result_value" rows="4"
                                                required><?php echo htmlspecialchars($row['result_value'] ?? ''); ?></textarea>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Reference Range</label>
                                                <input type="text" class="form-control" name="reference_range"
                                                    value="<?php echo htmlspecialchars($row['reference_range'] ?? ''); ?>">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Abnormal Flag</label>
                                                <select class="form-select" name="abnormal_flag">
                                                    <option value="NORMAL" <?php echo $row['abnormal_flag'] == 'NORMAL' ? 'selected' : ''; ?>>Normal
                                                    </option>
                                                    <option value="LOW" <?php echo $row['abnormal_flag'] == 'LOW' ? 'selected' : ''; ?>>Low</option>
                                                    <option value="HIGH" <?php echo $row['abnormal_flag'] == 'HIGH' ? 'selected' : ''; ?>>High</option>
                                                    <option value="CRITICAL" <?php echo $row['abnormal_flag'] == 'CRITICAL' ? 'selected' : ''; ?>>Critical
                                                    </option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Interpretation / Notes</label>
                                            <textarea class="form-control" name="interpretation"
                                                rows="3"><?php echo htmlspecialchars($row['interpretation'] ?? ''); ?></textarea>
                                        </div>

                                        <div class="d-flex justify-content-between">
                                            <button type="submit" name="save_draft" class="btn btn-warning">Save Draft
                                                (In Progress)</button>
                                            <button type="submit" name="complete" class="btn btn-primary">Finalize
                                                Results</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>