<?php

define( "RIS_ENTERED_BY", "DCM" );
define( "RIS_IDEXAM", "11512" );
define( "RIS_PATIENT_CLASS", "2" );
define( "RIS_IDUNIT", "15" );
define( "RIS_IDWARD", "1666" );
define( "RIS_INTERNAL_STATUS", "4" );
define( "RIS_IDROOM", "202" );
define( "RIS_ID_INTEGR", "999" );
define( "RIS_NEW_SCORE", "2" );


function order_json ( $study, $dcm_import ){

    $oggi = date( "Y-m-d" );
    $ora = date( "H:i:s" );

    $adesso = "$oggi $ora";
    $v_numb = str_replace( ":", " ", str_replace("-", "", $adesso) );

    $order_json = '
    {
        "ORDER_DATE": "' . $adesso . '",
        "ID_ENTERING_ORGANIZATION": "' . RIS_IDWARD . '",
        "ENTERED_BY": "' . RIS_ENTERED_BY . '",
        "EMERGENCY": "",
        "REQUESTED_DATE": "%_REQUESTED_DATE_%",
        "REASONFORSTUDY": "%_REASONFORSTUDY_%",
        "TRANSACTION_DATE": "",
        "RELEVANT_CLINICAL_INFO": "",
        "SCORE": "0",
        "PLACERORDERNUMBER": "' . $v_numb . '",
        "ORDER_STATUS": "' . RIS_INTERNAL_STATUS . '",
        "VERIFIED_BY": null,
        "TRANSPORT_ARRANGED": null,
        "ORDERING_PROVIDER": "",
        "DANGER_CODE": "",
        "PDI_STATUS": "0",
        "PRIOR_PLACERORDERNUMBER": null,
        "PLACERORDERGROUPNUMBER": "",
        "NUM_RICETTA": null,
        "SCREENING": "0",
        "ANONYMOUS_CODE": null,
        "PRIVACY_CODE": "000",
        "ARCHIVE_NUM": null,
        "PESO": null,
        "ALTEZZA": null,
        "INTERNAL_STATUS": ' . RIS_INTERNAL_STATUS . ',
        "TRANSPORTATION_MODE": "WALK",
        "ADMISSION": {
            "PATIENT_CLASS": "' . RIS_PATIENT_CLASS . '",
            "IDUNIT": "' . RIS_IDUNIT . '",
            "ASSIGNED_PATIENT_LOCATION": "' . RIS_IDWARD .'",
            "IDWARD": "' . RIS_IDWARD .'",
            "IDPATIENT": "%_IDPATIENT_%",
            "VISIT_NUMBER": "' . $v_numb . '",
            "TRANSACTION_DATE": "' . $adesso . '",
            "ATTENDING_DOCTOR": "",
            "REFERRING_DOCTOR": "",
            "CONSULTING_DOCTOR": "",
            "ENTERING_ORGANIZATION": "' . RIS_IDWARD .'",
            "ADMITTING_DOCTOR": ""
        },
        "AGENDE_ROOMS": {
            "IDAGENDA": "IMPORT_DCM"
        },
        "FILLER": {
            "DATE_FILLER": "' . $oggi . '",
            "TIME_FILLER": "' . $ora . '",
            "IDPATIENT": "%_IDPATIENT_%",
            "STUDYINSUID": null,
            "SOP_INS_UID": null,
            "ACCESSION_NUMBER": "%_ACCESSION_NUMBER_%",
            "TECHNICAL_NOTES": null,
            "SCREENING": "",
            "SCREENING_NOTES": null
        },
        "PROCEDURES": [
            {
                "STATUS": "' . RIS_INTERNAL_STATUS . '",
                "EXAM_DATE": "%_REQUESTED_DATE_%",
                "IDROOM": "' . RIS_IDROOM . '",
                "ACCESS_NUMBER": "%_ACCESSION_NUMBER_%",
                "IDFILLER": "",
                "SPECIMEN_SOURCE": "",
                "ID_INTEGR": "' . RIS_ID_INTEGR . '",
                "ID_AGENDA_CUP": "",
                "STUDY_INST_UID": null,
                "IDAUTHENTICATOR": 0,
                "IDNURSE": null,
                "IDSECONDNURSE": 0,
                "IDTECHNICIAN": 0,
                "IDSECONDTECHNICIAN": 0,
                "IDCREATOR": 0,
                "IDEXAM": "' . RIS_IDEXAM . '"
            }
        ]
    }
    ';

    // aggiorno le info
    $order_json = str_replace( "%_REQUESTED_DATE_%", $study["study_time"], $order_json );
    $order_json = str_replace( "%_REASONFORSTUDY_%", $study["study_description"], $order_json );
    $order_json = str_replace( "%_ACCESSION_NUMBER_%", $study["accession_number"], $order_json );
    $order_json = str_replace( "%_IDPATIENT_%", $study["pat_id"], $order_json );

    return $order_json;
}


function create_ris_order( $study, $imp_id ){
    echo "<div style='border: 1px dotted; padding: 10px; margin-top: 10px; background-color: lightgray;'>";

    echoo( "RIS: Elaboro studio " . $study["id"] . " => " . $study["orthanc_id"] . "\n" );
    WriteLog( "Elaboro studio " . $study["id"] . " => " . $study["orthanc_id"], ris_logfile, "INFO" );
    
    $sql = "    SELECT 	*
                FROM 	public.dcm_imports di 
                WHERE 	id = $imp_id";
    $imp = query_select( $sql );

    $oj = order_json( $study, $imp[0] );

    $curl = curl_init();
    curl_setopt_array(
        $curl, 
        array(
            CURLOPT_URL => IMPORT_restar_url . '/order',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => $oj,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        )
    );
    $response = curl_exec($curl);
    curl_close($curl);

    WriteLog( "INSERIMENTO ORDINE", ris_logfile, "INFO" );
    $new_o = json_decode( $response, true );

    echoo( "INS. ORDER:" );
    echoo( $new_o, true );

    if( isset($new_o["IDORDER"]) && !IsNull($new_o["IDORDER"]) && $new_o["IDORDER"]>0 ){
        // ordine inserito
        WriteLog( "INSERITO ORDINE: " . $new_o["IDORDER"], ris_logfile, "INFO" );

        // cambio stato in "SIGNED"
        $url = IMPORT_sc_connector_url . '/sc_connector/index.php';
        $pst = '{
            "function": "SetNewStatus",
            "input_parameters": {
                "id_event": "' . $new_o["IDORDER"] . '",
                "type_event": "order_pk",
                "user_id": "' . $imp[0]["iduser"] . '",
                "new_status": "SIGNED",
                "new_score": ' . RIS_NEW_SCORE . ',
                "descr": "IMPORT STUDIO",
                "sync": false
            }
        }';

        $curl = curl_init();
        curl_setopt_array(
            $curl, 
            array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $pst,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json'
                ),
            )
        );

        $response = curl_exec( $curl );

        curl_close( $curl );

        echoo( "CAMBIO STATUS: $url<br>POST:$pst<br/>RESPONSE:$response <br/>" );
        WriteLog( "CAMBIO STATUS ORDINE: " . $new_o["IDORDER"] . "\n$url\n$pst\nResponse: $response\n", ris_logfile, "INFO" );
    }
    else {
        echoo( "ERRORE NELLA CREAZIONE DELL'ORDINE <br/>$response<br/>" );
        WriteLog( "ERRORE NELLA CREAZIONE DELL'ORDINE n$response\n", ris_logfile, "INFO" );        
    }

    echo "</div>";
}




function create_ris_order_from_study( $study ){
    echo "<div style='border: 1px dotted; padding: 10px; margin-top: 10px; background-color: lightgray;'>";

    echoo( "Elaboro " . study["id"] . " => " . $study["orthanc_id"] . "   => " . $study["job_id"] . "\n" );
    WriteLog( "Elaboro " . $study["id"] . " => " . $study["orthanc_id"] . "  =>  " . $study["job_id"], ris_logfile, "INFO" );
    
    $sql = "    SELECT 	distinct(fk_import) as fki
                FROM 	public.dcm_imports di 
                        INNER JOIN public.dcm_imports_instances dii ON dii.fk_import = di.id 
                WHERE 	dii.parent_study = '" . study["orthanc_id"] .  "'  ";
    //echo "$sql<br/>";
    $sts = query_select( $sql );

    if ( isset($sts[0]['fki']) && !IsNull($sts[0]['fki'])  ) {
        $sql = "    SELECT 	*
                    FROM 	public.dcm_imports di 
                    WHERE 	id = " . $sts[0]['fki'];
        $imp = query_select( $sql );

        //echo "<pre>STUDY:", var_dump(study), "<br/>IMPORT:", var_dump($imp[0]), "</pre>";

        $oj = order_json( $study, $imp[0] );

        $curl = curl_init();
        curl_setopt_array(
            $curl, 
            array(
                CURLOPT_URL => IMPORT_restar_url . '/order',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $oj,
                CURLOPT_HTTPHEADER => array(
                    'Content-Type: application/json'
                ),
            )
        );
        $response = curl_exec( $curl );
        curl_close($curl);

        WriteLog( "INSERIMENTO ORDINE", ris_logfile, "INFO" );
        $new_o = json_decode( $response, true );

        echoo( "INS. ORDER:" );
        echoo( $new_o, true );

        if( isset($new_o["IDORDER"]) && !IsNull($new_o["IDORDER"]) && $new_o["IDORDER"]>0 ){
            // ordine inserito
            WriteLog( "INSERITO ORDINE: " . $new_o["IDORDER"], ris_logfile, "INFO" );


            // cambio stato in "SIGNED"
            $url = IMPORT_sc_connector_url . '/sc_connector/index.php';
            $pst = '{
                "function": "SetNewStatus",
                "input_parameters": {
                    "id_event": "' . $new_o["IDORDER"] . '",
                    "type_event": "order_pk",
                    "user_id": "' . $imp[0]["iduser"] . '",
                    "new_status": "SIGNED",
                    "new_score": ' . RIS_NEW_SCORE . ',
                    "descr": "IMPORT STUDIO",
                    "sync": false
                }
            }';

            $curl = curl_init();
            curl_setopt_array(
                $curl, 
                array(
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 0,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => $pst,
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json'
                    ),
                )
            );
    
            $response = curl_exec( $curl );
    
            curl_close( $curl );

            echoo( "CAMBIO STATUS: $url<br>POST:$pst<br/>RESPONSE:$response <br/>" );
            WriteLog( "CAMBIO STATUS ORDINE: " . $new_o["IDORDER"] . "\n$url\n$pst\nResponse: $response\n", ris_logfile, "INFO" );
        }

 
    }
    echo "</div>";
}





