<?php

require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/Mention.php');
require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/Modalite.php');
require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/FamilleActes.php');
require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/cdc2022/Ischemique.php');
require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/cdc2022/Rythmologie.php');
require_once(rootDir() . 'modules/pmsi/php/etudes/cardioInterventionnelle/cdc2022/Congenitale.php');
require_once(rootDir() . 'modules/base/php/utils/Cast.php');


class EtudeCardioPost
{
    //CTI_CARDIO_INTERVENTIONNELLE_2022
    private $code;

    private $cdc;

    private $iCTI_connexion;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->code = "CTI_CARDIO_INTERVENTIONNELLE_2022";
        $this->cdc = "2022";
        $this->iCTI_connexion = Database2Factory::getInstance(Environnement::PROVIDER_CTI);
    }

    public function execute()
    {
        echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "INFO" . "\t" . "Lancement post traitement de l'étude $this->code";

        $this->clear();
        echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "INFO" . "\t" . "Suppression effectuée pour l'étude $this->code";

        $years = $this->getYearsToTreat();
        $ischemique = new Ischemique();
        $rythmologie = new Rythmologie();
        $congenitale = new Congenitale();


        foreach ($years as $year) {
            $ischemique->checkCdcIsValid($year);
            $rythmologie->checkCdcIsValid($year);
            $congenitale->checkCdcIsValid($year);
        }

        echo "\r\n" . date("d/m/Y H:i:s") . "\t" . "INFO" . "\t" . "Fin des post traitements de l'étude $this->code";

    }

    /**
     * @return array
     */
    private function getYearsToTreat()
    {
        $years = array();

        $sql = <<<SQL
        SELECT 
        DISTINCT(EXTRACT('Year' From date_acte)) as year 
        from pmsi.p_rss_cardio;
SQL;

        $result = $this->iCTI_connexion->query($sql);
        while ($row = $this->iCTI_connexion->fetchAssoc($result)) {
            $years[] = $row['year'];
        }
        asort($years);
        return $years;
    }

    private function clear()
    {
        $sql = <<<SQL
            DELETE FROM
            pmsi.p_etude_cardio WHERE cdc = '$this->cdc'
SQL;

        $this->iCTI_connexion->query($sql);


    }


}