<?php
/**
 * @copyright Gmed Srl
 * @author Sciarrone Riccardo <riccardos@gmed.it>
 *
 * programma che cancella gli studi in "spedito" da x giorni
 *
 */

// 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 7 o 98\n\n" );
WriteLog( "ELABORO GLI STUDI in stato 7 o 98", 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'));
if( delete_after == 0 ){
    // NON conservo mai i doc elaborati
    $data_to_delete = date('Y-m-d', strtotime($date . ' +1 day'));
}



$studies = query_select("   SELECT  *
                            FROM    dcm_study
                            WHERE   archive_date < '$data_to_delete' 
                                    AND (status = 7 OR status = 98)
                                    $single_orthanc_id
                            ORDER BY id ");


echoo( " WHERE  archive_date < '$data_to_delete' AND (status = 7 AND  OR status = 98)  $single_orthanc_id \n\n" );


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 );
}
else {
    // c'è qualcosa da eliminare!!
    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"], delete_logfile, "INFO" );


        //curl -X DELETE http://localhost:8042/studies/d79f11d9-c75867f7-20330513-fb4c1101-33636dbf

        $cmd = orthanc_url . '/studies/' . $q_study["orthanc_id"];

        // 2023-03-09 - SR - ripristinare la chiamata REALE dopo i TEST
        $result = call_orthanc( $cmd, "DELETE", false, 'DELETE', null );
        //$result = Array( "TEST" => "OK" );


        WriteLog( "Studio " . $q_study["id"] . " => delete result: " . print_r($result, TRUE), delete_logfile, "INFO" );

        $new_status = 99;
        if( $q_study["status"] == 7 ){
            $new_status = 9;
        }
        $update_sql = " UPDATE  dcm_study
                        SET     status = $new_status
                        WHERE   id = " . $q_study["id"];
        $upd_chan = query_execute($update_sql);
        echoo( "Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " andato in status: $new_status <hr/>\n" );
        WriteLog( "Studio " . $q_study["id"] . " => " . $q_study["orthanc_id"] . " andato in status: $new_status", delete_logfile, "INFO" );
    }
}

/* 2023-05-03 - SR - 
 * ora, se l'import è ATTIVO, elimino anche gli studi che
 * - NON SONO STATI CONFERMATI
 * - SONO RIMASTI IN STATUS 0 DA PIU' DI UN ORA
 */
if( historic_import_active ){
    echoo( "ELABORO GLI STUDI DI IMPORT ANNULLATI O NON CHIUSI!" );
    $date = date('Y-m-d H:i:s');
    $data_to_delete = date('Y-m-d H:i:s', strtotime($date . ' -1 hours'));

    $sql = "    SELECT  id
                FROM    dcm_imports
                WHERE   import_date < '$data_to_delete'
                        AND (status = 99 OR status = 0)
                ORDER BY id ";
    //echoo( $sql, false, true );

    $imprt = query_select( $sql );
    if ( isset($imprt[0]["id"]) && !IsNull($imprt[0]["id"]) ){
        // c'è qualcosa da cancellare
        for( $x=0; $x < count($imprt); $x++ ){
            echoo( "Elaboro IMPORT " . $imprt[ $x ]["id"], false, true );
            $sql = "SELECT 	distinct(dii.parent_study) as std
                    FROM 	public.dcm_imports di 
                            INNER JOIN public.dcm_imports_instances dii ON dii.fk_import = di.id 
                    WHERE 	di.id = " . $imprt[ $x ]["id"];

            $stds = query_select( $sql );
            if ( isset($stds[0]["std"]) && !IsNull($stds[0]["std"]) ){
                // c'è qualcosa da cancellare
                for( $y=0; $y < count($stds); $y++ ){
                    $cmd = orthanc_url . '/studies/' . $stds[ $y ]["std"];
                    echoo( "[DELETE] $cmd", false, true );
                    $result = call_orthanc( $cmd, "DELETE", false, 'DELETE', null );
                }
            }
            // cambio lo status dell'impor
            $sql = "    UPDATE  public.dcm_imports 
                        SET     status =  90
                        WHERE 	id = " . $imprt[ $x ]["id"];
            $upd_chan = query_execute( $sql );
        }
    }
}


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

kill_pid($pid_name);
