<!DOCTYPE html>
<html lang="it">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">

        <!-- uikit -->
        <link href="include/uikit_theme/bower_components/uikit/css/uikit.almost-flat.min.css" rel="stylesheet" type="text/css"/>
       
        <!-- altair admin -->
        <link href="include/uikit_theme/assets/css/main.min.css" rel="stylesheet" type="text/css"/>
        
        <!-- themes -->
        <link href="include/uikit_theme/assets/css/themes/themes_combined.min.css" rel="stylesheet" type="text/css"/>

        <!-- Font awesome 5 -->
        <link href="include/uikit_theme/assets/icons/fontawesome-free-5/css/all.min.css" rel="stylesheet" type="text/css"/>
		  
		<!-- flag icons -->
		<link rel="stylesheet" href="include/uikit_theme/assets/icons/flags/flags.min.css" media="all">
        
        <title>RISULTATO IMPORT STUDIO DICOM</title>
       
        <!-- google web fonts (in locale) -->
        <script src="include/uikit_theme/assets/js/custom/webfont.js" type="text/javascript" async=""></script>
        <link href="include/uikit_theme/assets/css/webfontsStyles.css" rel="stylesheet" type="text/css"/>
        

        <!-- jQuery -->
        <script src="include/uikit_theme/bower_components/jquery/dist/jquery.min.js" type="text/javascript"></script>
        <script src="include/uikit_theme/bower_components/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
        <!-- common functions -->
        <script src="include/uikit_theme/assets/js/common.min.js" type="text/javascript"></script>
        <!-- uikit functions -->
        <script src="include/uikit_theme/assets/js/uikit_custom.min.js" type="text/javascript"></script>
        <!-- altair core functions -->
        <script src="include/uikit_theme/assets/js/altair_admin_common.min.js" type="text/javascript"></script>
        <!-- altair login page functions -->
        <script src="include/uikit_theme/assets/js/pages/login.min.js" type="text/javascript"></script>

        <link href="import.css" rel="stylesheet" type="text/css"/>

    </head>

<body style="padding-top: 0px !important;">

    <div style='margin-left: 1%; margin-right: 1%; width: 98%; height: 60px; background-color: #1976d2;'>
        <div style="float: left; height: 50px; width: 50%;">
            <img src="images/logo.png" alt="" height="50px">
            <span class="uk-badge uk-badge-success uk-text-upper">IMPORT STUDI DICOM ESTERNI</span>
        </div>
        <div style="float: right; height: 50px; border: 1px;">
            <!--div style="float: right; color: white; height: 50px; width: 70px;">
                <img style="height: 50px; margin-right: 20px; margin-top: 2px;" src="images/x-ray_worker.png" alt="" >
            </div-->
            <div style="float: right; color: white; height: 50px; vertical-align: middle; padding: 20px;">
                <span style='font-weight: bold;'><?= $_POST["list_name"]?></span>
            </div>
        </div>
    </div>

    <div style='margin-left: 1%; margin-right: 1%; lightgray; width: 98%;'  class='background_ris'>
    <div style='padding: 30px; width: 100%'>

    <span style="font-size: 1.3em; font-weight: bold;">RISULTATO DELL'IMPORT!</span>
    <br/>
    <br/>
<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 *
 * carica uno studio da file
 */


// 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";



$this_pid = __DIR__ . "/../cron_" . basename(__FILE__, ".php") . ".pid";
if (file_exists($this_pid)) {
    unlink($this_pid);
}

$pid_name = "import_studies";


$fk_import = -1;

$si = -1;
$user_id = -1;
$order_id = -1;
$patient_id = -1;

$pg_ok = false;

$descr = "";
$status = 0;

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ){
    //echo "POST<pre>", var_dump($_POST), "</pre>";


    $si = $_POST["si"];
    $user_id = $_POST["user_id"];
    $order_id = $_POST["order_id"];
    $patient_id = $_POST["patient_id"];
    $import_ids = $_POST["import_id"];

    if ( !isset($_POST["import_this"]) ){
        echo "NIENTE DA IMPORTARE!!<br/>" ;
        $import_this = "( '' ) ";
    }
    else {
        $import_this = "( '" . implode( "', '", $_POST["import_this"] ) . "' ) ";
    }
    

    $fk_import = $_POST["import_id"];

       
    if( isset($_POST["conferma_import"]) && $_POST["conferma_import"] == "CONFERMA STUDIO" && isset($_POST["import_this"]) ){
         // impostare IDPATIENT su orthanc
        //echo "<pre>", var_dump($_POST), "</pre>";

        $descr = "<img style='height: 50px; float: left;' src='images/ok.png'><span style='font-size: 1.2em; font-weight: bold; color: darkgreen; float: left;'>IMPORT CONFERMATO<br/>LO STUDIO SARA DISPONIBILE TRA QUALCHE MINUTO!!</span>";
        $status = 1;

        // echo "Chiamo il RIS per avere i dati dell'ordine<br/><br/>";
        
        $restar_cmd = IMPORT_restar_url . '/report/json?type=ORDER&identifier=' . $order_id;

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $restar_cmd,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
        ));
        $response = curl_exec($curl);

        curl_close($curl);
        //echo "$restar_cmd <br/>response: " . $response;
        $ordine = json_decode( $response, true );

        //echo "<pre>", var_dump( $ordine ), "</pre>";
        
        if( $ordine == null ){
            die( "NESSUNA CONNESSIONE AL SERVER RIS!!" );
            WriteLog( "NESSUNA CONNESSIONE AL SERVER RIS!!<br/>$restar_cmd ", import_logfile, "ERROR" );
        }
        $pt_name = $ordine["PATIENT"]["FAMILY_NAME"] . "^" . $ordine["PATIENT"]["GIVEN_NAME"];
        $pt_dob = str_replace( "-", "", substr( $ordine["PATIENT"]["DOB"], 0, 10 ) );
        $pt_sex = $ordine["PATIENT"]["SEX"];
        $pt_id = $ordine["PATIENT"]["IDPATIENT"];

        //echo "<span style='font-size: 1.2em; font-weight: bold;'>PAZIENTE DELL'ORDINE:<br/><span style='color: darkgreen;'>$pt_name (" . $ordine["PATIENT"]["DOB"] . ")</span> " . $ordine["PATIENT"]["SEX"] . "</span><br/>";


        // 2023-05-10 - SR
        /*
        SELECT 	distinct(di.status) AS sts, di.id 
        FROM 	public.dcm_imports di 
                INNER JOIN public.dcm_imports_instances dii ON dii.fk_import = di.id 
        WHERE 	dii.parent_patient in ( '05f22df5-a12b92a7-55be2071-aca8f5dd-89f3d984', '5648ac0c-6af0b8b9-2485669f-04b3bf8a-42ad02ae' )
                and di.id in (0,160,161,162);
        */


        $sql = "  SELECT  count(*) as nr_pt
                  FROM    public.dcm_imports
                  WHERE   id IN ($import_ids) ";
        $impt = query_select( $sql );

        //echo $impt, true );
        //echo "IMPORTATO " . $impt[0]["nr_pt"] . " PAZIENTI<br/><hr/><br/>";

        // elenco degli studi
        $sql = "    SELECT  distinct(parent_study) as ps
                    FROM    public.dcm_imports_instances
                    WHERE   fk_import IN ($import_ids) 
                            AND  parent_patient IN $import_this ";
        echo_sql( $sql );

        $stds = query_select( $sql );

        if ( IsNull($stds[0]['ps']) ) {
            // NULLA DA elaborare
            WriteLog( "NESSUNO STUDIO IMPORTATO ", import_logfile, "ERROR" );
            die( "NESSUNO STUDIO IMPORTATO<br/>" );
        }

        // echo "<br/><br/><hr/>Trovati i seguenti studi: <br/>";

        foreach( $stds as $st ){
            // echo $st["ps"] . "<br/>";
            $cmd = orthanc_url . '/studies/' . $st["ps"];
            $study = call_orthanc( $cmd, "GET_STUDY", false, 'GET');

            // echo $cmd . "<br/>"  );
            // echo $study, true );


            // estraggo l'ID dell'import di questo studio!
            $sql = "    SELECT  distinct(fk_import) as fk_i
                        FROM    public.dcm_imports_instances
                        WHERE   fk_import IN ($import_ids) 
                                AND  parent_study = '" . $st["ps"] . "' ";
            $dcm_i = query_select( $sql );
            $fk_import = $dcm_i[0]["fk_i"];


            $replace_flds = '';

            if( IMPORT_change_acc_number ){
                // c'è da ricalcolare l'ACC.NUMBER dello studio
                // echo "CAMBIO STUDIO Acc#  DA " . $study["MainDicomTags"]["AccessionNumber"] . " a " . acc_number_prefix . $fk_import . "<br/>";
                $replace_flds = '"AccessionNumber":"' . acc_number_prefix . $fk_import .'"';
            }

            // ora controllo il paziente di questo studio!!
            $pt_ok = true;
            if ( strtoupper($pt_name) != strtoupper($study["PatientMainDicomTags"]["PatientName"]) ){
                // echo "<span style='color: darkred; font-size: 1.1em; font-weight: bold;'>IL NOME PAZIENTE NON CORRISPONDE!!</span><br/>";
                $pt_ok = false;
            }

            if( $pt_dob != $study["PatientMainDicomTags"]["PatientBirthDate"] ){
                // echo "<span style='color: darkred; font-size: 1.1em; font-weight: bold;'>LA DATA DI NASCITA DEL PAZIENTE NON CORRISPONDE!!</span><br/>";
                $pt_ok = false;
            }

            if( $ordine["PATIENT"]["SEX"] != $study["PatientMainDicomTags"]["PatientSex"] ){
                // echo "<span style='color: darkred; font-size: 1.1em; font-weight: bold;'>IL SESSO DEL PAZIENTE NON CORRISPONDE!!</span><br/>";
                $pt_ok = false;
            }

            if( $ordine["PATIENT"]["IDPATIENT"] != $study["PatientMainDicomTags"]["PatientID"] ){
                // echo "<span style='color: darkred; font-size: 1.1em; font-weight: bold;'>L' ID DEL PAZIENTE NON CORRISPONDE!!</span><br/>";
                $pt_ok = false;
            }

            if ( $pt_ok ) {
                // echo "<span style='color: green; font-size: 1.1em; font-weight: bold;'>IL PAZIENTE CORRISPONDE!!</span><br/>";
            }

            $keep_source = "true";
            if ( !$pt_ok ){
                // i paziente è da cambiare
                if ( $replace_flds != '' ){
                    $replace_flds .= ", ";
                }
                $replace_flds .= '                
                    "PatientBirthDate":"' . $pt_dob . '",
                    "PatientID":"' . $pt_id . '",
                    "PatientName":"' . $pt_name . '",
                    "PatientSex":"' . $pt_sex . '" ';
                echo "<strong>CAMBIO I DATI PAZIENTE!!</strong><br/>";
                // non devo tenere l'originale
                $keep_source = "false";
            }

            // ora modifico lo studio
            $post_fields = '
            {   "Replace": { ' . $replace_flds . ' },
                "Remove":[],
                "Keep":["StudyInstanceUID","SeriesInstanceUID","SOPInstanceUID"],
                "KeepSource":'. $keep_source . ',
                "Force":true,
                "Synchronous":true
            }
            ';
        
            if( $replace_flds != '' ){
                // c'è qualcosa da cambiare!!
                $modify_url = "/studies/" . $st["ps"] . "/modify";
                
                // echo $modify_url . "<br/>" . trim($post_fields) );

                $new_std = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'POST', trim($post_fields) );

                //echo "<pre>", var_dump($new_std), "</pre>";

                echo "MODIFICATI TAG STUDIO $fk_import <br/>"; // $post_fields" . "<br/>";
                WriteLog( "MODIFICATI TAG STUDIO $fk_import <br/>$post_fields", import_logfile, "INFO" );

                if ( !$pt_ok ){
                    // ora devo modificare lo study ID di orthanc perché il paziente è cambiato
                    $sql = "
                        UPDATE  dcm_imports_instances
                        SET     parent_study = '" . $new_std["ID"] . "'
                        WHERE   parent_study = '" . $st["ps"] . "' 
                                AND fk_import = $fk_import ";
                    query_execute( $sql );

                    //echo "MODIFICATO STUDY ID  DA " . $st["ps"] . " a " . $new_std["ID"] . "<br/>";
                    WriteLog( "MODIFICATO STUDY ID  DA " . $st["ps"] . " a " . $new_std["ID"], import_logfile, "INFO" );
                }
            }
        }
        echo "<br/><br/>";
    }


    if( isset($_POST["annulla_import"]) && $_POST["annulla_import"] == "ANNULLA IMPORT" ){
        $descr = "<span style='font-size: 1.2em; font-weight: bold; color: darkred; float: left;'>IMPORT ANNULLATO!!!!  ($import_ids)</span>";
        $status = 99;
    }


    $sql = "    UPDATE  public.dcm_imports di
                SET     status = $status
                FROM    public.dcm_imports_instances dii 
                WHERE   di.id = dii.fk_import
                        AND di.id IN ($import_ids) 
                        AND parent_patient IN $import_this ";
    echo_sql( $sql );
    $ris = query_execute( $sql );



    // 2023-05-10 - SR
    // qui, invece, metto a 99 gli IMPORTs che NON sono stati confermati
    $sql = "    UPDATE  public.dcm_imports di 
                SET     status = 99
                FROM    public.dcm_imports_instances dii 
                WHERE   di.id = dii.fk_import
                        AND di.id IN ($import_ids) 
                        AND parent_patient NOT IN $import_this ";
    echo_sql( $sql );
    $ris = query_execute( $sql );

    WriteLog( "$descr \n elenco import: $import_ids \n elenco pazienti accettati: $import_this \n", import_logfile, "INFO" );
}
?>    
        <?=$descr?>
        <hr/>
        </div>
    </body>
</html>

<?php
function echo_sql( $sql ){
    return;
    echo "<div style='color: white; background-color: black; margin: 20px; padding: 10px;'>";
    echo "<pre>$sql</pre>";
    echo "</div>";
}