<?php
//$Id$ 
//gen openMairie le 05/06/2019 12:14

require_once "../gen/obj/participation_election.class.php";

class participation_election extends participation_election_gen {

	var $nombre_bureau;
	var $election;


    function __construct($id, &$dnu1 = null, $dnu2 = null) {
        $this->constructeur($id);      
		if($id!="]"){
			// nombre de bureaux a afficher depuis election_bureau 
			$this->election=$_GET['idxformulaire']; 
			$sql  = "select count(bureau) from ".DB_PREFIXE."election_bureau "; 
			$sql .= " where election_bureau.election =".$this->election;			
			$res = $this->db->getOne($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			for($i=1; $i <= $res ; $i++){
				array_push($this->champs,"bureau".$i);
				array_push($this->champs,"id".$i);
			}
			$this->nombre_bureau=$res;
		}
    }

    function init_class_actions() {
        parent::init_class_actions();  
		// verrou supprimer
		$this->class_actions[2]["condition"][1] = 'is_not_verrou';  
		// creer les bureau
        $this->class_actions[4] = array(
            "identifier" => "affichage",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("affichage tranche"),
                "order" => 50,
                "class" => "arrow-right-16",
            ),
            "view" => "formulaire",
            "method" => "affichage",
            "button" => "diffuser",
            "permission_suffix" => "tab",
        );        
           
		// creer les bureau
        $this->class_actions[5] = array(
            "identifier" => "web",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("afficher web"),
                "order" => 60,
                "class" => "arrow-right-16",
            ),
            "view" => "formulaire",
			"method" => "web",
            "button" => "diffuser",
            "permission_suffix" => "tab",
        );  
        
        // remise a zero
        $this->class_actions[6] = array(
            "identifier" => "remiseazero",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("annuler resultat"),
                "order" => 70,
                "class" => "delete-16",
            ),
            "view" => "formulaire",
			"method" => "annuler_resultat",
            "permission_suffix" => "tab",
        );  
         
	}


    function setType(&$form, $maj) {
		parent::setType($form, $maj);
		for($i=1; $i <= $this->nombre_bureau ; $i++){
			if($maj!=1)
				$form->setType('bureau'.$i,"hidden");
			$form->setType('id'.$i,"hidden");
		}		
		if($maj==1){
			for($i=1; $i <= $this->nombre_bureau ; $i++){
				//$form->setType('candidat'.$i,"text");
				$form->setType('bureau'.$i,"text");
				$form->setTaille('bureau'.$i,11);
				$form->setMax('bureau'.$i,11);					
			}
			$temp=$this->is_not_verrou();
			if(!$temp and $maj==1){
				$form->setType('tranche',"selecthiddenstatic");
			}
			$form->setType('envoi_aff',"hidden");
			$form->setType('envoi_web',"hidden");
		}
	}
	
    function setOnchange(&$form, $maj) {
		parent::setOnchange($form, $maj);
		if($maj==1){
			for($i=1; $i <= $this->nombre_bureau ; $i++){
				$form->setOnchange('bureau'.$i,'VerifNum(this)');
			}
		}
	}

    function setLib(&$form, $maj) {
        parent::setLib($form, $maj);
        // changement du libelle des bureaux depuis election_bureau
        $sql= "select concat(bureau.ordre,' ',bureau.libelle) as libelle from ".DB_PREFIXE."bureau "; 
        $sql .= " inner join ".DB_PREFIXE."election_bureau on election_bureau.bureau=bureau.bureau";
        $sql .= " where election = ".$this->getVal('election');
        $sql .= " order by bureau.ordre ";
        $res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($res);
		$i=0;
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){
			$i++;
			$form->setLib('bureau'.$i,$row['libelle']." : ");
		}
     }

	function set_form_default_values(&$form, $maj, $validation){
		// recuperation des valeurs identifiants bureaux et des votants pour le bureau 
		if($validation==0 and $maj==1){
			// identifiant de l election bureau concerne
			$sql= "select election_bureau.election_bureau from ".DB_PREFIXE."bureau "; 
			$sql .= " inner join ".DB_PREFIXE."election_bureau on election_bureau.bureau=bureau.bureau";
			$sql .= " where election = ".$this->getVal('election');
			$sql .= " order by bureau.ordre ";
			$res = $this->db->query($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$i=0;
			while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){
				$i++;
				$form->setVal('id'.$i,$row['election_bureau']);
			}
			// 
			
			
			// votant de participation_resultat
			$sql  = " select participation_bureau.votant from ".DB_PREFIXE."participation_bureau ";
			//$sql .= " inner join ".DB_PREFIXE."participation_election on participation_election.participation_election = participation.bureau.participation_election ";
			$sql .= " inner join ".DB_PREFIXE."election_bureau on election_bureau.election_bureau=participation_bureau.election_bureau";
			$sql .= " inner join ".DB_PREFIXE."bureau on election_bureau.bureau=bureau.bureau";
			$sql .= " where participation_bureau.participation_election = ".$this->getVal('participation_election'); 
			$sql .= " order by bureau.ordre ";				
			$res = $this->db->query($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			//$this->f->isDatabaseError($res);
			$i=0;
			while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){
				$i++;
				$form->setVal('bureau'.$i,$row['votant']);
			}
			//$this->addToMessage($sql);
			 		 			 
		}
	}


    function triggermodifier($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
		// update du votant de  participation_bureau suivant election/tranche/bureau
		$total_votant = 0;
		$this->addToMessage(_("participations enregistrées")." : ");
		for($i=1; $i <= $this->nombre_bureau ; $i++){	
			if(is_numeric($val["bureau".$i])){
				$votant=$val["bureau".$i];
				$total_votant = $total_votant + $votant;
			}else
				$votant=0;
			$sql  = " update ".DB_PREFIXE."participation_bureau set votant=".$votant;
			$sql .= " where participation_election = ".$this->getVal('participation_election'); 
			$sql .= " and election_bureau = ".$val["id".$i]; 
			//$this->addToMessage($sql);
			$res = $this->db->query($sql);
			
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$this->addToMessage(_("bureau")." ".$val["id".$i]." : ".$votant);					
		}	
		$this->addToMessage("<b>"._("total votants")." ".$total_votant."</b>");	
    }

    function triggermodifierapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
		// modification des bureaux transmis 	
		if($this->valF['envoi_aff']== 't'){
			$this->affichage('trigger');
		}
		if($this->valF['envoi_web']== 't'){
			$this->web('trigger');
		}
    }	

    function is_not_verrou() {
        //$this->setValFFromVal();
        $sql= " select verrou from ".DB_PREFIXE."election where election = ".
		$this->getVal("election");
		$etat = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($etat);				 
        if ($etat== 't' ) {
            return false;
        }         
        return true;
    }



	// ====================
	// methodes d'affichage
	// ====================
	
	function affichage ($mode=null){
        // si la methode est lancee par trigger
        // utiliser $this->valF 
        // car setValFFromVal() ramene les valeurs avant modification
        if($mode != 'trigger') 	     
			$this->setValFFromVal();
        // envoi aff a true
		if ($this->valF['envoi_aff']== 'f' and $mode!='annuler'){
			$this->f->db->autoCommit(false);
			$sql = "update  ".DB_PREFIXE."participation_election set envoi_aff=true where participation_election=".
			$this->valF['participation_election'];        
			$res = $this-> db -> query ($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$this->msg .=_("envoi affichage = true")."</br>";
			$this->f->db->commit();				
		}
		// inscrits
		$sql = "select    ";
		$sql .= " sum(inscrit) ";  
		$sql .= " from ".DB_PREFIXE."election_bureau ";
        $sql .= " where election_bureau.election=".$this->valF['election']; 
        $inscrits = $this->db->getOne($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($inscrits);
		// participations.inc
		$participations= $this->get_participations($this->valF["election"], $inscrits, "aff");	
        $contenu = "<?php\n";
        // On remplit le fichier uniquement si on a des résultats dans la requête		
		foreach ($participations as $key => $value)
			$contenu .= "\$participations [".$key."] = array (
				'heure' => \"".$value ['heure']."\", 
				'votants' => \"".$value ['votants']."\", 
				'tx' => \"".$value ['tx']."\");\n";
		
		$contenu .= "?>";	
		$envoi=$this->write_file("../aff/res/".$this->valF['election']."/participations.inc", $contenu);
		$this->msg .= "../aff/res/".$this->valF['election']."/participations.inc envoye"."</br>"; 		
		// 	/bpar/b(bureau).inc
		$sql = "select    ";
		$sql .= " election_bureau.bureau as bureau, bureau.ordre as ordre";  
		$sql .= " from ".DB_PREFIXE."election_bureau inner join ";
		$sql .= DB_PREFIXE."bureau on election_bureau.bureau=bureau.bureau ";
        $sql .= " where election_bureau.election=".$this->valF['election'];
        $sql .= " order by bureau.ordre ";           
        $res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$k = 0; // ?
		$i=0;
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){		
			$participation= $this->get_bureau($this->valF["election"], 'aff',$row['bureau']);
			$contenu = "<?php\n";
			$contenu .= "\$bureau_libelle = \"".$participation['libelle']." - ".$bureau_libelle."\";\n";
			$contenu .= "\$inscrit = \"".$participation['inscrit']."\";\n";
			$contenu .= "\$votant = \"".$participation['votant']."\";\n";
			$contenu .= "\$exprime = \"".$participation['exprime']."\";\n";
			$contenu .= "\$blanc = \"".$participation['blanc']."\";\n";
			$contenu .= "\$nul = \"".$participation['nul']."\";\n";	
			if (isset($participation)){			
				foreach ($participation as $key => $value){
					if(is_numeric($key))
						$contenu .= "\$participation [".$key."] = array ('heure' => \"".
							$value ['heure']."\", 'votants' => \"".$value ['votants'].
							"\", 'tx' => \"".$value ['tx']."\");\n";
				}
			}
			$contenu .= "?>";		
			$envoi=$this->write_file("../aff/res/".$this->valF['election']."/bpar/b".$row['ordre'].".inc", $contenu);
			//$this->msg .= "../aff/res/".$this->valF['election']."/bpar/b".$row['ordre'].".inc envoye"." | "; 		
			$i++;
		}
		$this->msg .= $i." "._("bureau(x) modifie(s)")." "._("dans")." "."../aff/res/".$this->valF['election']."/bpar/</br>";
		if ($mode!='annuler')
			$this->f->layout->display_message('valid', $this->msg);		 
	}


    /**
    * Permet de mettre à jour le fichier participation.inc du dossier : "web/res/".$election."/"
    * Ne convient pas pour les simulations qui n'ont pas de participations
    * Variables : 
    *   $participations [0] = array ('heure' => "12:00:00", 'votants' => "4720", 'tx' => "13.95");
    *   $participations [1] = array ('heure' => "14:00:00", 'votants' => "11284", 'tx' => "33.35");
    *   $participations [...] = array ('heure' => "16:00:00", 'votants' => "16141", 'tx' => "47.7");
    */

	
	function web ($mode=null){	
        // si la methode est lancee par trigger
        // utiliser $this->valF 
        // car setValFFromVal() ramene les valeurs avant modification
        if($mode != 'trigger') 		     
			$this->setValFFromVal();
        // envoi aff a true
		if ($this->valF['envoi_web']== 'f'  and $mode!='annuler' ){
			$this->f->db->autoCommit(false);
			$sql = "update  ".DB_PREFIXE."participation_election set envoi_web=true where participation_election=".
			$this->valF['participation_election'];        
			$res = $this-> db -> query ($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$this->msg .=_("envoi affichage = true")."</br>";
			$this->f->db->commit();				
		}
		// inscrits
		$sql = "select    ";
		$sql .= " sum(inscrit) ";  
		$sql .= " from ".DB_PREFIXE."election_bureau ";
        $sql .= " where election_bureau.election=".$this->valF['election'];
        // $this->addToMessage($sql);    
        $inscrits = $this->db->getOne($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($inscrits);
		// participations.inc
		$participations= $this->get_participations($this->valF["election"], $inscrits, "web");	
        $contenu = "<?php\n";
        // On remplis le fichier uniquement si on a des résultats dans la
        // requête		
		foreach ($participations as $key => $value)
			$contenu .= "\$participations [".$key."] = array (
				'heure' => \"".$value ['heure']."\", 
				'votants' => \"".$value ['votants']."\", 
				'tx' => \"".$value ['tx']."\");\n";
		
		$contenu .= "?>";	
		$envoi=$this->write_file("../web/res/".$this->valF['election']."/participation.inc", $contenu);
		$this->msg .="../web/res/".$this->valF['election']."/participation.inc envoye"."</br>"; 
		if ($mode!='annuler')
			$this->f->layout->display_message('valid', $this->msg);		
		
	}

	// ==================================
	// methode de recuperation de donnees
	// ==================================

	// recupère bureau
	function get_bureau($election, $affichage, $bureau){
		// on recherche les bureaux affiches et on fait les cumuls pour election
		$sql = "select tranche.libelle as tranche,  bureau.libelle, ";
		$sql .= " inscrit, participation_bureau.votant as participation, exprime, nul, blanc ";  
		$sql .= " from ".DB_PREFIXE."election_bureau inner join ";
		$sql .= DB_PREFIXE."bureau on election_bureau.bureau=bureau.bureau ";
		$sql .= " inner join ".DB_PREFIXE."participation_bureau on participation_bureau.election_bureau=election_bureau.election_bureau ";
		$sql .= " inner join ".DB_PREFIXE."participation_election on participation_election.participation_election=participation_bureau.participation_election ";
		$sql .= " inner join ".DB_PREFIXE."tranche on participation_election.tranche=tranche.tranche ";
        $sql .= " where election_bureau.election=".$election;
        $sql .= " and election_bureau.bureau=".$bureau." and participation_election.envoi_".$affichage." is true ";;
        $sql .= " order by tranche.ordre ";
        // $this->addToMessage($sql);    
        $res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$k = 0;
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){
			$inscrit = $row['inscrit'];
			if ($row['inscrit'] == 0) //division par 0
			   $taux = "0.00%";
			else
			   $taux= number_format (round ($row['participation'] * 100 / $row['inscrit'], 2),2)."%";
			//
			$participation [$k] = array (
				'heure' => $row ['tranche'], 
				'votants' => $row ['participation'],
				'tx' => $taux);
            $k++;
			$votant=$row["votant"];
			$exprime=$row["exprime"];
			$nul=$row["nul"];
			$blanc=$row["blanc"];
			$libelle=$row["libelle"];
		}
		 
		$participation['votant']=$votant;
		$participation['exprime']=$exprime;
		$participation['nul']=$nul;
		$participation['blanc']=$blanc;
		$participation['inscrit']=$inscrit; 
		$participation['libelle']=$libelle; 
		return $participation; 
	}

	// recupere les participations de l election
	function get_participations($election, $inscrits, $affichage){			
        $sql = "select tranche.libelle,participation_election_votant.votant  ";
        $sql .= " from ".DB_PREFIXE."participation_election inner join ".DB_PREFIXE."tranche ";
        $sql .= " on tranche.tranche = participation_election.tranche ";
        $sql .= " inner join ".DB_PREFIXE."participation_election_votant ";
        $sql .= " on participation_election_votant.participation_election = participation_election.participation_election ";
        $sql .= " where election='".$election."' and participation_election.envoi_".$affichage." is true ";
        $sql .= " order by tranche.ordre";
        //      
        $i=0;
        $res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);		
		while ($row =& $res -> fetchRow ()){
			$participations [$i] = array (
				'heure' => $row [0], 
				'votants' => $row [1], 
				'tx' => number_format (round ($row[1] * 100 / $inscrits, 2), 2)."%");
			$i++;
		}	 
		return $participations;
	}


	

    /**
     * ecriture du fichier
     */
    function write_file($path, $content) {
        $error = false;
        $parent_folder = dirname($path);
        if (!file_exists($parent_folder)) {
            @$ret = mkdir($parent_folder);
            if ($ret == false) {
                $error = true;
            }
        }
        @$inf = fopen($path, "w");
        if ($inf == false) {
            $error = true;
        } else {
            @$ret = fwrite($inf, $content);
            if ($ret == false) {
                $error = true;
            } else {
                @$ret = fclose($inf);
                if ($ret == false) {
                    $error = true;
                }
            }
        }
               
        if($error==true){
			$this->msg= _("erreur d'ecriture");
			$this->f->layout->display_message('error', $this->msg);
		}
		 
    }
    
    // =========================================================================
    // action : annuler les resultats d'un bureau dans la base, affichage et web
    // =========================================================================
 	function annuler_resultat() {     
		$participation_election=$this->getval('participation_election');
		$this->msg="";
		$this->f->db->autoCommit(false);
		// remise participation_bureau a null dans la base
		// dans election_bureau
		$sql = " update ".DB_PREFIXE."participation_election ";
		$sql .= " set  envoi_aff = false, envoi_web=false ";
		$sql .= " where participation_election.participation_election = ".$participation_election;
		$res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$this->msg .= _("annulation dans participation election")."</br>"; 
		// dans election_resultat
		$sql = " update ".DB_PREFIXE."participation_bureau ";
		$sql .= " set  votant = null ";
		$sql .= " where participation_bureau.participation_election = ".$participation_election;
		$res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$this->f->db->commit();
		$this->msg .= _("annulation des votants dans participation_bureau")."</br>"; 
		// met a jour affichage du bureau
		$this->affichage('annuler');
		// annule bureau sur le web	
		$this->web('annuler');	
		// message
		$this->f->layout->display_message('valid', $this->msg);
	}
}
