<?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['samples'])) {
    echo json_encode(['status' => 'error', 'message' => 'No collection data received.']);
    exit;
}

$samples = $data['samples'];
$global_remarks = isset($data['overall_recommendation']) ? trim($data['overall_recommendation']) : '';

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

$conn->begin_transaction();

try {
    $stmtInsertCol = $conn->prepare("
        INSERT INTO clinical_sample_collections 
        (request_id, sample_id, barcode, collection_status, source, collection_notes, overall_recommendation) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    // FIXED: Must match 'Awaiting Sample' from the reception desk
    $stmtUpdateReq = $conn->prepare("
        UPDATE clinical_lab_requests 
        SET status = ? 
        WHERE id = ? AND status = 'Awaiting Sample'
    ");

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

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

    foreach ($samples as $sample) {
        $req_id = intval($sample['request_id']);
        $samp_id = intval($sample['sample_id']);
        $barcode = trim($sample['barcode']);
        $status = trim($sample['status']); 
        $source = trim($sample['source']);
        $notes = trim($sample['specific_notes']);

        $stmtInsertCol->bind_param("iisssss", $req_id, $samp_id, $barcode, $status, $source, $notes, $global_remarks);
        if (!$stmtInsertCol->execute()) {
            throw new Exception("Failed to save collection data for request ID: " . $req_id);
        }
        
        $collection_id = $conn->insert_id;

        $new_req_status = ($status === 'Collected') ? 'Sample Collected' : 'Collection Failed';
        $stmtUpdateReq->bind_param("si", $new_req_status, $req_id);
        if (!$stmtUpdateReq->execute()) {
            throw new Exception("Failed to update lab request status.");
        }

        $audit_vals = json_encode([
            'request_id' => $req_id,
            'barcode' => $barcode, 
            'collection_status' => $status
        ]);
        $rec_id_str = "COL-" . $collection_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' => 'Samples processed successfully.']);

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

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