<?php
//$Id$ 
//gen openMairie le 30/05/2019 16:10

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

class election_bureau extends election_bureau_gen {

	var $nombre_candidat;
	var $election;
	var $candidats;



    function __construct($id, &$dnu1 = null, $dnu2 = null) {
        $this->constructeur($id);
        // calcul du nombre de candidat pour affichage
		if($id!="]"){			
			$this->election=$_GET['idxformulaire']; 
			$sql  = "select count(election_candidat) from ".DB_PREFIXE."election_candidat ";
			$sql .= " where 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,"candidat".$i);
				array_push($this->champs,"id".$i);
			}
			$this->nombre_candidat=$res;
		}
    }

    function init_class_actions() {
        parent::init_class_actions(); 
        
        // verrou supprimer
		$this->class_actions[2]["condition"][1] = 'is_not_verrou';
           
		// envoi a l affichage
        $this->class_actions[4] = array(
            "identifier" => "affichage",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("affichage bureau"),
                "order" => 50,
                "class" => "arrow-right-16",
            ),
            "view" => "formulaire",
            "method" => "affichage",
            "permission_suffix" => "tab",
        );        
           
		// envoi sur le web
        $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",
            "permission_suffix" => "tab",
        );  

		// remise a zero
        $this->class_actions[6] = array(
            "identifier" => "remiseazero",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("annuler les resultats"),
                "order" => 70,
                "class" => "delete-16",
            ),
            "view" => "formulaire",
			"method" => "annuler_resultat",
            "permission_suffix" => "tab",
        );  
        

    
	}

    /**
     *
     * @return string
     */
    function get_var_sql_forminc__sql_bureau() {
        return "SELECT bureau.bureau, concat(bureau.ordre, ' - ', bureau.libelle) as lib FROM ".DB_PREFIXE."bureau ORDER BY bureau.ordre ASC";
    }

    /**
     *
     * @return string
     */
    function get_var_sql_forminc__sql_bureau_by_id() {
        return "SELECT bureau.bureau, concat(bureau.ordre, ' - ', bureau.libelle) as lib FROM ".DB_PREFIXE."bureau WHERE bureau = <idx>";
    }



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


	function set_form_default_values(&$form, $maj, $validation){
		// recuperation des identifiants candidats et des resultats
		if($validation==0 and $maj==1){
			// identifiant candidat
			$sql= "select election_candidat from ".DB_PREFIXE."election_candidat ";
			$sql .= " where election_candidat.election = ".$this->getVal('election'); 
			$sql .= " order by election_candidat.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_candidat']);
			}
			
			// resultat d election_resultat
			$sql  = " select election_resultat.resultat from ".DB_PREFIXE."election_resultat ";
			$sql .= " inner join ".DB_PREFIXE."election_candidat on election_resultat.election_candidat = election_candidat.election_candidat ";
			$sql .= " where election_candidat.election = ".$this->getVal('election'); 
			$sql .= " and election_bureau = ".$this->getVal('election_bureau');
			$sql .= " order by election_candidat.ordre ";
			//echo $sql;
			$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('candidat'.$i,$row['resultat']);
			}			 			 
		}
	}


    function setLib(&$form, $maj) {
        parent::setLib($form, $maj);
        // changement du libelle des candidats
        $sql= "select candidat.libelle from ".DB_PREFIXE."election_candidat ";
        $sql .= " inner join ".DB_PREFIXE."candidat on candidat.candidat = election_candidat.candidat ";
        $sql .= " where election_candidat.election = ".$this->getVal('election'); 
        $sql .= " order by 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('candidat'.$i,$row['libelle']." : ");
			$this->candidats[$i]=$row['libelle'];
		}
		if($maj==3){
			$form->setLib('election_bureau','');
			$form->setLib('bureau','');
			$form->setLib('election','');
			
		}
     }

    function setLayout(&$form, $maj) { 
		if($maj==3){
			$form->setBloc('election_bureau','D',"","col_4"); // bloc 
				$form->setFieldset('election_bureau','D',_('Election'), "collapsible");			
				$form->setFieldset('bureau','F','');
			$form->setBloc('bureau','F',''); 
			$form->setBloc('inscrit','D',"","col_3"); // bloc 
				$form->setFieldset('inscrit','D',_('resultat du bureau'), "collapsible");
				$form->setFieldset('exprime','F',''); 
			$form->setBloc('exprime','F','');     // fin bloc 
			$form->setBloc('envoi_aff','D',"","col_2"); // bloc 
				$form->setFieldset('envoi_aff','D',_('envoi'), "collapsible");
				$form->setFieldset('envoi_web','F',''); 
			$form->setBloc('envoi_web','F','');
		}
	}

    function triggermodifier($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
		// update d election_resultat : resultat du candidat dans le bureau
		// calcul exprime
		$exprime = 0;
		$this->msg .=_("résultats enregistrés")." : "."</br>";
		for($i=1; $i <= $this->nombre_candidat ; $i++){	
			if(is_numeric($val["candidat".$i])){
				$resultat=$val["candidat".$i];
				$exprime = $exprime + $resultat;
			}else
				$resultat=0;
			$sql  = " update ".DB_PREFIXE."election_resultat set resultat=".$resultat;
			$sql .= " where election_bureau = ".$this->valF['election_bureau'];
			$sql .= " and election_candidat = ".$val["id".$i]; 
			$res = $this->db->query($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			if($this->db->affectedRows()>0)
				$this->msg .= " - ".$val["id".$i]." - ".$this->candidats[$i]." = ".$resultat."</br>";
			else{				
				$this->msg .= '<b>'._("pas d'ajout de ".$resultat.
				" dans election_résultat -> vérifier la création de résultat dans candidat").'</b></br>';
			}		
		}	
		$this->valF['exprime']=$val['votant']-$val['nul']-$val['blanc'];
		if($this->valF['exprime']!=$exprime){
			$temp=$this->valF['exprime']-$exprime;
			$this->msg .= "<b><u>"._("ATTENTION")." :</u> "._("il y a un ecart de")." ".$temp." ".
				_("entre exprimés")." : ".$exprime." "._("et votant-null-blanc").
				" : ".$this->valF['exprime']."</b></br>";
		}else
			$this->msg .="<b>"._("total exprimés")." ".$exprime."</b></br>";
			
    }

    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 standard
	// envoi de fichiers affichage
	// =============================

    /**
    * Permet de mettre à jour les fichiers  du dossier : "aff/res/".$election."/bres/"
    * b."codebureau".inc , election.inc, last.inc, bureaux.inc, resultats.inc
    */
    function affichage ($mode=null){	
		// creation du repertoire election si il n existe pas a voir creation election		
        // On récupère le libelle du bureau 
        $this->msg .= '<b>'._("envoi a l'affichage")."</b></br>";   
        // 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'){
			$this->f->db->autoCommit(false);
			$sql = "update  ".DB_PREFIXE."election_bureau set envoi_aff=true where election_bureau=".
			$this->valF['election_bureau'];        
			$res = $this-> db -> query ($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$this->addToMessage(_("envoi affichage = true"));
			$this->f->db->commit();				
		}
		// ========
		// bXXX.inc
		// ========*
		//$bureau_libelle = "1 - Mairie";
		//$inscrit = "100";
		//$votant = "80";
		//$exprime = "60";
		//$blanc = "10";
		//$nul = "10";
		//$candidat [1] = array ('nom' => "Gilbert MATHIEU",'prenom' => "Liste pour le renouveau",'voix' => "50",'tx' => "83.33%");		
		// libelle bureau	
        $bureau_libelle = $this-> get_bureau_libelle ($this->valF['bureau']);
        $temp= explode( " - ", $bureau_libelle);
        $ordre=$temp[0];
        
        // resultat dans election candidat suivant ordre
		$candidat = $this->get_candidats_bureau($this->valF['election'], 
												$this->valF['election_bureau'],
												$this->valF['exprime']);
		$contenu = "<?php\n";
		$contenu .= "\$bureau_libelle = \"".$bureau_libelle."\";\n";
		$contenu .= "\$inscrit = \"".$this->valF['inscrit']."\";\n";
		$contenu .= "\$votant = \"".$this->valF['votant']."\";\n";
		$contenu .= "\$exprime = \"".$this->valF['exprime']."\";\n";
		$contenu .= "\$blanc = \"".$this->valF['blanc']."\";\n";
		$contenu .= "\$nul = \"".$this->valF['nul']."\";\n";
		foreach ($candidat as $key => $value){
			if(is_numeric($key))
				$contenu .= "\$candidat [".$key."] = array (
					'nom' => \"".$value ['nom']."\",
					'prenom' => \"".$value ['prenom']."\",
					'voix' => \"".$value ['voix']."\", 
					'tx' => \"".$value ['tx']."\");\n";
		}
		$contenu .= "?>";
		$envoi=$this->write_file("../aff/res/".$this->valF['election']."/bres/b".$ordre.".inc", $contenu);
		$this->msg .="../aff/res/".$this->valF['election']."/bres/b".$ordre.".inc envoye"."</br>";
		// =========================
		// last.inc (dernier bureau)
		// =========================
		$contenu = $this->valF['bureau'];
		$envoi=$this->write_file("../aff/res/".$this->valF['election']."/last.inc", $contenu);
		$this->msg .="../aff/res/".$this->valF['election']."/last.inc envoye"."</br>";
		// fichiers communs
		$bureau=$this->affichage_bureaux($this->valF['election']);
		$exprime=$this->affichage_election($this->valF['election'],$bureau);
		$this->affichage_resultats($this->valF['election'],$exprime);
		$this->f->layout->display_message('valid', $this->msg); 
    }

	function desaffichage (){	
        // On récupère le libelle du bureau 
        $this->msg .='<b>'._("desaffichage")."</b>"."</br>";     
        $this->setValFFromVal();
		// ========
		// bXXX.inc
		// ========
        $bureau_libelle = $this-> get_bureau_libelle ($this->valF['bureau']);
        $temp= explode( " - ", $bureau_libelle);
        $ordre=$temp[0];
        if (file_exists("../aff/res/".$this->valF['election']."/bres/b".$ordre.".inc")){
			unlink("../aff/res/".$this->valF['election']."/bres/b".$ordre.".inc");
			$this->msg .="../aff/res/".$this->valF['election']."/bres/b".$ordre.".inc supprime"."</br>";
		}
		// fichiers communs
		$bureau=$this->affichage_bureaux($this->valF['election']);
		$exprime=$this->affichage_election($this->valF['election'],$bureau);
		$this->affichage_resultats($this->valF['election'],$exprime);		 
    }


	// ============================
	// bureaux.inc (bureau arrives)
	// ============================
	// $bureau [1] = array ('code' => "1",'etat' => "1", 'lib' => "Mairie");
	// on recherche les bureaux affiches et on fait les cumuls
	function affichage_bureaux($election){
		$bureau= $this->get_bureaux($election, "aff");           		
        $contenu = "<?php\n";
        foreach ($bureau as $key => $value){
			if(is_numeric($key))
				$contenu .= "\$bureau [".$key."] = array ('code' => \"".
							$key."\",'etat' => \"".$value ['etat']."\", 'lib' => \"".
							$bureau [$key]['lib']."\");\n";
        }
        $contenu .= "?>";                
		$envoi=$this->write_file("../aff/res/".$election."/bureaux.inc", $contenu);
		$this->msg .="../aff/res/".$election."/bureaux.inc envoye"."</br>"; 
		return $bureau;			      
	}

	// =====================
	// election.inc (global)
	// =====================
	function affichage_election($election, $bureau){
		// libelle election
        $sql = "select libelle from ".DB_PREFIXE."election where election=".$election;        
        $election_libelle = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($election_libelle);
		// reprise des cumuls des bureaux arrives
        $contenu = "<?php\n";
        $contenu .= "\$election = \"".$this->get_election_libelle($election)."\";\n";
        $contenu .= "\$bureauxarrives = \"".$bureau['bureaux_arrives']."\";\n";
        $contenu .= "\$bureauxtot = \"".$bureau['bureaux_total']."\";\n";
        $contenu .= "\$inscrits = \"".$bureau['inscrits']."\";\n";
        $contenu .= "\$votants = \"".$bureau['votants']."\";\n";
        $contenu .= "\$blancs = \"".$bureau['blancs']."\";\n";
        $contenu .= "\$nuls = \"".$bureau['nuls']."\";\n";
        $contenu .= "\$exprimes = \"".$bureau['exprimes']."\";\n";
        $contenu .= "\$inscritsbureauxarrives = \"".$bureau['inscritsbureauxarrives']."\";\n";
        $contenu .= "?>";
		$envoi=$this->write_file("../aff/res/".$election."/election.inc", $contenu);
		$this->msg .="../aff/res/".$election."/election.inc envoye"."</br>"; 
		return $bureau['exprimes'];
	}

	// =========================    		
	// resultats.inc (candidats)
	// =========================
	// $candidats [1] = array ('photo' => "1.jpg", 'code' => "202", 'nom' => "PIES", 'prenom' => "Valere", 'parti' => "DIV",'voix' => "200", 'tx' => "42.42%"); 	
	function affichage_resultats($election, $exprime){
        $candidats= $this->get_candidats_election($election, $exprime, "aff");
        $contenu = "<?php\n";
        foreach ($candidats as $key => $value){
			$contenu .= "\$candidats [".$key."] = array ('photo' => \"".$value ['ordre'].".jpg"."\", 'code' => \"";
			if (isset($value ['ordre'])) 
				$contenu .= "".$value ['ordre']."";
			$contenu .= "\", 'nom' => \"";
			if (isset($value ['nom'])) 
				$contenu .= "".$value ['nom']."";
			$contenu .= "\", 'prenom' => \"";
			if (isset($value ['prenom'])) 
				$contenu .= "".$value ['prenom']."";
			$contenu .=  "\", 'parti' => \"";
			if (isset($value ['parti'])) 
				$contenu .= "".$value ['parti']."";
			$contenu .=  "\", 'voix' => \"";
			if (isset($value ['voix'])) 
				$contenu .= "".$value ['voix']."";
			$contenu .=  "\", 'tx' => \"";
			if (isset($value ['tx'])) 
				$contenu .= "".$value ['tx']."";
			//$contenu .= "%\");\n";
			$contenu .= "\");\n";
			}
        $contenu .= "?>";	
		$envoi=$this->write_file("../aff/res/".$election."/resultats.inc", $contenu);
		$this->msg .="../aff/res/".$election."/resultats.inc envoye"."</br>";
    }
    
    
    /**
    * Permet de mettre à jour les fichiers  du dossier : "web/res/".$election."/bres/"
    * b."codebureau".html , election.inc,  bureau.inc, collectivite.inc
    */


	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();
        $this->msg .= '<b>'._("envoi sur le web")."</b></br>";
        // envoi web a true
        if ($this->valF['envoi_web']== 'f'){
			$this->f->db->autoCommit(false);
			$sql = "update  ".DB_PREFIXE."election_bureau set envoi_web=true where election_bureau=".
			$this->valF['election_bureau'];        
			$res = $this-> db -> query ($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			$this->msg .=_("envoi web = true")."</br>";
			$this->f->db->commit();				
		}
		// =================
		// bureau bxxx.html
		// =================
        $bureau_libelle=htmlentities($this->get_bureau_libelle($this->valF['bureau']));
        $temp= explode( " - ", $bureau_libelle);
        $ordre=$temp[0];
        $candidat= $this->get_candidats_bureau($this->valF['election'],$this->valF['election_bureau'],$this->valF['exprime']);
        $contenu = "<font SIZE=4 color=#E61313>\n";
        $contenu .= "<b>\n";
        $contenu .= $bureau_libelle."\n";       
        $contenu .= "</b>\n";
        $contenu .= "</font>\n";
        $contenu .= "<br>\n";
        $contenu .= "Inscrits: ";
        $contenu .= $this->valF['inscrit']."\n";
        $contenu .= "<br>\n";
        $contenu .= "Votants: ";
        $contenu .= $this->valF['votant']."\n";
        $contenu .= "<br>\n";
        $contenu .= "Blancs: ";
        $contenu .= $this->valF['blanc']."\n";
        $contenu .= "<br>\n";
        $contenu .= "Nuls: ";
        $contenu .= $this->valF['nul']."\n";
        $contenu .= "<br>\n";
        $contenu .= "Exprim&eacute;s: ";
        $contenu .= $this->valF['exprime']."\n";
        $contenu .= "<br>\n";
        $contenu .= "<table border=1  width=290 cellpadding=2 cellspacing=0 bordercolor=#395683 style='font-size:10pt;font-weight: bold;color: #000066'>\n";
        $contenu .= "<tr>\n";
        $contenu .= "<td valign=middle align=left bgcolor=#C7DCFC>\n";
        $contenu .= "Candidats\n";
        $contenu .= "</td>\n";
        $contenu .= "<td valign=middle align=right bgcolor=#C7DCFC>\n";
        $contenu .= "Voix\n";
        $contenu .= "</td>\n";
        $contenu .= "<td valign=middle align=right bgcolor=#C7DCFC>\n";
        $contenu .= "%\n";
        $contenu .= "</td>\n";
        $contenu .= "</tr>\n";
		for ($i = 1; $i <= $candidat ['nb_candidat']; $i++){	
            $contenu .= "<tr>\n";
            $contenu .= "<td valign=middle align=left>\n";
            $contenu .= $candidat[$i]['nom']." ".$candidat[$i]['prenom']."\n";
            $contenu .= "</td>";
            $contenu .= "<td valign=middle align=right>\n";
            $contenu .= $candidat[$i]['voix']."\n";
            $contenu .= "</td>";
            $contenu .= "<td valign=middle align=right>\n";
            $contenu .= $candidat[$i]['tx']."\n";
            $contenu .= "</td>";
            $contenu .= "</tr>\n";
        }
        $contenu .= "</table>\n";		
		$envoi=$this->write_file("../web/res/".$this->valF['election']."/b".$ordre.".html", $contenu);
		$this->msg .= "../web/res/".$this->valF['election']."/b".$ordre.".html envoye"."</br>";
		// fichiers communs
		$bureau=$this->web_bureau($this->valF['election']);
		$this->web_collectivite($this->valF['election'],$bureau);
		$this->web_election($this->valF['election'],$bureau, $candidat);
		//
		$this->f->layout->display_message('valid', $this->msg);  
			
	}

	// cette méthode annule un envoi  de bxxx.html sur le web
	function annuler_web(){
		$this->setValFFromVal();
        $this->msg .='<b>'._("suppression sur le web")."</b>"."</br>";
		// =================
		// bureau bxxx.html
		// =================
        $bureau_libelle=htmlentities($this->get_bureau_libelle($this->valF['bureau']));
        $temp= explode( " - ", $bureau_libelle);
        $ordre=$temp[0];
        if (file_exists("../web/res/".$this->valF['election']."/b".$ordre.".html")){
			unlink("../web/res/".$this->valF['election']."/b".$ordre.".html");
			$this->msg .="../web/res/".$this->valF['election']."/b".$ordre.".html supprime"."</br>";
		}		
		// fichiers communs
		$bureau=$this->web_bureau($this->valF['election']);
		$this->web_collectivite($this->valF['election'],$bureau);
		$this->web_election($this->valF['election'],$bureau, $candidat);
	}

	// ==========
	// bureau.inc
	// ==========	
	function web_bureau($election){ 
		$bureau = $this->get_bureaux($election,'web');
        $contenu = "<?php\n";
        foreach ($bureau as $key => $value){
			if(is_numeric($key)) // que les bureaux
				$contenu .= "\$bureau [".$key."] = array ('code' => \"".$key."\",'etat' => \"".$value ['etat']."\", 'obj' => \"\", 'positionx' => \"\",'positiony' => \"\");\n";
        }
        $contenu .= "?>";		
		$envoi=$this->write_file("../web/res/".$election."/bureau.inc", $contenu);
		$this->msg .="../web/res/".$election."/bureau.inc envoye"."</br>"; 
		return $bureau;
	}
			
	// ================
	// collectivite.inc
	// ================
    function web_collectivite($election,$bureau){
        $contenu = "<?php\n";
        $contenu .= "\$inscrits = \"".$bureau['inscrits']."\";\n";
        $contenu .= "\$votants = \"".$bureau['votants']."\";\n";
        $contenu .= "\$blancs = \"".$bureau['blancs']."\";\n";
        $contenu .= "\$nuls = \"".$bureau['nuls']."\";\n";
        $contenu .= "\$exprimes = \"".$bureau['exprimes']."\";\n";
        $candidats= $this->get_candidats_election($election,$bureau['exprimes'], "web");
        foreach ($candidats as $key => $value) {
            $contenu .= "\$candidats [".$key."] = array (
                'photo' => \"".$value ['photo']."\", 
                'code' => \"".$value ['ordre']."\",
                'nom' => \"".$value ['nom']."\",
                'prenom' => \"".$value ['prenom']."\",
                'parti' => \"\",
                'voix' => \"".$value ['voix']."\", 
                'tx' => \"".$value ['tx']."\");\n";
        }
        $contenu .= "?>";
		$envoi=$this->write_file("../web/res/".$this->valF['election']."/collectivite.inc", $contenu);
		$this->msg .= "../web/res/".$this->valF['election']."/collectivite.inc envoye"."</br>";	
	}
				
	// ============
	// election.inc
	// ============	
	function web_election($election, $bureau, $candidat){
        $contenu = "<?php\n";
        $contenu .= "\$election_libelle = \"".$this->get_election_libelle($election)."\";\n";
        $contenu .= "\$election_date = \"".$this->get_election_date($election)."\";\n";
        $contenu .= "\$nbcandidat = \"".$candidat ['nb_candidat']."\";\n";
        $contenu .= "\$bureau_arr = \"".$bureau['bureaux_arrives']."\";\n";
        $contenu .= "\$bureau_tot = \"".$bureau['bureaux_total']."\";\n";
        $contenu .= "?>";
		$envoi=$this->write_file("../web/res/".$election."/election.inc", $contenu);
		$this->msg .= "../web/res/".$election."/election.inc envoye"."</br>";
	}


	// ==================================================================
	// methodes communes de recuperation de donnees pour affichage et web
	// ==================================================================

	// libelle du bureau
	function get_bureau_libelle($bureau){
        $sql = "select libelle from ".DB_PREFIXE."bureau where bureau=".$bureau;        
        $bureau_libelle = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($bureau_libelle);	
		
        $sql = "select ordre from ".DB_PREFIXE."bureau where bureau=".$bureau;        
        $bureau_ordre = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($bureau_libelle);
		$bureau_libelle2=$bureau_ordre." - ".$bureau_libelle;
		$this->msg .=_("bureau")." ".$bureau_libelle2."</br>";
		return $bureau_libelle2;	
	}


    // candidat pour un bureau  
    // nom, prenom, resultat, taux     
    function get_candidats_bureau($election, $bureau, $exprime){
		if ($exprime == 0) $exprime = 1; // division par 0
        $sql = "select election_candidat.ordre, candidat.libelle, candidat.libelle_long, ";
        $sql .= " election_resultat.resultat ";
        $sql .= " from ".DB_PREFIXE."election_candidat ";
        $sql .= " inner join ".DB_PREFIXE."candidat "; 
        $sql .= " on election_candidat.candidat=candidat.candidat ";
        $sql .= " inner join ".DB_PREFIXE."election_resultat "; 
        $sql .= " on election_resultat.election_candidat=election_candidat.election_candidat ";
        $sql .= " where election_candidat.election=".$election;
        $sql .= " and election_resultat.election_bureau=".$bureau;
        $sql .= " order by election_candidat.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++;
			$candidat [$i]['nom'] = $row ['libelle'];
            $candidat [$i]['prenom'] = $row ['libelle_long'];
            $candidat [$i]['ordre'] = $row ['ordre'];
            $candidat [$i]['voix'] = $row ['resultat'];
            $candidat [$i]['tx'] = number_format (round ($row ['resultat'] * 100 / $exprime, 2), 2)."%";           
        }
        $candidat ['nb_candidat']=$i;
		return $candidat;		 
    }

    // candidat pour l election  
    // nom, prenom, resultat, taux     
    function get_candidats_election($election, $exprime, $affichage){
		if ($exprime == 0) $exprime = 1; // division par 0
        // requete en fonction des bureaux envoyés à l'affichage ou sur le web
        $sql = "select election_candidat.ordre, candidat.libelle, candidat.libelle_long, ";
        $sql .= " sum(election_resultat.resultat) as resultat ";
        $sql .= " from ".DB_PREFIXE."election_candidat ";
        $sql .= " inner join ".DB_PREFIXE."candidat "; 
        $sql .= " on election_candidat.candidat=candidat.candidat ";
        $sql .= " inner join ".DB_PREFIXE."election_resultat ";
        $sql .= " on election_resultat.election_candidat=election_candidat.election_candidat "; 
        $sql .= " inner join ".DB_PREFIXE."election_bureau "; 
        $sql .= " on election_resultat.election_bureau=election_bureau.election_bureau ";
        $sql .= " where election_candidat.election=".$election;
        $sql .= " and election_bureau.envoi_".$affichage." is true "; 
        $sql .= " group by election_candidat.ordre, candidat.libelle, candidat.libelle_long"; 
        $sql .= " order by election_candidat.ordre";
        //$this->addToMessage($sql);         
        $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++;
			$candidats [$i]['nom'] = $row ['libelle'];
            $candidats [$i]['prenom'] = $row ['libelle_long'];
            $candidats [$i]['ordre'] = $row ['ordre'];
            $candidats [$i]['voix'] = $row ['resultat'];
            $candidats [$i]['photo'] = $i.".jpg";
            $candidats [$i]['tx'] = number_format (round ($row ['resultat'] * 100/ $exprime, 2), 2)."%";           
        }
		return $candidats;		 
    }

	// bureaux arrives + totaux arrives
	function get_bureaux($election, $affichage){
		// on recherche les bureaux affiches et on fait les cumuls pour election
		$sql = "select bureau.ordre, election_bureau.envoi_".$affichage." as envoi, bureau.libelle, ";
		$sql .= " inscrit, votant, exprime, nul, blanc ";  
		$sql .= " from ".DB_PREFIXE."election_bureau inner join ";
		$sql .= DB_PREFIXE."bureau on election_bureau.bureau=bureau.bureau ";
        $sql .= " where election=".$election." ";
        $sql .= " order by bureau.ordre ";
        $res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$bureaux_total=0;
		$bureaux_arrives=0;
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){
			$bureau [$row["ordre"]]['lib'] = $row ["libelle"];
			$bureau [$row["ordre"]]['etat'] = 0;
			$bureaux_total++;
			if($row["envoi"]=='t'){
				$bureau [$row["ordre"]]['etat'] = 1;
				// cumul bureaux arrives pour election.inc
				$bureaux_arrives++;				
				$inscritsbureauxarrives=$inscritsbureauxarrives+$row["inscrit"];
				$votants=$votants+$row["votant"];
				$exprimes=$exprimes+$row["exprime"];
				$nuls=$nuls+$row["nul"];
				$blancs=$blancs+$row["blanc"];
			}else{
				$bureau [$row["ordre"]]['etat'] = 0;
			}
			$inscrits=$inscrits+$row["inscrit"];
		}
		$bureau['bureaux_total']=$bureaux_total;
		$bureau['bureaux_arrives']=$bureaux_arrives;
		$bureau['inscritsbureauxarrives']=$inscritsbureauxarrives;
		$bureau['votants']=$votants;
		$bureau['exprimes']=$exprimes;
		$bureau['nuls']=$nuls;
		$bureau['blancs']=$blancs;
		$bureau['inscrits']=$inscrits;
		return $bureau; 
	}

	// libelle election
	function get_election_libelle($election){
		// libelle election
        $sql = "select libelle from ".DB_PREFIXE."election where election=".$election;        
        $election_libelle = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($election_libelle);
		return $election_libelle;
	}

	// date de l election
	function get_election_date($election){
		// libelle election
        $sql = "select date from ".DB_PREFIXE."election where election=".$election;        
        $election_libelle = $this-> db -> getOne ($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
		$this->f->isDatabaseError($election_libelle);
		return $election_libelle;
	}

    /**
     * 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() {     
		$election_bureau=$this->getval('election_bureau');
		$this->msg="";
		$this->f->db->autoCommit(false);
		// remise bureau a null dans la base
		// dans election_bureau
		$sql = " update ".DB_PREFIXE."election_bureau ";
		$sql .= " set  votant = null, exprime= null, nul =null, blanc=null, envoi_aff = false, envoi_web=false ";
		$sql .= " where election_bureau.election_bureau = ".$election_bureau;
		$res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$this->msg .= _("annulation resultat bureau")."</br>"; 
		// dans election_resultat
		$sql = " update ".DB_PREFIXE."election_resultat ";
		$sql .= " set  resultat = null ";
		$sql .= " where election_resultat.election_bureau= ".$election_bureau;
		$res = $this->db->query($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($res);
		$this->f->db->commit();
		$this->msg .= _("annulation resultat")."</br>"; 
		// annule affichage du bureau
		$this->desaffichage();
		// annule bureau sur le web	
		$this->annuler_web();	
		// message
		$this->f->layout->display_message('valid', $this->msg);
	}
    
	// =================================================================
	// affichage des resultats dans le formulaire d affichage
	// =================================================================


 	function afterSousFormSpecificContent() { 
		$maj=$this->getParameter("maj");
		if($maj==3){
			$election_bureau=$this->getVal('election_bureau'); 			
			echo "<div id=\"affichage_article\" class=\"formEntete ui-corner-all\">";  
			$this->affiche_data($election_bureau);
			echo "</div>";
		}
	}

	function affiche_data($election_bureau){
		$sql = "select election_candidat.ordre, candidat.libelle, ";
		$sql .= " election_resultat.resultat  ";
		$sql .= " from ".DB_PREFIXE."election_resultat ";
		$sql .= " left join  ".DB_PREFIXE."election_candidat on election_resultat.election_candidat=election_candidat.election_candidat " ;
		$sql .= " left join  ".DB_PREFIXE."candidat on candidat.candidat=election_candidat.candidat " ;
		$sql .= " where election_resultat.election_bureau = ".$election_bureau;
		$sql .= " order by election_candidat.ordre ";
		$res=$this->db->query($sql);
		if (database::isError($res))
		   die($res->getDebugInfo()." ".$sql);
		else {  
			$temp = _("Liste des Candidats");				
			echo "<fieldset class=\"cadre ui-corner-all ui-widget-content\"><legend>".$temp."</legend>";
			echo "<table class=\"tab-tab\">";
			echo "<tr class=\"ui-tabs-nav ui-accordion ui-state-default tab-title\">";		
			// affichage des entetes
			echo "<th class=\"title\">"._("ordre")."</th>";
			echo "<th class=\"title\">"._("candidat")."</th>";
			echo "<th class=\"title\">"._("voix")."</th>";
			echo "</tr>";
			$i=0;
			$oddeven=array("odd","even");
			$exprime=0;
			while ($line=$res->fetchrow(DB_FETCHMODE_ASSOC)) {
				echo "<tr class=\"tab-data ".$oddeven[$i%2]."\">";
				echo '<td>'.$line['ordre'].'</td>';
				echo '<td>'.$line['libelle'].'</td>';
				echo '<td style="text-align:right">'.$line['resultat'].'</td>';
				echo "</tr>";
				$exprime=$exprime+$line['resultat'];
				$i++;
			}	
			echo "<tr class=\"tab-data ".$oddeven[$i%2]."\">";	
			echo '<td></td><td>'._("Total exprime").'</td><td style="text-align:right">'.$exprime.'</td></tr>';	
			echo "</table>";
			echo "</fieldset>";	
			if($i==0)
				echo "<b>"._("les resultats election n'ont pas ete crees - voir action dans onglet candidat")."</b>";
			else
				echo $i." "._("resultat(s) candidat cree(s)"); 		
		
		}			

	}



 
}
