<?php

class TRecProcedure extends TObjetStd {
	function __construct() {
		parent::set_table(MAIN_DB_PREFIX.'rec_procedure');
		parent::add_champs('entity,active',array('type'=>'integer', 'index'=>true));
		parent::add_champs('name,description',array('type'=>'string'));
		parent::add_champs('is_default',array('type'=>'integer', 'index'=>true));
		parent::add_champs('allow_free_events', array('type'=>'integer'));
		parent::_init_vars();
		$this->start();

		//Ajout d'un tableau d'étapes lié à la procédure
		$this->setChild('TRecEtape', 'fk_procedure');
	}

	//Ajout d'une etape
	function addEtape($idEtape) {
		$iLien = $this->addChild($db, 'TRecEtape');
		$this->TRecProcedureEtape[$iLien]->fk_procedure = $idEtape;
	}

	function getLastRang(&$ATMdb){
		$sql = "SELECT MAX(rang) as rang FROM ".MAIN_DB_PREFIX."rec_etape WHERE fk_procedure = ".$this->rowid;
		$ATMdb->Execute($sql);
		$ATMdb->Get_line();
		return $ATMdb->Get_field('rang')+1;
	}

	function load(&$db, $id, $loadChild = true) {
		
		parent::load($db, $id, $loadChild);

		usort($this->TRecEtape, array('TRecProcedure','_tri_rang'));


	}

	static function _tri_rang($a, $b) {
		if ($a->rang == $b->rang)   {      return 0;   }
		else if ($a->rang < $b->rang) { return -1; }
		else { return 1; }
	}

	function getFirstEtape() {
		if(!empty($this->TRecEtape[0])) return $this->TRecEtape[0];
		else return null;

	}

	static function getListProcedureForCombo(&$PDOdb, $add_empty=false,$date_lim_reglement = 0) {
		global $langs;

		$sql = "SELECT p.rowid, p.name, e.delais, e.name as nameEtape
			FROM ".MAIN_DB_PREFIX."rec_procedure as p
				LEFT JOIN ".MAIN_DB_PREFIX."rec_etape as e ON (e.fk_procedure = p.rowid)
			WHERE e.rang = 1 AND p.entity IN (".getEntity('rec_procedure',1).")
			ORDER BY p.rowid ASC";

		$form = new TFormCore;

		$PDOdb->Execute($sql);

		$TProcedure = array();

		if($add_empty)$TProcedure[0] = '';

		while ($obj = $PDOdb->Get_line()) {

			$label = $obj->name;

			if(!empty($date_lim_reglement)) {
				$date = round((time() - strtotime($date_lim_reglement)) / 86400 );
				$delai = ($date - $obj->delais);

				if($delai <= 0) $label .= " (".abs($delai)." ".$langs->trans('DaysBeforeFirstStep')." '".$obj->nameEtape."')";
				else $label .= " (1ère étape '".$obj->nameEtape."' dépassée de ".$delai." jour(s))";

			}


			$TProcedure[$obj->rowid] = $label;
		}


		return $TProcedure;

	}

}