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

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

class election_candidat extends election_candidat_gen {

	var $idxformulaire;

    function init_class_actions() {
        parent::init_class_actions();    

		// verrou supprimer
		$this->class_actions[2]["condition"][1] = 'is_not_verrou';
		$this->class_actions[0]["condition"][1] = 'is_not_verrou';
       
         $this->class_actions[5] = array(
            "identifier" => "resultat",
            "portlet" => array(
                "type" => "action-direct-with-confirmation",
                "libelle" => _("creer resultat du candidat"),
                "order" => 60,
                "class" => "edit-16",
            ),
            "view" => "formulaire",
            "method" => "insert_election_resultat",
            "button" => "diffuser",
            "permission_suffix" => "tab",
            "condition" => array(
                "is_not_creation_resultat")
        );
	}

    function setType(&$form, $maj) {
		parent::setType($form, $maj);
		if($maj==0){
			$form->setType('creation_resultat',"checkboxstatic");
			$form->setType('siege',"hiddenstatic");
			$form->setType('siege_com',"hiddenstatic");
		}

	}

    function setValsousformulaire(&$form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire, &$dnu1 = null, $dnu2 = null) {
        $this->idxformulaire = $idxformulaire; // necessaire pour valeur par defaut
		parent::setValsousformulaire($form, $maj, $validation, $idxformulaire, $retourformulaire, $typeformulaire, $dnu1, $dnu2);
		
    }


	function set_form_default_values(&$form, $maj, $validation){
		// calcul du dernier + 1 numero d'ordre des candidats dans l'election 
		if($validation==0 and $maj==0 ){
			if($this->is_in_context_of_foreign_key('election', $this->retourformulaire)){
				if($this->idxformulaire != 0){
					$sql= "select max(ordre) from ".DB_PREFIXE."election_candidat ";
					$sql .= " where election = ".$this->idxformulaire;
					$res = $this->db->getOne($sql);
					$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
					$this->f->isDatabaseError($res);			
					$form->setVal('ordre',$res+1);
				}
			}
		}
	}	

	function insert_election_resultat() { 
		$this->setValFFromVal();
		// verification d existence de resultat
		$sql = "select count(election_resultat) from ".DB_PREFIXE."election_resultat ";
		$sql .= " inner join ".DB_PREFIXE."election_candidat ";
		$sql .= " on election_candidat.election_candidat=election_resultat.election_candidat ";
		$sql .= " where election_candidat.election = ".$this->valF['election'];
		$sql .= " and  election_candidat.election_candidat = ".$this->valF['election_candidat'];
		$election_resultat = $this->db->getOne($sql);
		$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);		
		$this->f->isDatabaseError($election_resultat);
		if($election_resultat==0){
			$i=0;
			$correct=true;
			require_once '../obj/election_resultat.class.php';
			$this->f->db->autoCommit(false);		
			$sql= "select election_bureau.election_bureau from ".DB_PREFIXE."election_bureau ";
			$sql .= " where election = ".$this->valF['election'];
			$sql .= " order by election_bureau.election_bureau ";
			//$this->addToMessage(_($sql));
			$res = $this->db->query($sql);
			$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
			$this->f->isDatabaseError($res);
			while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC) ){		
				$election_resultat = new election_resultat("]", $db, $DEBUG);
				$valF["election_bureau"]=$row['election_bureau'];
				$valF["election_candidat"]=$this->valF['election_candidat'];
				$ret = $election_resultat->ajouter($valF);
				// Si le traitement ne s'est pas déroulé correctement
				if ($ret !== true) {
					// Return
					$this->addToMessage(_("resultat")." ".$row['election_bureau']." "._("non cree."));
					$correct=false;
				}else{
					//$this->addToMessage($row['election_bureau']." "._('cree'));
					$i++;
				}			
			}					
			if($correct){			
				// creation_bureau a true
				if ($this->getVal('creation_resultat')== 'f' and $i>0){
					$sql = "update  ".DB_PREFIXE."election_candidat set creation_resultat=true where election_candidat=".
					$this->valF['election_candidat'];			      
					$res = $this-> db -> query ($sql);
					$this->addToLog(__METHOD__."(): db->query(\"".$sql."\");", VERBOSE_MODE);
					$this->f->isDatabaseError($res);				 
					$this->addToMessage(_("creation_resultat = true"));			
				}
				$class='valid';
				$this->f->db->commit();
			}else
				$class='error';
			$this->addToMessage($i." "._("election resultat crees"));
			if($i==0)
				$this->addToMessage(_("verifiez que les bureaux ont ete crees pour l'election"));
		}else{
			$this->addToMessage(_("il y a")."  ".$election_resultat." "._("resultat(s)  existant(s) pour ce candidat").
					" -> "._("creation non effectuéé"));		
			$class='valid';
		} 
		$this->f->layout->display_message($class, $this->msg);
	}

    function setLib(&$form, $maj) {
		//libelle des champs
		parent::setLib($form, $maj);
        $form->setLib('prefecture', __('code candidat prefecture'));
        $form->setLib('creation_resultat', __('resultat deja crees'));
        $form->setLib('age_moyen', __('age moyen de la liste municipale'));
        $form->setLib('siege', __('siege de la liste municipale (calcule)'));
        $form->setLib('age_moyen_com', __('age moyen de la liste communautaire'));
        $form->setLib('siege_com', __('siege de la liste communautaire (calcule)'));
    }

    function setLayout(&$form, $maj) { 
			$form->setFieldset('election_candidat','D',_('Candidats'), "collapsible");			
			$form->setFieldset('creation_resultat','F','');
			$form->setFieldset('age_moyen','D',_('Listes Municipales'), "startClosed");
			$form->setFieldset('sieges_com','F','');  
	}


    function is_not_creation_resultat() {
        //
        $etat = $this->getVal("creation_resultat");
        if ($etat== 't' ) {
            return false;
        }
        return true;
    }

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




}
