<?php

include APPLICATION_PATH . '/DAO/CovidDAO.php';
include APPLICATION_PATH . '/DAO/FicheEpidemioDAO.php';
include APPLICATION_PATH . '/DAO/UtilisateurDAO.php';
include APPLICATION_PATH . '/DAO/ProfilDAO.php';
include APPLICATION_PATH . '/DAO/PersonneDAO.php';
include APPLICATION_PATH . '/DAO/LogDAO.php';
include APPLICATION_PATH . '/DAO/DroitDAO.php';
include APPLICATION_PATH . '/DAO/MenuDAO.php';
include PUBLIC_PATH . '/Fonctions/Fonction.php';
include PUBLIC_PATH . '/files_to_include/Constantes.php';
include APPLICATION_PATH .'/DAO/Osms.php';


class CovidController extends Zend_Controller_Action
{

    public function init()
    {
       header('Access-Control-Allow-Origin: *');
        session_start();
        if ( isset($_SESSION["idUtilisateur"])){
            $_SESSION["derniereAction"] = new \DateTime();
        }else{
            $this->_helper->redirector('index' , 'Index');
        }

    }

    public function indexAction()
    {
        try{
          $covidDao = new CovidDAO();
          $connection = $covidDao->_em->getConnection();
          if ($_SESSION["orgunit"]==DECIDEUR) {
                      $sql = " CREATE OR REPLACE VIEW covidEpi AS SELECT c.grippe_num_inclusion AS id, concat(COALESCE(c.grippe_nom_prenom,''),' ', COALESCE(c.grippe_prenom,'')) AS nom,  c.grippe_result_pcr AS resultat,c.sexe AS sexe, c.grippe_tel_patient AS telephone,c.orgUnit AS lieu,COALESCE(c.grippe_date_prelev,'') AS datePrelev"
                 . " FROM covid c left join smsrecus r on c.grippe_num_inclusion=r.id "
                  . "where  r.id IS NULL";
          
          }else{
                      $sql = " CREATE OR REPLACE VIEW covidEpi AS (SELECT c.grippe_num_inclusion AS id, concat(COALESCE(c.grippe_nom_prenom,''),' ', COALESCE(c.grippe_prenom,'')) AS nom,  c.grippe_result_pcr AS resultat,c.sexe AS sexe, c.grippe_tel_patient AS telephone,c.orgUnit AS lieu,COALESCE(c.grippe_date_prelev,'') AS datePrelev"
                 . " FROM covid c left join smsrecus r on c.grippe_num_inclusion=r.id "
                  . "where r.id IS NULL "." and c.orgUnit like '".$_SESSION["orgunit"]."')";
          }

          $requete = $connection->prepare($sql);
          $requete->execute();
       } catch (Exception $ex) {
          echo $ex->getMessage() . " Si cela persiste veuillez contacter l'administateur";
          exit();
       }
    }


  public function informationAction(){
      if(!empty($_POST)){
          $formSanitaire = $_POST["formSanitaire"];
          $semaineEpidemio = $_POST["semaineEpidemio"];
          $ficheDao = new FicheSMSDAO();
           $fiche= $ficheDao->getFiche($semaineEpidemio, $formSanitaire);
           $result = array("formSanitaire"=>$fiche->getFormsanitaire(),"semaineEpidemio"=>$fiche->getSemaineepidemio(),"nbconsulttotal"=>$fiche->getNbconsulttotal(),
               "nbaffectfebrile"=>$fiche->getNbaffectfebrile(),"nbira"=>$fiche->getNbira(),"nbsg"=>$fiche->getNbsg(),
               "nbconsultants1"=>$fiche->getNbconsultants1(),"nbfebrile1"=>$fiche->getNbfebrile1(),"nbira1"=>$fiche->getNbira1(),"nbsg1"=>$fiche->getNbsg1(),
                "nbconsultants2"=>$fiche->getNbconsultants2(),"nbfebrile2"=>$fiche->getNbfebrile2(),"nbira2"=>$fiche->getNbira2(),"nbsg2"=>$fiche->getNbsg2(),
                "nbconsultants3"=>$fiche->getNbconsultants3(),"nbfebrile3"=>$fiche->getNbfebrile3(),"nbira3"=>$fiche->getNbira3(),"nbsg3"=>$fiche->getNbsg3(),
                "nbconsultants4"=>$fiche->getNbconsultants4(),"nbfebrile4"=>$fiche->getNbfebrile4(),"nbira4"=>$fiche->getNbira4(),"nbsg4"=>$fiche->getNbsg4(),
                "nbconsultants5"=>$fiche->getNbconsultants5(),"nbfebrile5"=>$fiche->getNbfebrile5(),"nbira5"=>$fiche->getNbira5(),"nbsg5"=>$fiche->getNbsg5(),
               "nbecouvnano"=>$fiche->getNbecouvnano(),"nbecouvbucco"=>$fiche->getNbecouvbucco());
          echo json_encode(array("type"=>"success","data"=>$result));
          exit();
      }else{
          echo json_encode(array("type"=>"error","data"=>"Paramètres incorrects"));
          exit();
      }
      
  }
  public function validerAction(){
      if(!empty($_POST)){
          $formSanitaire = $_POST["formSanitaire"];
          $semaineEpidemio = $_POST["semaineEpidemio"];
          $ficheDao = new FicheSMSDAO();
           $ficheSMS= $ficheDao->getFiche($semaineEpidemio, $formSanitaire);
           
           if(!is_object($ficheSMS)){
                echo json_encode(array("type"=>"error","data"=>"Fiche inexistante"));
                exit();
           }else{
               //
               try {
                   $ficheDao->_em->beginTransaction();
                        $ficheEpiDao  = new FicheepidemioDAO();
                        $ficheEpidemio = new \Application\Models\Ficheepidemio();
                        //Set parameter of ficheEpidemio
                        $ficheEpidemio->setDateenvoi($ficheSMS->getDateenvoi());
                        $ficheEpidemio->setFormsanitaire($ficheSMS->getFormsanitaire());
                        $ficheEpidemio->setJourepidemio($ficheSMS->getJourepidemio());
                        $ficheEpidemio->setIddonnee($ficheSMS->getIddonnee());
                        $ficheEpidemio->setSemaineepidemio($ficheSMS->getSemaineepidemio());
                                 
                        $ficheEpidemio->setNbconsulttotal($ficheSMS->getNbconsulttotal());
                        $ficheEpidemio->setNbconsultants1($ficheSMS->getNbconsultants1());
                        $ficheEpidemio->setNbconsultants2($ficheSMS->getNbconsultants2());
                        $ficheEpidemio->setNbconsultants3($ficheSMS->getNbconsultants3());
                        $ficheEpidemio->setNbconsultants4($ficheSMS->getNbconsultants4());
                        $ficheEpidemio->setNbconsultants5($ficheSMS->getNbconsultants5());
                        
                        $ficheEpidemio->setNbechantillon($ficheSMS->getNbechantillon());
                        $ficheEpidemio->setNbecouvbucco($ficheSMS->getNbecouvbucco());
                        $ficheEpidemio->setNbecouvnano($ficheSMS->getNbecouvnano());
                        
                        $ficheEpidemio->setNbaffectfebrile($ficheSMS->getNbaffectfebrile());
                        $ficheEpidemio->setNbfebrile1($ficheSMS->getNbfebrile1());
                        $ficheEpidemio->setNbfebrile2($ficheSMS->getNbfebrile2());
                        $ficheEpidemio->setNbfebrile3($ficheSMS->getNbfebrile3());
                        $ficheEpidemio->setNbfebrile4($ficheSMS->getNbfebrile4());
                        $ficheEpidemio->setNbfebrile5($ficheSMS->getNbfebrile5());
                        
                        $ficheEpidemio->setNbira($ficheSMS->getNbira());
                        $ficheEpidemio->setNbira1($ficheSMS->getNbira1());
                        $ficheEpidemio->setNbira2($ficheSMS->getNbira2());
                        $ficheEpidemio->setNbira3($ficheSMS->getNbira3());
                        $ficheEpidemio->setNbira4($ficheSMS->getNbira4());
                        $ficheEpidemio->setNbira5($ficheSMS->getNbira5());
                        $ficheEpidemio->setNbsg($ficheSMS->getNbsg());
                        
                        $ficheEpidemio->setNbsg1($ficheSMS->getNbsg1());
                        $ficheEpidemio->setNbsg2($ficheSMS->getNbsg2());
                        $ficheEpidemio->setNbsg3($ficheSMS->getNbsg3());
                        $ficheEpidemio->setNbsg4($ficheSMS->getNbsg4());
                        $ficheEpidemio->setNbsg5($ficheSMS->getNbsg5());
                       
                        //Enregistement de la nouvelle ficheEpidemio
                        $ficheEpiDao->enregistrer($ficheEpidemio);
                        $ficheDao->disable($ficheSMS);
                   $ficheDao->_em->commit();
                   echo json_encode(array("type"=>"success","message"=>"Validation effectuée avec succèss"));
               
               } catch (Exception $ex) {
                   $ficheDao->_em->rollBack();
                   echo json_encode(array("type"=>"error","message"=>$ex->getMessage()));
               }
               
           }
        
         
          exit();
      }else{
          echo json_encode(array("type"=>"error","data"=>"Paramètres incorrects"));
          exit();
      }
  }

    public function editerAction()
    {
        if ( !empty($_POST)){
            //Initialisation
            $formSanitaire = trim($_POST["formSanitaire"]);
            $semaineEpidemio = trim($_POST["semaineEpidemio"]);
            $nbEcouvnano = (int)$_POST["nbEcouvnano"];
            $nbEcouvbucco = (int)$_POST["nbEcouvbucco"];
            $nbConsultTotal = (int)$_POST["nbConsultTotal"];
            $nbAffectFebrile = (int)$_POST["nbAffectFebrile"];
            $nbIra = (int)$_POST["nbIra"];
            $nbSg = (int)$_POST["nbSg"];
            //Consultation
            $nbConsultants1 = (int)$_POST["nbConsultants1"];
            $nbConsultants2 = (int)$_POST["nbConsultants2"];
            $nbConsultants3 = (int)$_POST["nbConsultants3"];
            $nbConsultants4 = (int)$_POST["nbConsultants4"];
            $nbConsultants5 = (int)$_POST["nbConsultants5"];
            //Febrile
            $nbfebrile1 = (int)$_POST["nbfebrile1"];
            $nbfebrile2 = (int)$_POST["nbfebrile2"];
            $nbfebrile3 = (int)$_POST["nbfebrile3"];
            $nbfebrile4 = (int)$_POST["nbfebrile4"];
            $nbfebrile5 = (int)$_POST["nbfebrile5"];
            
            //IRa
            $nbIra1 = (int)$_POST["nbIra1"];
            $nbIra2 = (int)$_POST["nbIra2"];
            $nbIra3 = (int)$_POST["nbIra3"];
            $nbIra4 = (int)$_POST["nbIra4"];
            $nbIra5 = (int)$_POST["nbIra5"];
            
            //nbSg
            $nbSg1 = (int)$_POST["nbSg1"];
            $nbSg2 = (int)$_POST["nbSg2"];
            $nbSg3 = (int)$_POST["nbSg3"];
            $nbSg4 = (int)$_POST["nbSg4"];
            $nbSg5 = (int)$_POST["nbSg5"];
            
           $ficheDao = new FicheSMSDAO();
           $fiche = $ficheDao->getFiche($semaineEpidemio, $formSanitaire);
            if ( !is_object($fiche)){
                echo json_encode(array("type" => "error" , "message" => "Fiche de la semaine (" . $semaineEpidemio." et du site ".$formSanitaire. ") inexistante"));
                exit();
            }else{
                //Total
                if( $fiche->getNbconsulttotal()!=$nbConsultTotal){
                    $fiche->setNbconsulttotal($nbConsultTotal);
                }
                if( $fiche->getNbaffectfebrile()!=$nbAffectFebrile){
                    $fiche-> setNbaffectfebrile($nbAffectFebrile);
                }
                 if( $fiche->getNbira()!=$nbIra){
                    $fiche->setNbira($nbIra);
                }
                if( $fiche->getNbsg()!=$nbSg){
                    $fiche->setNbsg($nbSg);
                }
                //Consultation
               if( $fiche->getNbconsultants1()!=$nbConsultants1){
                    $fiche->setNbconsultants1($nbConsultants1);
                }
                if( $fiche->getNbconsultants2()!=$nbConsultants2){
                    $fiche->setNbconsultants2($nbConsultants2);
                }
                if( $fiche->getNbconsultants3()!=$nbConsultants3){
                    $fiche->setNbconsultants3($nbConsultants3);
                }
                if( $fiche->getNbconsultants4()!=$nbConsultants4){
                    $fiche->setNbconsultants4($nbConsultants4);
                }
                if( $fiche->getNbconsultants5()!=$nbConsultants5){
                    $fiche->setNbconsultants5($nbConsultants5);
                }
                //Febrile
                if( $fiche->getNbfebrile1()!=$nbfebrile1){
                    $fiche->setNbfebrile1($nbfebrile1);
                }
                if( $fiche->getNbfebrile2()!=$nbfebrile2){
                    $fiche->setNbfebrile2($nbfebrile2);
                }
                if( $fiche->getNbfebrile3()!=$nbfebrile3){
                    $fiche->setNbfebrile3($nbfebrile3);
                }
                if( $fiche->getNbfebrile4()!=$nbfebrile4){
                    $fiche->setNbfebrile4($nbfebrile4);
                }
                if( $fiche->getNbfebrile5()!=$nbfebrile5){
                    $fiche->setNbfebrile5($nbfebrile5);
                }
                
                //Ira
                if( $fiche->getNbira1()!=$nbIra1){
                    $fiche->setNbira1($nbIra1);
                }
                 if( $fiche->getNbira2()!=$nbIra2){
                    $fiche->setNbira2($nbIra2);
                }
                 if( $fiche->getNbira3()!=$nbIra3){
                    $fiche->setNbira3($nbIra3);
                }
                if( $fiche->getNbira4()!=$nbIra4){
                    $fiche->setNbira4($nbIra4);
                }
                if( $fiche->getNbira5()!=$nbIra5){
                    $fiche->setNbira5($nbIra5);
                }
                //SG
                if( $fiche->getNbsg1()!=$nbSg1){
                    $fiche->setNbsg1($nbSg1);
                }
                if( $fiche->getNbsg2()!=$nbSg2){
                    $fiche->setNbsg2($nbSg2);
                }
                if( $fiche->getNbsg3()!=$nbSg3){
                    $fiche->setNbsg3($nbSg3);
                }
                if( $fiche->getNbsg4()!=$nbSg4){
                    $fiche->setNbsg4($nbSg4);
                }
                if( $fiche->getNbsg5()!=$nbSg5){
                    $fiche->setNbsg5($nbSg5);
                }
                //Ecouvillon
                if( $fiche->getNbecouvnano()!=$nbEcouvnano){
                    $fiche->setNbecouvnano($nbEcouvnano);
                }
                if( $fiche->getNbecouvbucco()!=$nbEcouvbucco){
                    $fiche->setNbecouvbucco($nbEcouvbucco);
                }
              try {
                  $ficheDao->_em->beginTransaction();
                   $ficheDao->editer($fiche);
                   
                   
                   $ficheDao->_em->commit();
                    echo json_encode(array("type" => "success","message"=>"Enregistrement effectué avec succèss"));
              } catch (Exception $ex) {
                  $ficheDao->_em->rollBack();
                    echo json_encode(array("type" => "error","message"=>$ex->getMessage()));
              }
               
                
            }
            exit();
            
        }else{
           echo json_encode(array("type" => "error","msg"=>"Paramètres incorrects"));
            exit();
        }
        
       
    }

    

    public function sendsmsAction(){
       if (!empty($_POST)){
            $liste  = $_POST["parametres"];
            $nbreSmsEnvoye = 0;
            foreach ( $liste as $elem) {
                 if (trim($elem["sexe"]) =="Feminin") {
                    $nomReceiver = "Mme ".strtoupper(trim($elem["nom"]));
                  }else{
                    if (trim($elem["sexe"] =="Masculin")) {
                      $nomReceiver = "Mr ".strtoupper(trim($elem["nom"]));
                    }else{
                      $nomReceiver = strtoupper(trim($elem["nom"]));
                    }
                  }
                  $sexe = trim($elem["sexe"]);
                  $resultat = trim($elem["resultat"]);
                  $phoneReceiver="tel:+237";
                   $labo = trim($elem["labo"]);
                    $identifiant = trim($elem["id"]);
                  $phoneReceiver.= trim($elem["tel"]);
                   $message = "";
                 
                  $datePrelev = trim($elem["datePrelev"]);
                  switch ($labo) {
                    case 'Virologie':
                      $message.=$nomReceiver.", le CENTRE PASTEUR DU CAMEROUN vous informe que votre prelevement du ".$datePrelev." a été testé NEGATIF";
                      break;
                     case 'HOPITAL LAQUINTINIE DOUALA':
                      $message.=$nomReceiver.", l'HOPITAL LAQUINTINIE DOUALA vous informe que votre prelevement du ".$datePrelev." a été testé NEGATIF";
                      case 'CPC GAROUA':
                      $message.=$nomReceiver.", le CENTRE PASTEUR DU CAMEROUN ANNEXE DE GAROUA vous informe que votre prelevement du ".$datePrelev." a été testé NEGATIF";
                      case 'HOPITAL LAQUINTINIE DOUALA':
                      $message.=$nomReceiver.", l'HOPITAL LAQUINTINIE DOUALA vous informe que votre prelevement du ".$datePrelev." a été testé NEGATIF";
                      case 'HOPITAL REGIONAL DE BERTOUA':
                        $message.=$nomReceiver.", l'HOPITAL REGIONAL DE BERTOUA vous informe que votre prelevement du ".$datePrelev." a été testé NEGATIF";
                      case 'TUBERCULOSIS REFERENCE LABORATORY BAMENDA':
                        $message.=$nomReceiver.", the TUBERCULOSIS REFERENCE LABORATORY BAMENDA informs you that your sample of ".$datePrelev." a has been tested NEGATIVE";
                      case 'LABORATORY FOR EMERGING INFECTIOUS DISEASES':
                        $message.=$nomReceiver.", the LABORATORY FOR EMERGING INFECTIOUS DISEASES of BUEA informs you that your sample of ".$datePrelev." a has been tested NEGATIVE";
                    default:
                      # code...
                      break;
                  }
                  
                  

              $config = array(
                  'token' => 'efYImzg65FsRnGkuq8rYT83F8mhi'
              );

              $osms = new Osms($config);

              //$osms->setVerifyPeerSSL(false);

              $response = $osms->sendSms(
                  // sender
                  'tel:+237696993837',
                  // receiver
                  $phoneReceiver,
                  // message
                  $message
              );

              if (empty($response['error'])) {
                  
                            try{
                              $nbreSmsEnvoye = $nbreSmsEnvoye+1;
                          $covidDao = new CovidDAO();
                          $connection = $covidDao->_em->getConnection();
                          $sql = "insert into smsrecus(id,nom,resultat,sexe,telephone,lieu,datePrelev) values('".$identifiant."','".$nomReceiver."','".$resultat."','".$sexe."','".$phoneReceiver."','".$labo."','".$datePrelev."')";

                          $requete = $connection->prepare($sql);
                          $requete->execute();
                       } catch (Exception $ex) {
                          echo $ex->getMessage() . " Si cela persiste veuillez contacter l'administateur";
                          exit();
                       }
              }


            }
            if ($nbreSmsEnvoye>0) {
              echo json_encode(array("type" => "success","message"=>"Message envoye avec susccess"));
            }else{
              echo json_encode(array("type" => "erreur","message"=>"Echec d'envoi des sms"));
            }

        exit();
    }
  }


  public function datatableAction()
    {
        $table = 'covidEpi';

        $primaryKey = 'id';
        $columns = array(
            array('db' => 'lieu' , 'dt' => 0),
            array('db' => 'nom' , 'dt' => 1),
             array('db' => 'sexe' , 'dt' => 2),
            array('db' => 'resultat' , 'dt' => 3),
             array('db' => 'telephone' , 'dt' => 4),
            array('db' => 'id' , 'dt' => 5),
            array('db' => 'datePrelev' , 'dt' => 6)
        );


        $sql_details = array(
            'user' => DB_USER,
            'pass' => DB_PASSWORD,
            'db' => DB_NAME,
            'host' => HOSTNAME
        );

        require(PUBLIC_PATH . '/files_to_include/ssp.class.php');

        $resultatDataTable = SSP::simple($_POST, $sql_details, $table, $primaryKey, $columns);
        $finalResult = array();
        $finalResult["draw"] = $resultatDataTable["draw"];
        $finalResult["recordsTotal"] = $resultatDataTable["recordsTotal"];
        $finalResult["recordsFiltered"] = $resultatDataTable["recordsFiltered"];
        $finalResult["data"] = array();
        foreach ( $resultatDataTable["data"] as $ligneTableau ){
            $identifiant =  utf8_encode($ligneTableau[5]);
            $labo = $ligneTableau[0];
            $sexe = $ligneTableau[2];
            $resultat = $ligneTableau[3];
            $telephone = $ligneTableau[4];
            $datePrelev = $ligneTableau[6];
            $patient =  utf8_encode($ligneTableau[1]);
          
            $chaine = "";
            if ($resultat == "Negatif") {
              $couleurBackground = COULEUR_NEGATIF;
              $chaine .= "<input class='cocher' type='checkbox' resultat='".$resultat."' identifiant='" . $identifiant . "'/>";
                     $chaine .= " <a style='color:#ffffff;'  nom='".$patient."' labo=".$labo." sexe=".$sexe."  datePrelev=".$datePrelev."  tel=".$telephone." class='sendSMS' resultat='".$resultat."'  id='" . $identifiant . "'><i title='Send SMS' class='glyphicon glyphicon-envelope clickcursor bluelink' ></i></a>";
                     $chaine .= " <a style='color:#ffffff;' nom='".$patient."' labo=".$labo." sexe=".$sexe."  datePrelev=".$datePrelev."  tel=".$telephone." class='print' resultat='".$resultat."'  identifiant='" . $identifiant . "'><i title='Print' class='glyphicon glyphicon-print clickcursor' ></i></a>";
            }elseif($resultat == "Positif") {
              $couleurBackground = COULEUR_POSITIF;
              $chaine .= "<input type='checkbox'  resultat='".$resultat."' id='" . $identifiant . "'/>";
               $chaine .= " <a style='color:#ffffff;' nom=".$patient." labo=".$labo." sexe=".$sexe."  datePrelev=".$datePrelev."  tel=".$telephone." class='print' resultat='".$resultat."'  id='" . $identifiant . "'><i title='Print' class='glyphicon glyphicon-print clickcursor' ></i></a>";
            }else{
              $couleurBackground = COULEUR_NON_VALIDER;
            }
            $newLine = array( $labo,$patient,$sexe,$resultat,$identifiant,$telephone,$datePrelev);
                    
                    //$urlEditer = $this->_helper->url->url(array('controller' => 'Sms', 'action' => 'editer' , 'id' => $id));
                     
           

           
            
             $newLine[] = $chaine;
             $newLine[] = $couleurBackground;
            $finalResult["data"][] = $newLine;
        }
        
        echo json_encode($finalResult);
        exit();

}
}






