<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 *
 * programma cheprende gli "other" studi che sono stati riconciliati dal RIS (status 51)
 * qui cambia i TAG DICOM e li rimette nella procedura standard 
 *
 */

// 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__ . "/tags_to_modify_calculation.php";

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

$pid_name = "delete_studies";
check_pid( $pid_name );


if( isset($GLOBALS["db_error"]['default_db']) ){
    WriteLog( "Errore DB: " . $GLOBALS["db_error"]['default_db'], "ERROR" );
    die_proc( "Errore DB: " . $GLOBALS["db_error"]['default_db'], $pid_name );
}


echoo( "\nELABORO GLI STUDI in stato 51\n\n" );
WriteLog( "ELABORO GLI STUDI in stato 51", process_logfile, "INFO" );



$single_orthanc_id = "";
if ( isset($argv[1]) || isset($_GET["id"]) ) {
    // da elaborare UN singolo studio
    $single_orthanc_id = " AND orthanc_id = '" .
                            ( isset($argv[1]) ? $argv[1] : $_GET["id"] )
                            . "' ";
}

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$data_to_delete = date('Y-m-d', strtotime($date . ' -' . delete_after . ' day'));


$studies = query_select("   SELECT  *
                            FROM    dcm_study
                            WHERE   status = 51 
                                    $single_orthanc_id
                            ORDER BY id ");


echoo( " WHERE:  status=51  $single_orthanc_id \n\n" );


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



/*
 *
 * REFERENCE ORTHANC
 * https://book.orthanc-server.com/users/anonymization.html
 * 
 */

foreach ($studies as $q_study) {
    echoo( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "  Status: " . $q_study["status"] . " \n" );
    WriteLog( "Elaboro " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "  Status: " . $q_study["status"], os_reconciled_logfile, "INFO" );

    // carico lo studio
    $modify_url = "/studies/" . $q_study["orthanc_id"];
    $o_study = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'GET' );

    /*
    echoo( "STUDIO: \n" );
    echoo( $o_study, true );
    echoo( "<hr/>\n" );
    */
    



    // carico il paziente
    // [ParentPatient] => da39a3ee-5e6b4b0d-3255bfef-95601890-afd80709
    $modify_url = "/patients/" . $o_study["ParentPatient"];
    $o_patient = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'GET' );
    

    /*
    echoo( "PATIENT: \n" );
    echoo( $o_patient, true );
    echoo( "<hr/>\n" );
    */

    $jsn_std = json_decode($q_study["tags_to_modify"]);



    /*
     *
     * da capire come fare per cambiare i dati paziente senza duplicare lo studio
     * 
     
                // modifico di paziente!!
                $post_fields = '{   
                    "Replace": ' . json_encode($jsn_std->Patient) . ',
                    "KeepSource":true,
                    "Force":true,
                    "Synchronous":false
                } ';
                $modify_url = "/patients/" . $o_study["ParentPatient"] . "/modify";
                $result = call_orthanc( orthanc_url . $modify_url, "PATIENT", FALSE, 'POST', trim($post_fields) );
                echoo( "\nchiamata paziente: $modify_url \n\n" );
                echoo( $result, true );


                // carico le istanze dello studio
                $modify_url = "/studies/" . $q_study["orthanc_id"] . "/instances";
                $study_instances = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'GET' );
                


                $post_fields = '{   
                    "Replace": ' . json_encode($jsn_std->Patient) . ',
                    "Remove":[],
                    "Keep":["StudyInstanceUID","SeriesInstanceUID","SOPInstanceUID"],
                    "KeepSource":true,
                    "Force":true,
                    "Synchronous":false
                }';

                foreach( $study_instances as $instance ){

                    echoo( $instance, true );
                
                    $modify_url = "/instances/" . $instance["ID"] . "/modify";
                    echoo( "chiamo othanc al  $modify_url\ncon questi parametri:\n" . trim($post_fields) );
                    echoo( "\n\n" );
                
                    $result = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'POST', trim($post_fields) );
                
                    echoo( $result, true );

                    if( isset($result["error"]) ){
                        // studio non trovato! passo alla prossima
                        echoo("ERRORE RICONCILIAZIONE " . $result["error"] . " - " .$result["descr"] . "\n<hr/>\n");
                        WriteLog("ERRORE  RICONCILIAZIONE  " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " " . $result["error"] . " - " .$result["descr"], os_reconciled_logfile, "ERROR");
                        continue;
                    }
                    
                }    
                
    *
    *
    */


    $post_fields = '
    {   "Replace": {"AccessionNumber":"' . $q_study["accession_number"] . '"},
        "Remove":[],
        "Keep":["StudyInstanceUID","SeriesInstanceUID","SOPInstanceUID"],
        "KeepSource":true,
        "Force":true,
        "Synchronous":false
    }';

    $modify_url = "/studies/" . $q_study["orthanc_id"] . "/modify";
    $result = call_orthanc( orthanc_url . $modify_url, "STUDIES", FALSE, 'POST', trim($post_fields) );

    //echoo( "chiamo othanc al  $modify_url\ncon questi parametri:\n" . trim($post_fields) );
    //echoo( "\n\n" );


    echoo( $result, true );
    if( isset($result["error"]) ){
        // studio non trovato! passo alla prossima
        echoo("ERRORE RICONCILIAZIONE " . $result["error"] . " - " .$result["descr"] . "\n<hr/>\n");
        WriteLog("ERRORE  RICONCILIAZIONE  " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " " . $result["error"] . " - " .$result["descr"], os_reconciled_logfile, "ERROR");
        continue;
    }

    
    $update_sql = " UPDATE  dcm_study
                    SET     status = 5
                    WHERE   id = " . $q_study["id"];
    //$upd_chan = query_execute($update_sql);


    echoo( "Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " andato in status: 5 <hr/>\n" );
    WriteLog( "Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " andato in status: 5", os_reconciled_logfile, "INFO" );
}


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

kill_pid($pid_name);
