<?php

namespace App\Services;

use Carbon\Carbon;
use App\ResultSample;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

use Exception;
use App\DataListiner;
use App\Periksa; 
use App\RekapAntibiotik;
use App\PendaftaranOnListiner;

// Proses untuk Growth and Detection Result
function processGrowthDetectionResult($rawData){
    // Format: R|1| ^ ^ ^GND_MGIT^430100001234|INST_POSITIVE ^87| ...
    $resultData = explode('|', $rawData);

    return [
        'test_type'         => 'Growth/Detection',
        'accession_number'  => $resultData[2],
        'status'            => $resultData[3], // Positif atau Negatif
        'completion_time'   => $resultData[7]
    ];
}
// Proses untuk Isolate Result
function processIsolateResult($rawData){
    $resultData = explode('|', $rawData);
    return [
        'test_type'         => 'Isolate',
        'isolate_result'    => $resultData[3] ?? null,
        'antibiotic'        => $resultData[4] ?? null,
        'value'             => $resultData[5] ?? null,
        'status'            => $resultData[6] ?? null,
        'completion_time'   => $resultData[10] ?? null
    ];
}
// Proses untuk Other Test Result
function processOtherResult($rawData){
    // Format: R|1| ^ ^ ^OTHER^Seq123|Complete| ...
    $resultData = explode('|', $rawData);

    return [
        'test_type'         => 'Other',
        'sequence_number'   => $resultData[3],
        'result'            => $resultData[4],
        'description'       => $resultData[5],
        'completion_time'   => $resultData[6]
    ];
}

class AstmMessageService
{
    /**
     * Membersihkan string dari karakter non-printable
     */
    private function cleanString($string)
    {
        return preg_replace('/[^\x20-\x7E|]+/', '', $string);
    }

    /**
     * Parsing data berdasarkan format yang diberikan
     */
    private function parseResultData($rawData, $format)
    {
        $resultData = explode('|', $rawData);
        $parsedData = [];

        foreach ($format as $key => $index) {
            $parsedData[$key] = $resultData[$index] ?? null;
        }

        return $parsedData;
    }
    /**
     * Proses hasil AST Record
     */
    public function processAstResult($rawData)
    {
        $format = [
            'test_type' => 0,
            'accession_number' => 2,
            'antibiotic' => 3,
            'susceptibility' => 4,
            'value' => 5,
            'status' => 6,
            'completion_time' => 10
        ];

        return $this->parseResultData($rawData, $format);
    }
    /**
     * Proses hasil ID Record
     */
    public function processIdResult($rawData)
    {
        $format = [
            'test_type'         => 0,
            'accession_number'  => 2,
            'organism_name'     => 3,
            'status'            => 6,
            'completion_time'   => 10
        ];

        return $this->parseResultData($rawData, $format);
    }
    public function createHeader($senderName, $versionNumber)
    {
        $messageDateTime = Carbon::now()->format('YmdHis');
        return "H|{$senderName}|{$versionNumber}|{$messageDateTime}";
    }

    // Fungsi untuk membuat Patient Record (P)
    public function createPatientRecord($patient)
    {
        // Extract fields from $patient array, adjust field positions based on mapping
        return "P|{$patient['id']}|{$patient['last_name']}|{$patient['first_name']}|{$patient['middle_name']}|{$patient['suffix']}|{$patient['dob']}|{$patient['sex']}|{$patient['address']}||{$patient['phone']}|{$patient['admitting_physician']}";
    }

    // Fungsi untuk membuat Order Record (O)
    public function createOrderRecord($order)
    {
        // Order fields based on mapping (Accession Number, Test ID, etc.)
        return "O|{$order['accession_number']}|{$order['isolate_number']}|{$order['organism']}|{$order['exclude_isolate']}|{$order['priority']}|{$order['collection_date_time']}|{$order['collected_by']}|{$order['received_by']}|{$order['specimen_action_code']}|{$order['isolate_source_test']}|{$order['isolate_source_test_start_time']}|{$order['receipt_date_time']}|{$order['specimen_type']}|{$order['body_site']}|{$order['ordering_physician']}|{$order['ordering_physician_phone']}|{$order['ordering_physician_fax']}|{$order['ordering_physician_pager']}|{$order['specimen_user_field_1']}|{$order['specimen_user_field_2']}|{$order['specimen_user_field_3']}|{$order['specimen_user_field_4']}|{$order['specimen_user_field_5']}|{$order['finalized_date_time']}|{$order['specimen_reimbursement_value']}|{$order['test_reimbursement_value']}|{$order['isolate_classification']}";    }
    public function createTerminatorRecord($order)
    {
        // Order fields based on mapping (Accession Number, Test ID, etc.)
        return "L|1|N";
    }
    // Fungsi untuk membuat pesan lengkap (header + patient + order)
    public function createMessage($senderName, $versionNumber, $patient, $order)
    {
        $header         = $this->createHeader($senderName, $versionNumber);
        $patientRecord  = $this->createPatientRecord($patient);
        $orderRecord    = $this->createOrderRecord($order);
        $terimatorRecord= $this->createTerminatorRecord($order);
        return implode("\n", [$header, $patientRecord, $orderRecord, $terimatorRecord]);
    }

    /**
     * Proses data ASTM Response
     */
    public function processAstmResponse($response, $alat) {
        // Bersihkan data
        $astmData = $this->cleanString($response);
        // Validasi awal: response tidak kosong
        if (empty($astmData)) {
            Log::error("ASTM data kosong atau tidak valid.");
        }
        $jsonantibiotik = array(
				'Oxacillin-OX',
				'Cefoxitin-FOX',
				'Benzylpenicillin-P',
				'Ampicillin-AM',
				'Azithromycin-AZM',
				'Erythromycin-ERY',
				'Cefazolin-CZO',
				'Cefepime-FEP',
				'Cefixime-CFM',
				'Cefotaxime-CTX',
				'Cefuroxime-CXM',
				'Ceftazidime-CAZ',
				'Ceftriaxone-CRO',
				'Ceftazidime/Avibactam-CZA',
				'Piperacilin/Tazobactam-TZP',
				'Ampicillin/Sulbactam-SAM',
				'Amoxicillin/Clavulanate-AMC',
				'Cefoperazon/Sulbactam-SCF',
				'Aztreonam-ATM',
				'Ceftaroline-CPT',
				'Ciprofloxacin-CIP',
				'Levofloxacin-LEV',
				'Moxifloxacin-MFX',
				'Clindamycin-CLI',
				'Colistin-CS',
				'Tetracyclin-TCY',
				'Tigecycline-TGC',
				'Gentamicin-GM',
				'Amikacin-AN',
				'Meropenem-MEM',
				'Imipenem-IPM',
				'Doripenem-DOR',
				'Ertapenem-ETP',
				'Minocycline-MNO',
				'Doxycycline-DOX',
				'Spectinomycin-SPT',
				'Tigecycline-TGC',
				'Trimethoprim/Sulfamethoxazole-SXT',
				'Fosfomycin-FOS',
				'Vancomycin-VAN',
				'Linezolid-LNZ',
				'Fluconazole',
				'Voriconazole',
				'Caspofungin',
				'Micafungin',
				'Amphotericin B',
				'Flucytosine'
			);
        $headerData         = [];
        $patientData        = [];
        $orderData          = [];
        $resultData         = [];
        $instrumenDT        = [];
        $mltrData           = [];
        $isolate            = null;
        $accession_number   = null;
        $segments           = explode("\n", $astmData);
        foreach ($segments as $rsegmen){
            $cekdata        = explode('|', $rsegmen);
            $datapertama    = $cekdata[0];
            $cleankode      = preg_replace("/[^a-zA-Z]/", "", $datapertama);
            if ($cleankode == 'H'){
                $headerData = array_merge([$cleankode], array_slice($cekdata, 1));
            }
            if ($cleankode == 'P'){
                $patientData = array_merge([$cleankode], array_slice($cekdata, 1));
            }
            if ($cleankode == 'O'){
                $orderData = array_merge([$cleankode], array_slice($cekdata, 1));
            }
            if ($cleankode == 'R'){
                $resultData = array_merge([$cleankode], array_slice($cekdata, 1));
            }
            if ($cleankode == 'I'){
                $instrumenDT = array_merge([$cleankode], array_slice($cekdata, 1));
            }
            if ($cleankode == 'mtrsl'){
                $mltrData = array_merge([$cleankode], array_slice($cekdata, 1));
            }
        }
        if (!empty($patientData) && !empty($headerData)) {
            $resultSample                                   = new ResultSample();
            $noregister                                     = $patientData[4] ?? null;
            $resultSample->sender_name                      = $alat;
            $resultSample->version_number                   = $headerData[11] ?? $patientData[12] ?? null;
            $resultSample->message_datetime                 = $resultData[13] ?? null; // '20241130152734'
            // Patient Record (Segment P)
            $resultSample->patient_id                       = $patientData[4] ?? null; // '11607396'
            $resultSample->patient_name_last                = $patientData[6] ?? null; // 'ZAKIYATUN'
            $resultSample->patient_name_first               = $patientData[7] ?? null; // 'O'
            $resultSample->patient_name_middle              = $patientData[8] ?? null;
            $resultSample->patient_name_suffix              = $patientData[9] ?? null;
            $resultSample->patient_name_title               = $patientData[10] ?? null;
            $resultSample->patient_dob                      = $resultData[11] ?? null; // '19800101'
            $resultSample->patient_sex                      = $patientData[12] ?? null; // 'F'
            $resultSample->address_street                   = $patientData[13] ?? null; // 'Street ABC'
            $resultSample->address_city                     = $patientData[14] ?? null;
            $resultSample->address_state                    = $patientData[15] ?? null;
            $resultSample->address_zip                      = $patientData[16] ?? null;
            $resultSample->address_country                  = $patientData[17] ?? null;
            $resultSample->patient_phone                    = $patientData[18] ?? null; // '081234567890'

            // Order Record (Segment O)
            $resultSample->accession_number                 = $orderData[4] ?? null; // '12345'
            $resultSample->isolate_number                   = $orderData[5] ?? null; // '67890'
            $resultSample->organism                         = $orderData[6] ?? null; // 'E. coli'
            $resultSample->exclude_isolate_from_statistics  = $isolate; // 'false'
            $resultSample->test_id                          = $orderData[8] ?? null; // 'Test123'

            // Result Record (Segment R)
            $resultSample->result_type_code                 = $resultData[4] ?? null; // 'S'
            $resultSample->antibiotic                       = $resultData[5] ?? null; // 'Amoxicillin'
            $resultSample->antibiotic_concentration         = $resultData[6] ?? null; // '100mg'
            $resultSample->antibiotic_concentration_units   = $resultData[7] ?? null; // 'mg'
            $resultSample->test_status                      = $resultData[8] ?? null; // 'Completed'
            $resultSample->result_data                      = json_encode(array_slice($resultData, 9)); // Additional data (if any)

            $resultSample->preliminary_final_status         = $resultData[13] ?? null;
            $resultSample->test_start_datetime              = $resultData[14] ?? null;
            $resultSample->result_status_datetime           = $resultData[15] ?? null;
            $resultSample->test_complete_datetime           = $resultData[16] ?? null;
            // Periksa apakah data duplikat berdasarkan accession_number
            //if (ResultSample::where('accession_number', $resultSample->accession_number)->exists()) {
            //    return response()->json(['message' => 'Data sudah ada.'], 409);
            //}

            // Simpan ke database
            if ($noregister){
                Periksa::where('nofoto', $accession_number)->update([
                    'status' => 'Data Vitek di Terima',
                ]);
                Log::info("Data berhasil disimpan:", $resultSample->toArray());
                $resultSample->save();
            }
            return response()->json(['message' => 'Data berhasil diproses dan disimpan.']);
            
        } else {
            if (!empty($mltrData)){
                $mulaikirim                 = 0;
                $tanggalmasuk               = '';
                $tanggalkeluar              = '';
                $parsedData = [
                    'patient_info' => [],
                    'antibiotics' => []
                ];
                $resultSample               = new ResultSample();
                for ($i = 0; $i < count($mltrData); $i++) {
                    $field = $mltrData[$i];
                    $kodeduadigit = substr($field, 0, 2);
                                
                    if ($field == 'ra') {
                        $current_antibiotic = [];
                        for ($j = 1; $j <= 5; $j++) {
                            if (isset($mltrData[$i + $j])) {
                                $subField = $mltrData[$i + $j];
                                $code = substr($subField, 0, 2);
                                $value = substr($subField, 2);

                                switch ($code) {
                                    case 'a1':
                                        $current_antibiotic['instrument_code'] = $value; // Kode dari alat
                                        break;
                                    case 'a2':
                                        $current_antibiotic['antibiotic_name'] = $value; // Nama antibiotik
                                        break;
                                    case 'a3':
                                        $current_antibiotic['value'] = $value; // Nilai MIC
                                        break;
                                    case 'a4':
                                        $current_antibiotic['interpretation'] = $value; // S, I, atau R
                                        break;
                                    case 'an':
                                        $current_antibiotic['resistance_note'] = $value; // Catatan resistansi
                                        break;
                                }
                            }
                        }
                        $antibioticName = $current_antibiotic['antibiotic_name'] ?? null;
                        if ($antibioticName && isset($kodevitek[$antibioticName])) {
                            $current_antibiotic['lis_code'] = $kodevitek[$antibioticName];
                        } else {
                            $current_antibiotic['lis_code'] = $current_antibiotic['instrument_code'] ?? 'NOT_FOUND';
                        }
                        $parsedData['antibiotics'][] = $current_antibiotic;
                        $i += 5;
                    } else {
                        if ($kodeduadigit == 'mt'){
                            $resultSample->sender_name =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'ii'){
                            $resultSample->version_number =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'rr'){
                            $resultSample->isolate_number =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'ci'){
                            $accession_number               = substr($field, 2);
                            $resultSample->accession_number = $accession_number;
                        }
                        if ($kodeduadigit == 'pi'){
                            $resultSample->patient_id       =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'pn'){
                            $patientNames   = substr($field, 2);
                            $patientNames   = explode(',', $patientNames ?? null);
                            if (count($patientNames) > 0) {
                                $resultSample->patient_name_first = trim($patientNames[0]);
                            }
                            if (count($patientNames) > 1) {
                                $resultSample->patient_name_last = trim($patientNames[1]);
                            }
                            if (count($patientNames) > 2) {
                                $resultSample->patient_name_middle = trim($patientNames[2]);
                            }
                        }
                        
                        if ($kodeduadigit == 'pl'){
                            $resultSample->hospital_service =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'p2'){
                            $resultSample->hospital_client  =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'ss'){
                            $resultSample->specimen_type    =  substr($field, 2);
                        }
                        if ($kodeduadigit == 'o2'){
                            $resultSample->organism         =  substr($field, 2);
                        }
                        if ($kodeduadigit == 's1'){
                            $tanggalmasuk                   =  substr($field, 2);
                        }
                        if ($kodeduadigit == 's2'){
                            $tanggalmasuk                   =  $tanggalmasuk.' '.substr($field, 2);
                        }
                        if ($kodeduadigit == 's3'){
                            $tanggalkeluar                  =  substr($field, 2);
                        }
                        if ($kodeduadigit == 's4'){
                            $tanggalkeluar                  =  $tanggalkeluar.' '.substr($field, 2);
                        }
                    }
                }
                $resultSample->additional_result    = json_encode($parsedData['antibiotics']);
                if ($tanggalmasuk != ''){
                    try {
                        $resultSample->message_datetime       = Carbon::parse($tanggalmasuk)->format('Y-m-d H:i:s') ?? null;
                    }catch (Exception $e) {
                        $resultSample->message_datetime       = date('Y-m-d H:i:s');
                    }
                }
                if ($tanggalkeluar != ''){
                    try {
                        $resultSample->test_complete_datetime       = Carbon::parse($tanggalkeluar)->format('Y-m-d H:i:s') ?? null;
                    }catch (Exception $e) {
                        $resultSample->test_complete_datetime       = date('Y-m-d H:i:s');
                    }
                }
                $resultSample->save();
                if ($accession_number){
                    $accession_number   = substr($accession_number, 0, 9);
                    $getorderid         = Periksa::where('nofoto', $accession_number)->first();
                    $orderid            = $getorderid->id ?? null;
                    if ($orderid){
                        if(is_array($parsedData['antibiotics']) && count($parsedData['antibiotics']) > 0){
                            Log::info("Processing", $parsedData['antibiotics']);
                            foreach ($parsedData['antibiotics'] as $item){
                                $glassreportname = in_array($item['antibiotic_name'], $jsonantibiotik);
                                
                                RekapAntibiotik::updateOrCreate(
				                    [
                                        'orderid'			=> $orderid,
                                        'antibiotic'		=> $item['antibiotic_name'],
                                    ],
                                    [
                                        'resistance'		=> $item['resistance_note'] ?? null,
                                        'value'				=> $item['value'] ?? null,
                                        'interpretation'	=> $item['interpretation'] ?? null,
                                        'glassreportname'	=> $glassreportname,
                                        'created_at'		=> date('Y-m-d H:i:s'),
                                        'updated_at'		=> date('Y-m-d H:i:s'),
                                    ]
                                );
                            }
                        }
                        Periksa::where('nofoto', $accession_number)->update([
                            'status' => 'Data Vitek di Terima',
                        ]);
                    } else {
                        Log::warning("Accession Number Not Found", $accession_number.' Result Date '.$tanggalkeluar);
                    }
                }
                Log::info("Data MTRL Berhasil di Parse dan di simpan ", $resultSample->toArray());
                return response()->json(['message' => 'Data berhasil diproses dan disimpan.']);
            } else {    
                $headerData = explode("|", $astmData);
                if (isset($headerData[3])){
                    $accnumber                  = $headerData[47] ?? null;
                    $noregister                 = $headerData[16] ?? null;
                    $nama                       = $headerData[18] ?? null;
                    $urgensi                    = $headerData[50] ?? null; //A Critical R Normal
                    $iddokter                   = $headerData[33] ?? null;
                    $test_start_datetime        = $headerData[52] ?? null;
                    $result_status_datetime     = $headerData[59] ?? null;
                    $specimen_type              = $headerData[60] ?? null;
                    $resulttype                 = $headerData[34] ?? null;
                    $resultstatus               = $headerData[63] ?? null;
                    $preliminary                = $headerData[40] ?? null; //P
                    $test_complete_datetime     = $headerData[44] ?? null;
                    $tesid                      = $headerData[62] ?? null;
                    $alamat                     = $headerData[23] ?? null;
                    $instrumen                  = $resultData[2] ?? null;
                    $body_site                  = '';
                    $tengah                     = '';
                    $depan                      = '';
                    $akhir                      = '';
                    $suffix                     = '';
                    $title                      = '';
                    $concentration_unit         = '';
                    $kode                       = '';
                    $antibiotic                 = '';
                    $city                       = '';
                    $state                      = '';
                    $zipcode                    = '';
                    $country                    = '';
                    if ($resulttype){
                        $getdataresult          = explode('^', $resulttype);
                        $kode                   = $getdataresult[3] ?? '';
                        $concentration_unit     = $getdataresult[4] ?? '';
                    }
                    if ($specimen_type){
                        $getdata                = explode('\n', $specimen_type);
                        $specimen_type          = $getdata[0];
                        $body_site              = $getdata[1] ?? '';
                    }
                    if ($tesid){
                        $gettgl                 = explode('^', $tesid);
                        $tesid                  = $gettgl[3] ?? null;
                    }
                    if ($instrumen){
                        $gettgl                 = explode('^', $instrumen);
                        $instrumen              = $gettgl[0];
                        $media_assay_type       = $gettgl[1] ?? null;
                        $protocol_length        = $gettgl[2] ?? null;
                        $instrument_number      = $gettgl[3] ?? null;
                        $instrument_location    = $gettgl[4] ?? null;
                        $protocol_name          = $gettgl[5] ?? null;
                    } else {
                        $media_assay_type       = null;
                        $protocol_length        = null;
                        $instrument_number      = null;
                        $instrument_location    = null;
                        $protocol_name          = null;
                    }
                    if ($isolate == '' OR $isolate == '0' OR is_null($isolate)){
                        $isolate = false;
                    } else { $isolate = true; }
                    if ($test_complete_datetime){
                        $test_complete_datetime     = substr($test_complete_datetime, 0, 14);
                        //$test_complete_datetime     = Carbon::parse($test_complete_datetime)->format('Y-m-d H:i:s');
                    }
                    if ($result_status_datetime){
                        $result_status_datetime     = substr($result_status_datetime, 0, 14);
                        //$result_status_datetime     = Carbon::parse($result_status_datetime)->format('Y-m-d H:i:s');
                    }
                    if ($test_start_datetime){
                        $test_start_datetime        = substr($test_start_datetime, 0, 14);
                        //$test_start_datetime        = Carbon::parse($test_start_datetime)->format('Y-m-d H:i:s');
                    }
                    if ($nama){
                        $getnama    = explode('\015', $nama);
                        $nama       = $getnama[0];
                        $getnama    = explode('\n', $nama);
                        $nama       = $getnama[0];
                        
                        $akhir      = $getnama[1] ?? '';
                        $depan      = $getnama[2] ?? '';
                        $tengah     = $getnama[3] ?? '';
                        $suffix     = $getnama[4] ?? '';
                        $title      = $getnama[5] ?? '';
                        
                        $nama       = $nama.$akhir;
                    }
                    if ($alamat){
                        $getnama    = explode('^', $alamat);
                        $alamat     = $getnama[0];
                        $city       = $getnama[1] ?? '';
                        $state      = $getnama[2] ?? '';
                        $zipcode    = $getnama[3] ?? '';
                        $country    = $getnama[4] ?? '';
                    }
                    if ($test_start_datetime == ''){ $test_start_datetime = null; }
                    if ($result_status_datetime == ''){ $result_status_datetime = null; }
                    if ($test_complete_datetime == ''){ $test_complete_datetime = null; }
        
                    $resultSample->sender_name          = $headerData[4] ?? 'Unkown';
                    $resultSample->version_number       = $headerData[12] ?? 'V0.0';
                    $resultSample->message_datetime     = $test_start_datetime;
                    // Patient Record (Segment P)
                    $resultSample->patient_id           = $noregister; // '11607396'
                    $resultSample->patient_name_last    = $nama; // 'ZAKIYATUN'
                    $resultSample->patient_name_first   = $depan; // 'O'
                    $resultSample->patient_name_middle  = $tengah;
                    $resultSample->patient_name_suffix  = $suffix;
                    $resultSample->patient_name_title   = $title;
                    $resultSample->patient_dob          = $headerData[20] ?? null;
                    $resultSample->patient_sex          = $headerData[21] ?? null;
                    $resultSample->address_street       = $alamat;
                    $resultSample->address_city         = $city;
                    $resultSample->address_state        = $state;
                    $resultSample->address_zip          = $zipcode;
                    $resultSample->address_country      = $country;
                    $resultSample->patient_phone        = $headerData[25] ?? null;
                    $resultSample->admitting_physician  = $headerData[27] ?? null;
                    $resultSample->patient_diagnosis    = $headerData[33] ?? null;
                    $resultSample->patient_therapy      = json_encode($headerData);
                    $resultSample->admit_datetime       = null;
                    $resultSample->room_number          = $headerData[46] ?? '00001';
                    $resultSample->hospital_service     = $headerData[45] ?? 'RSSA Malang';
                    $resultSample->hospital_client      = $orderData[4] ?? 'Lab Mikro';
                    
                    // Order Record (Segment O)
                    $resultSample->accession_number                 = $accnumber; // '12345'
                    $resultSample->isolate_number                   = $orderData[5] ?? null; // '67890'
                    $resultSample->organism                         = $orderData[6] ?? null; // 'E. coli'
                    $resultSample->exclude_isolate_from_statistics  = $isolate; // 'false'
                    $resultSample->specimen_type                    = $specimen_type;
                    $resultSample->body_site                        = $body_site;
                    $resultSample->test_id                          = $tesid; // 'Test123'
                    $resultSample->urgensi                          = $urgensi; //A Critical R Normal
        
                    // Result Record (Segment R)
                    $resultSample->result_type_code                 = $kode;
                    $resultSample->antibiotic                       = $antibiotic;
                    $resultSample->antibiotic_concentration         = $concentration_unit; // '100mg'
                    $resultSample->antibiotic_concentration_units   = $concentration_unit; // 'mg'
                    $resultSample->test_status                      = $resultstatus; // 'Completed'
                    $resultSample->result_data                      = json_encode($orderData); // Additional data (if any)
                    
                    $resultSample->preliminary_final_status         = $preliminary;
                    $resultSample->test_start_datetime              = $test_start_datetime;
                    $resultSample->result_status_datetime           = $result_status_datetime;
                    $resultSample->test_complete_datetime           = $test_complete_datetime;
        
                    $resultSample->instrument_type                  = $instrumen;
                    $resultSample->media_assay_type                 = $media_assay_type;
                    $resultSample->protocol_length                  = $protocol_length;
                    $resultSample->instrument_number                = $instrument_number;
                    $resultSample->instrument_location              = $instrument_location;
                    $resultSample->protocol_name                    = $protocol_name;
                    $resultSample->additional_result                = json_encode($resultData);
                    if ($noregister){
                        $resultSample->save();
                        Log::info("Data ASTM Berhasil di Parse dan di simpan ", $resultSample->toArray());
                        return response()->json(['message' => 'Data berhasil diproses dan disimpan.']);
                    }
                } else {
                    Log::debug("Abaikan Data Berikut ". json_encode($headerData));
                }
            }
        }
    }
    /**
     * Proses data ASTM Response
     */
    public function processAstmMessages($dataListener) {
        foreach ($dataListener as $data) {
            try {
                // Ambil pesan ASTM dari kolom 'message' atau yang relevan
                $response = $data->rawdt;
                if ($data->alat == 'BD Mikro 1'){
                    if ($data->no_id != ''){
                        $rnmpas         = $data->rnmpas;
                        $getnama        = explode('|', $rnmpas);
                        $resultSample   = new ResultSample();
                        $resultSample->sender_name      = $data->alat;
                        $resultSample->message_datetime = $data->tgl_data;
                        $resultSample->version_number   = 'V1.0';
                        $resultSample->patient_id       = $data->urut;
                        $resultSample->patient_name_last= $getnama[0];
                        $resultSample->accession_number = $data->no_id;
                        $resultSample->test_status      = $data->organisme;
                        $resultSample->save();
                        DataListiner::where('urut', $data->urut)->update([
                            'processed' => 1
                        ]);
                        Periksa::where('nofoto', $data->no_id)->update([
                            'status' => 'Data BD di Terima',
                        ]);
                        Log::info("Data ASTM BD ", $resultSample->toArray());
                        PendaftaranOnListiner::where('rnoreg', $data->no_id)->update([
                            'rtglast'		=> date('Y-m-d'),
                            'flg_vitek1'	=> 0,
						    'flg_vitek2'	=> 0
                        ]);
                    } else {
                        DataListiner::where('urut', $data->urut)->update([
                            'processed' => 9
                        ]);
                    }
                } else {
                    // Lakukan parsing menggunakan method/fungsi yang sudah dibuat
                    $result = $this->processAstmResponse($response, $data->alat);
                    // Jika berhasil, tandai data sudah diproses
                    if ($result) {
                        DataListiner::where('urut', $data->urut)->update([
                            'processed' => 1
                        ]);
                    } else {
                        Log::debug($result);
                    }
                }
            } catch (\Exception $e) {
                Log::critical($e->getMessage());
            }
        }
    }
    public function processAstmMessagesLokal($dataListener) {
        foreach ($dataListener as $data) {
            try {
                // Ambil pesan ASTM dari kolom 'message' atau yang relevan
                $response = $data->rawdt;
                if ($data->alat == 'COM1' OR $data->alat == 'COM3'){
                    if (isset($data->no_id) AND $data->no_id != ''){
                        $rnmpas         = $data->rnmpas;
                        $getnama        = explode('|', $rnmpas);
                        $resultSample   = new ResultSample();
                        $resultSample->sender_name      = $data->alat;
                        $resultSample->message_datetime = $data->tgl_data;
                        $resultSample->version_number   = 'V1.0';
                        $resultSample->patient_id       = $data->seq_no;
                        $resultSample->patient_name_last= $getnama[0];
                        $resultSample->accession_number = $data->no_id;
                        $resultSample->test_status      = $data->organisme;
                        $resultSample->save();
                        DB::table('lis_phoenix')->where('id', $data->id)->update([
                            'processed' => 1
                        ]);
                        Periksa::where('nofoto', $data->no_id)->update([
                            'status' => 'Data BD di Terima',
                        ]);
                        Log::info("Data ASTM BD ", $resultSample->toArray());
                        PendaftaranOnListiner::where('rnoreg', $data->no_id)->update([
                            'rtglast'		=> date('Y-m-d'),
                            'flg_vitek1'	=> 0,
						    'flg_vitek2'	=> 0
                        ]);
                    } else {
                        DB::table('lis_phoenix')->where('id', $data->id)->update([
                            'processed' => 9
                        ]);
                    }
                } else {
                    // Lakukan parsing menggunakan method/fungsi yang sudah dibuat
                    $result = $this->processAstmResponse($response, $data->alat);
                    // Jika berhasil, tandai data sudah diproses
                    if ($result) {
                        DB::table('lis_phoenix')->where('id', $data->id)->update([
                            'processed' => 1
                        ]);
                    } else {
                        Log::debug($result);
                    }
                }
            } catch (\Exception $e) {
                Log::critical($e->getMessage());
            }
        }
    }
}
