<?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['action']) || empty($data['requests'])) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid payload. Missing action or requests.']);
    exit;
}

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

$conn->begin_transaction();

try {
    if ($action === 'VERIFY') {
        $stmtUpdate = $conn->prepare("
            UPDATE clinical_lab_requests 
            SET status = 'Completed', pathologist_remarks = ?, verified_by = ?, verified_at = NOW()
            WHERE id = ? AND status = 'Awaiting Verification'
        ");
    } elseif ($action === 'REJECT') {
        $stmtUpdate = $conn->prepare("
            UPDATE clinical_lab_requests 
            SET status = 'Sample Collected', pathologist_remarks = ?, reject_reason = 'Rejected at Verification', completed_by = NULL, completed_at = NULL
            WHERE id = ? AND status = 'Awaiting Verification'
        ");
        
        // If rejected, we must clear the scientist's erroneous results from the DB to allow re-entry
        $stmtClearRes = $conn->prepare("DELETE FROM clinical_lab_results WHERE request_id = ?");
    } else {
        throw new Exception("Unknown action type.");
    }

    $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', ?, ?, ?)
    ");

    foreach ($requests as $req) {
        $req_id = intval($req['request_id']);
        $remarks = trim($req['pathologist_remarks']);

        if ($action === 'VERIFY') {
            $stmtUpdate->bind_param("sii", $remarks, $staff_id, $req_id);
            $audit_msg = 'Result Verified and Released to EMR';
        } else {
            $stmtUpdate->bind_param("si", $remarks, $req_id);
            $stmtClearRes->bind_param("i", $req_id);
            if (!$stmtClearRes->execute()) {
                throw new Exception("Failed to clear erroneous results.");
            }
            $audit_msg = 'Result Rejected by Pathologist. Routed back to Scientist.';
        }

        if (!$stmtUpdate->execute()) {
            throw new Exception("Failed to update status for request ID: " . $req_id);
        }

        $audit_vals = json_encode(['action' => $action, 'pathologist_remarks' => $remarks, 'status_update' => $audit_msg]);
        $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' => 'Action completed successfully.']);

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

if(isset($stmtUpdate)) $stmtUpdate->close();
if(isset($stmtClearRes)) $stmtClearRes->close();
if(isset($stmtAudit)) $stmtAudit->close();
$conn->close();
?>