<?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 !== 'ACCEPT_INTO_LAB') {
        throw new Exception("Unknown action type.");
    }

    $stmtUpdate = $conn->prepare("
        UPDATE clinical_lab_requests 
        SET status = 'Awaiting Sample' 
        WHERE id = ? AND status = 'Pending'
    ");

    $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 (!$stmtUpdate || !$stmtAudit) {
        throw new Exception("System Error: Failed to prepare database statements.");
    }

    foreach ($requests as $req_id) {
        $req_id = intval($req_id);

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

        $audit_vals = json_encode(['status_changed_to' => 'Awaiting Sample', 'action' => 'Accepted at Reception']);
        $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' => 'Requests formally accepted.']);

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

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