<?php
session_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/rimax/application/dripend/includes/db.php';
header('Content-Type: application/json');

$json_input = file_get_contents("php://input");
$data = json_decode($json_input, true);

if (empty($data['tests']) || empty($data['patient_no'])) {
    echo json_encode(['status' => 'error', 'message' => 'No result data received.']);
    exit;
}

$patient_no = trim($data['patient_no']);
$tests = $data['tests'];

$staff_id = isset($_SESSION['staff_id']) ? intval($_SESSION['staff_id']) : 1;
$ip_addr = $_SERVER['REMOTE_ADDR'];

$conn->begin_transaction();

try {
    $stmtInsertRes = $conn->prepare("
        INSERT INTO clinical_lab_results 
        (request_id, parameter_id, result_value, reference_range_used, result_flag) 
        VALUES (?, ?, ?, ?, ?)
    ");

    $stmtUpdateReq = $conn->prepare("
        UPDATE clinical_lab_requests 
        SET status = 'Awaiting Verification', scientist_remarks = ?, completed_by = ?, completed_at = NOW()
        WHERE id = ? AND status = 'Sample Collected'
    ");

    $stmtAudit = $conn->prepare("
        INSERT INTO system_audit_logs 
        (staff_id, action_type, table_name, record_id, new_values, ip_address) 
        VALUES (?, 'UPDATE', 'clinical_lab_requests', ?, ?, ?)
    ");

    if (!$stmtInsertRes || !$stmtUpdateReq || !$stmtAudit) {
        throw new Exception("System Error: Failed to prepare database statements.");
    }

    foreach ($tests as $test) {
        $req_id = intval($test['request_id']);
        $remarks = trim($test['remarks']);
        
        foreach ($test['parameters'] as $param) {
            $param_id = intval($param['parameter_id']);
            $val = trim($param['value']);
            $ref = trim($param['reference']);
            $flag = trim($param['flag']);

            $stmtInsertRes->bind_param("iisss", $req_id, $param_id, $val, $ref, $flag);
            if (!$stmtInsertRes->execute()) {
                throw new Exception("Failed to save result for parameter ID: " . $param_id);
            }
        }

        $stmtUpdateReq->bind_param("sii", $remarks, $staff_id, $req_id);
        if (!$stmtUpdateReq->execute()) {
            throw new Exception("Failed to update lab request status to Awaiting Verification.");
        }

        $audit_vals = json_encode([
            'status_changed_to' => 'Awaiting Verification',
            'parameters_entered' => count($test['parameters'])
        ]);
        $rec_id_str = "LAB-REQ-" . $req_id;
        
        $stmtAudit->bind_param("isss", $staff_id, $rec_id_str, $audit_vals, $ip_addr);
        if (!$stmtAudit->execute()) {
            throw new Exception("Database failure while writing Audit Log.");
        }
    }

    $conn->commit();
    echo json_encode(['status' => 'success', 'message' => 'Results submitted successfully.']);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}

if(isset($stmtInsertRes)) $stmtInsertRes->close();
if(isset($stmtUpdateReq)) $stmtUpdateReq->close();
if(isset($stmtAudit)) $stmtAudit->close();
$conn->close();
?>