<?php


// Report all errors except E_NOTICE
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


include __DIR__ . "/conf/config.inc.php";
include __DIR__ . "/include/basic_function.php";
include __DIR__ . "/include/dcm_function.php";
include __DIR__ . "/include/ris_function.php";



// prendo quelli che hanno già finito il giro
$studies = query_select("   SELECT  *
                            FROM    dcm_study
                            WHERE   status = 9 
                            ORDER BY id ");


if ( !isset($studies[0]['id']) || IsNull($studies[0]['id']) ) {
    // NULLA DA elaborare
    WriteLog("NULLA DA ELABORARE", send_logfile, "INFO");
    die_proc("NULLA DA ELABORARE \n", $pid_name);
}


foreach ( $studies as $q_study ) {
    echo "<div style='border: 1px dotted; padding: 10px; margin-top: 10px; background-color: lightgray;'>";

    echoo( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "   => " . $q_study["job_id"] . "\n" );
    WriteLog( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "  =>  " . $q_study["job_id"], send_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 = '" . $q_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($q_study), "<br/>IMPORT:", var_dump($imp[0]), "</pre>";

        $oj = order_json( $q_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);

        $new_o = json_decode( $response, true );
        echo "INS. ORDER:<pre>", var_dump( $new_o ), "</pre><br/>";

        if( isset($new_o["IDORDER"]) && !IsNull($new_o["IDORDER"]) && $new_o["IDORDER"]>0 ){
            // ordine inserito
            // cambio stato in "SIGNED"
            $curl = curl_init();
            curl_setopt_array(
                $curl, 
                array(
                    CURLOPT_URL => IMPORT_sc_connector_url . '/sc_connector/index.php',
                    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 => '{
                        "function": "SetNewStatus",
                        "input_parameters": {
                            "id_event": "' . $new_o["IDORDER"] . '",
                            "type_event": "order_pk",
                            "user_id": "' . $imp[0]["iduser"] . '",
                            "new_status": "SIGNED",
                            "new_score": 0,
                            "descr": "IMPORT STUDIO",
                            "sync": false
                        }
                    }',
                    CURLOPT_HTTPHEADER => array(
                        'Content-Type: application/json'
                    ),
                )
            );
    
            $response = curl_exec($curl);
    
            curl_close($curl);
            echo "CAMBIO STATUS: $response <br/>";
        }

 
    }
    echo "</div>";
}


echoo("\n\n<hr>FINE ELABORAZIONE\n\n");


