<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 * 
 * programma che testa i job di sent per vedere 
 * se lo studio è stato correttamente trasferito
 */




// 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";
//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 = "succ_send_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 6\n\n" );
WriteLog( "ELABORO GLI STUDI in stato 6", 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"] )
                            . "' ";
}



$studies = query_select("   SELECT  *
                            FROM    dcm_study
                            WHERE   status = 6 
                                    $single_orthanc_id
                            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 ) {
    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" );
    
    
    $cmd = orthanc_url . $q_study["job_id"];
    echoo("\n\ncomando: $cmd\n\n");
    
    $result = call_orthanc( $cmd, "JOB_CHECK", false, 'GET', '', FALSE );

    echoo( $result, TRUE );
    
    
    if( isset($result["error"]) ){
        // studio non trovato! passo alla prossima
        echoo("ERRORE NEL JOB " . $result["error"] . " - " .$result["descr"] . "\n");
        WriteLog("ERRORE NEL JOB  " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " " . $result["error"] . " - " .$result["descr"], send_logfile, "ERROR");
        
        // 2023-05-15 - SR - aggiunto 'send_repeat = send_repeat + 1' ==>  porto avanti il contatore dei tentativi di invio al centrale
        $update_sql = " UPDATE  dcm_study 
                        SET     status = 8, 
                                dicom_error = '" . $result["error"] . " - " .$result["descr"] . "' 
                                send_repeat = send_repeat + 1
                        WHERE   id = " . $q_study["id"];
        echoo("<pre>\n$update_sql\n</pre><hr/>\n");
        $upd_chan = query_execute( $update_sql );
        continue;
    }
    elseif( isset($result["ErrorCode"]) && $result["ErrorCode"] != "0" ){
        echoo("ERRORE NEL JOB " . $result["ErrorCode"] . " - " .$result["ErrorDescription"] . "\n");
        WriteLog("ERRORE NEL JOB  " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " " . $result["ErrorCode"] . " - " .$result["ErrorDescription"], send_logfile, "ERROR");
        

        // 2023-05-15 - SR - aggiunto 'send_repeat = send_repeat + 1' ==>  porto avanti il contatore dei tentativi di invio al centrale
        $update_sql = " UPDATE  dcm_study 
                        SET     status = 8, 
                                dicom_error = '" . $result["ErrorCode"] . " - " .$result["ErrorDescription"] . "',
                                send_repeat = send_repeat + 1
                        WHERE   id = " . $q_study["id"];
        echoo("<pre>\n$update_sql\n</pre><hr/>\n");
        $upd_chan = query_execute( $update_sql );
        continue;      
    }
    elseif ( isset($result["State"]) ){
        
        // è tornato un risultato standard
        
        if( $result["State"] == "Success"){
            $update_sql = " UPDATE  dcm_study 
                            SET     status = 7,
                                    archive_date = '" . date("Y-m-d H:i:s") . "' 
                            WHERE   id = " . $q_study["id"];
            $upd_chan = query_execute($update_sql);
            echoo("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " IN '7 - SPEDITO' \n<hr/>\n");
            WriteLog("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " IN '7 - SPEDITO' ", send_logfile, "INFO");     
            
            
            $completion_time = $result["CompletionTime"];
            // ora scrivo nella tabella sent
            $i_sql = "  INSERT INTO     public.dcm_sent
                            (dcmstudy_id, sent_datetime, response)
                        VALUES
                            (" . $q_study["id"]. ", " . dcm_time(substr($completion_time, 0, 8), substr($completion_time, 9, 6)) . ", '" . pg_escape_string( json_encode($result) ) . "')";
            //echoo("$i_sql\n\n");
            query_execute( $i_sql );          
            
            
            // 2023-05-03 - SR - se c'è l'import attivo, se lo studio è da import, CREO l'ordine nel RIS
            if( historic_import_active ){
                $sql = "    SELECT 	distinct(dii.fk_import) as fks
                            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"] . "' ";
                $fks = query_select( $sql );

                if ( isset($fks[0]['fks']) && !IsNull($fks[0]['fks']) && $fks[0]['fks'] > 0 ) {
                    // lo studio arriva dall'IMPORT
                    echoo( "QUESTO STUDIO " . $q_study["orthanc_id"] . " ARRIVA DALL'IMPORT<br/>" );

                    $update_sql = " UPDATE  dcm_imports 
                                    SET     status = 2,
                                            send_date = '" . date("Y-m-d H:i:s") . "' 
                                    WHERE   id = " . $fks[0][ 'fks' ];
                    $upd_s = query_execute($update_sql);
                    echoo( "IMPORT " . $fks[0]['fks'] . " MESSO A status=2 <br/>" );

                    // creo l'ORDER sul RIS
                    create_ris_order( $q_study, $fks[0]['fks'] );
                }
            }


        }
        else {
            // lo studio NON è ancora passato, aggiorno il contatore
            $update_sql = " UPDATE  dcm_study 
                            SET     job_test_repeter = job_test_repeter +1,
                            archive_date = '" . date("Y-m-d H:i:s") . "' 
                            WHERE   id = " . $q_study["id"];
            echoo("<pre>\n$update_sql\n</pre>");
            $upd_chan = query_execute($update_sql);
            echoo("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " store  ANCORA  in corso " . $q_study["job_test_repeter"] . "<hr/>\n");
            WriteLog("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " store  ANCORA  in corso " . $q_study["job_test_repeter"], send_logfile, "INFO");  
        }
    }
    else {
        echoo( "\nNON SO COSA FARE con questa Risposta:\n" );
        echoo( $result, TRUE );
        echoo( "<hr/>\n" );
        WriteLog("succ_send_studies.php  Problema con Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . "\nNON SO COSA FARE con questa Risposta:\n" .$result, send_logfile, "INFO");
    }
    
    
}


// 2023-05-15 - SR 
// TUTTI gli studi che sono andati in errore di JOB (status=8) ma che non hanno superato il numero di tentativi!!
$update_sql = " 
    UPDATE  dcm_study 
    SET     status = 6
    WHERE   status = 8 
            AND send_repeat < " . max_send_repeat;
echoo("<pre>\n$update_sql\n</pre>");
$upd_chan = query_execute($update_sql);

echoo( "Riportati a '6'  gli studi in '8' e con send_repeat < " . max_send_repeat );
//WriteLog("Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " store  ANCORA  in corso " . $q_study["job_test_repeter"], send_logfile, "INFO"); 


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

kill_pid($pid_name);