<?php
/*******************************************************************************
 *                    _ _ _ _
 *                   / _ _  /
 *            _ _   / /__/ /_ _   ____ _ _   _ _ _    __
 *           / _ ` /   _ _// _ ` / __// _ ` / _ \\ \ / /
 *          / _ _// /\ \  / _ _/ \_ \/ _ _// / \/ \ ` /
 *          \_ , /_/  \_\ \_ ,  /__ /\_ , /_/      \_/
 *
 *******************************************************************************
 *    Application:  eReserv
 *    Version:      6
 *    Author:       David Di Certo
 *    Website:      http://www.cogites.com
 *    Email:        contact@cogites.com
 *    Copyright:    2013 - David Di Certo
 *******************************************************************************
 *    == FR ==      La revente et la redistribution de l'application sont
 *                  strictement interdites.
 *
 *                  Vous êtes tenu d'avoir pris connaissance des
 *                  Conditions Générales de Vente disponibles sur Cogites.com
 *                  (y compris pour la version Free).
 *
 *    == EN ==      Resale and redistribution of the application are
 *                  Strictly prohibited.
 *
 *                  You are required to have read the Terms and Conditions
 *                  available on Cogites.com (including the Free version).
 *
 *******************************************************************************
*/

	require_once ('business/TenantMgr.php');
	require_once ('business/TenancyMgr.php');
	require_once ('business/ReservationMgr.php');
	require_once ('business/UserMgr.php');
	require_once ('business/ConfigMgr.php');
	require_once ('business/PaymentMgr.php');
	require_once ('config/Func.php');
	
class Tagger
{
	private static $arrTagList = array("Reservation","Tenant","Tenancy","Landlord","User","Payment","PaymentModule","Renter","Date","Other");
	
	private static $arrTagReservation = array(
			"<DATEDEBUT>","<DATEFIN>","<NBR_NUITEES>","<DATE_CONTRAT>",
			"<PRIX>","<PAYE>","<ACOMPTE>","<SOLDE>","<TOTAL_EXTRA>","<LIST_EXTRA>","<DATE_DUJOUR>","<DATE_BUTOIR>","<DATE_BUTOIR_SOLDE>",
			"<ADULTES>","<ENFANTS_2_A_13>","<ENFANTS_INF_2>","<PMR>",
			"<STATUS_RES>","<COMMENTAIRES_RES>","<RESERV_ID>",
			"<TOTAL_VAT>","<TOTAL_TAX>","<TOTAL_HT>","<TOTAL_TTC>"
		);
	private static $arrTagTenant = array(
			"<TITRE_LOC>","<NOM_LOC>","<PRENOM_LOC>","<ADRESSE_LOC>","<ADRESSE2_LOC>","<CP_LOC>","<VILLE_LOC>","<PAYS_LOC>",
			"<TEL_LOC>","<PORTABLE_LOC>","<FAX_LOC>","<EMAIL_LOC>","<COMMENTAIRES_LOC>","<REFERENCE_LOC>"
		);
	private static $arrTagTenancy = array(
			"<LOCATION>","<ADRESSE_LOCATION>","<ADRESSE2_LOCATION>","<CP_LOCATION>","<VILLE_LOCATION>","<PAYS_LOCATION>","<COMMENTAIRES_LOCATION>"
		);
	private static $arrTagLandlord = array(
			"<TITRE_PRO>","<NOM_PRO>","<PRENOM_PRO>","<ADRESSE_PRO>","<ADRESSE2_PRO>","<CP_PRO>","<VILLE_PRO>","<PAYS_PRO>",
			"<TEL_PRO>","<PORTABLE_PRO>","<FAX_PRO>","<EMAIL_PRO>","<COMMENTAIRES_PRO>"
		);
	private static $arrTagUser = array(
			"<NOM_USR>","<EMAIL_USR>","<COMMENTAIRES_USR>"
		);
	private static $arrTagPayment = array(
			"<PAIEMENT_DATE>","<PAIEMENT_TYPE>","<PAIEMENT_METHODE>","<PAIEMENT_MONTANT>"
		);
	private static $arrTagPaymentModule = array(
			"<PAIEMENTMODULE_PAYPAL>","<PAIEMENTMODULE_PAYPAL_AUT_CAPT>","<PAIEMENTMODULE_CMCIC>","<PAIEMENTMODULE_SYSTEMPAY>","<PAIEMENTMODULE_SIPSATOS>","<PAIEMENTMODULE_PAYZEN>"
		);
	private static $arrTagRenter = array(
			"<TITRE_LOUEUR>","<NOM_LOUEUR>","<PRENOM_LOUEUR>","<ADRESSE_LOUEUR>","<CP_LOUEUR>","<VILLE_LOUEUR>","<PAYS_LOUEUR>",
			"<TEL_LOUEUR>","<PORTABLE_LOUEUR>","<EMAIL_LOUEUR>","<URL_LOUEUR>"
		);
	private static $arrTagDate = array(
			"<DATE_YEAR_2>","<DATE_YEAR_4>","<DATE_MONTH_NB_2>","<DATE_MONTH_NB_02>","<DATE_DATE_2>","<DATE_DATE_02>","<DATE_MYSQL>",
		);
	private static $arrTagOther = array(
			"<SAUT_PAGE>","<SIGNATURE>"
		);

	private static $arrValReservation = array();
	private static $arrValTenant = array();
	private static $arrValTenancy = array();
	private static $arrValUser = array();
	private static $arrValPayment = array();
	private static $arrValRenter = array();
	private static $arrValDate = array();

	static public function setUserName(){
		global $session;
		$usr = (isset($session->userDisplayName) ? $session->userDisplayName : "");
		return $usr;
	}
	static function getTagList(){
		return self::$arrTagList;
	}
	static function getTag($tagName){
		switch ($tagName) {
			case "Reservation":
				return self::$arrTagReservation;
				break;
			case "Tenant":
				return self::$arrTagTenant;
				break;
			case "Tenancy":
				return self::$arrTagTenancy;
				break;
			case "Landlord":
				return self::$arrTagLandlord;
				break;
			case "User":
				return self::$arrTagUser;
				break;
			case "Payment":
				return self::$arrTagPayment;
				break;
			case "PaymentModule":
				return self::$arrTagPaymentModule;
				break;
			case "Renter":
				return self::$arrTagRenter;
				break;
			case "Date":
				return self::$arrTagDate;
				break;
			case "Other":
				return self::$arrTagOther;
				break;
		}
				
	}
	static function getTagReservation(){
		return self::$arrTagReservation;
	}
	static function getTagTenant(){
		return self::$arrTagTenant;
	}
	static public function setReservationId($id){
		global $tr;
		Logger::debug(' --> Tagger::setReservationId: ' . $id);
		$configMgr = new ConfigMgr();
		$config = $configMgr->getConfigs();
		$reservationMgr = new ReservationMgr();
		if (!empty($id)){
			$arrReservation = $reservationMgr->getReservation($id);
		}else{
			$arrReservation[] = new ReservationVo();
		}
		$paymentMgr = new PaymentMgr();
		if (!empty($id)){
			$arrPayment = $paymentMgr->getPaymentByReservation($id);
			if (empty($arrPayment)) {
				$arrPayment[] = new PaymentVo();
			}
		}else{
			$arrPayment[] = new PaymentVo();
		}

		$nbNights = round((strtotime($arrReservation[0]->departure_date) - strtotime($arrReservation[0]->arrival_date))/(60*60*24));

		// $pourcentage_acompte = $config['lease_deposit_percent'];
		$prix = $arrReservation[0]->price;
		// $deposit = round($pourcentage_acompte * $prix / 100, 2);
		$deposit = $arrReservation[0]->deposit;

		$totalExtra = 0;
		$arrExtra = array();
		$listExtra = $tr->translate("msgNoExtra");
		$arrListExtra = array();
		foreach ($arrExtra as $extra) {
			$arrListExtra[] = $extra->qty . " " . $extra->name . " " . $extra->total . $config['currency_symbol'];
		}
		if ($arrListExtra) $listExtra = implode(",", $arrListExtra);
		if($arrReservation[0]->disabled != 1){$disabled = $tr->translate("No");}else{$disabled = $tr->translate("Yes");}
		if($arrReservation[0]->paid != 1){$paid = $tr->translate("No");}else{$paid = $tr->translate("Yes");}

		$date_dujour = date($config['date_format']);
		$date_butoir = $config['lease_dateline'];
		if(isset($date_butoir)){
			$date_butoir = date($config['date_format'], strtotime(" + $date_butoir day"));
		}else{
			$date_butoir = '';
		}
		$date_butoir_solde = $config['balance_dateline'];
		if(isset($date_butoir_solde)){
			$date_butoir_solde = date($config['date_format'], strtotime($arrReservation[0]->arrival_date . " - $date_butoir_solde day"));
		}else{
			$date_butoir_solde = '';
		}
		
		// $tax_adults = (int)$config['tax_rate'] * (int)$nbNights * (int)$arrReservation[0]->adults_nb;
		// $tax_children = (int)$config['tax_rate_children'] * (int)$nbNights * (int)$arrReservation[0]->childs_nb;
		// $tax_total = $tax_adults + $tax_children;
		$tax_total = getTaxTotal($arrReservation, $config);
		$tax_total = number_format((float)$tax_total, 2, '.', '');
		$vat_total = getVatTotal($arrReservation, $arrExtra, $config);
		$vat_total = number_format((float)$vat_total, 2, '.', '');

		$ht_total = getPriceHT($arrReservation, $arrExtra, $config);
		$ht_total = number_format((float)$ht_total, 2, '.', '');
		$ttc_total = getPriceTTC($arrReservation, $arrExtra, $config);
		$ttc_total = number_format((float)$ttc_total, 2, '.', '');
		
		// $balance = number_format((float)$ttc_total, 2, '.', '') - number_format((float)$deposit, 2, '.', '');
		$balance = number_format((float)getBalance($arrReservation, $arrExtra, $arrPayment, $config), 2, '.', '');
		$solde = number_format((float)$ttc_total - $deposit, 2, '.', '');
		if ($arrReservation[0]->status > ReservationMgr::RESERV_LEASE_SENT) {
			$solde = $balance;
		}

		self::$arrValReservation = array(
			date($config['date_format'], strtotime($arrReservation[0]->arrival_date)),date($config['date_format'], strtotime($arrReservation[0]->departure_date)),
			$nbNights,$arrReservation[0]->lease_date,$arrReservation[0]->price,$paid,$deposit,$solde,$totalExtra,$listExtra,$date_dujour,$date_butoir,$date_butoir_solde,
			$arrReservation[0]->adults_nb,$arrReservation[0]->childs_nb,$arrReservation[0]->baby_nb,$disabled,
			$arrReservation[0]->status,$arrReservation[0]->comment,$arrReservation[0]->reservation_id,
			$vat_total,$tax_total,$ht_total,$ttc_total
		);
		self::setTenantId($arrReservation[0]->tenant_id);
		self::setTenancyId($arrReservation[0]->tenancy_id);
		self::setUserId(self::setUserName());
		self::setPaymentId('');
		self::setRenterInfo();
		self::setDates();
		// Logger::debug(' <-- setReservationId: ' . print_r(self::$arrValReservation, true));
	}
	
	static public function setTenantId($id){
		Logger::debug(' --> Logger::setTenantId: ' . $id);
		$tenantMgr = new TenantMgr();
		if (!empty($id)){
			$arrTenant = $tenantMgr->getTenant($id);
			if (empty($arrTenant)) $arrTenant[] = new TenantVo();
		}else{
			$arrTenant[] = new TenantVo();
		}
		self::$arrValTenant = array(
			$arrTenant[0]->title,$arrTenant[0]->lastname,$arrTenant[0]->name,$arrTenant[0]->address1,$arrTenant[0]->address2,$arrTenant[0]->zipcode,$arrTenant[0]->city,$arrTenant[0]->country,
			$arrTenant[0]->phone,$arrTenant[0]->cellphone,$arrTenant[0]->fax,$arrTenant[0]->email,$arrTenant[0]->comment,$arrTenant[0]->reference
		);
		// Logger::debug(' <-- setTenantId: ' . print_r(self::$arrValTenant, true));
	}
	
	static public function setTenancyId($id){
		Logger::debug(' --> Logger::setTenancyId: ' . $id);
		$tenancyMgr = new TenancyMgr();
		if (!empty($id)){
			$arrTenancy = $tenancyMgr->getTenancy($id);
			if (empty($arrTenancy)) $arrTenancy[] = new TenancyVo();
		}else{
			$arrTenancy[] = new TenancyVo();
		}
		self::$arrValTenancy = array(
			$arrTenancy[0]->name,$arrTenancy[0]->address1,$arrTenancy[0]->address2,$arrTenancy[0]->zipcode,$arrTenancy[0]->city,$arrTenancy[0]->country,$arrTenancy[0]->comment
		);
		// Logger::debug(' <-- setTenancyId: ' . print_r(self::$arrValTenancy, true));
	}

	static public function setUserId($id){
		Logger::debug(' --> Logger::setUserId: ' . $id);
		$userMgr = new UserMgr();
		if (!empty($id)){
			$arrUser = $userMgr->getUsers($id);
		}else{
			$arrUser[] = new UserVo();
		}
		// Logger::debug(' --> arrUser: ' . print_r($arrUser, true));
		self::$arrValUser = array(
			$arrUser[0]->username,$arrUser[0]->email,$arrUser[0]->comment
		);
		// Logger::debug(' <-- setUserId: ' . print_r(self::$arrValUser, true));
	}
	
	static public function setPaymentId($id){
		Logger::debug(' --> Logger::setPaymentId: ' . $id);
		$paymentMgr = new PaymentMgr();
		$configMgr = new ConfigMgr();
		$config = $configMgr->getConfigs();
		if (!empty($id)){
			$arrPayment = $paymentMgr->getPayment($id);
			if (empty($arrPayment)) {
				$arrPayment[] = new PaymentVo();
			}
		}else{
			$arrPayment[] = new PaymentVo();
		}

		// Logger::debug(' --> arrPayment: ' . print_r($arrPayment, true));

		self::$arrValPayment = array(
			date($config['date_format'], strtotime($arrPayment[0]->payment_date)),$arrPayment[0]->type,$arrPayment[0]->method,$arrPayment[0]->amount
		);

		// self::setReservationId($arrPayment[0]->reservation_id);

		// Logger::debug(' <-- setPaymentId: ' . print_r(self::$arrValPayment, true));
	}
	static public function setRenterInfo() {
		Logger::debug(' --> Logger::setRenterInfo');
		$configMgr = new ConfigMgr();
		$config = $configMgr->getConfigs();
		self::$arrValRenter = array(
				$config['renter_title'],$config['renter_lastname'],$config['renter_name'],$config['renter_address'],$config['renter_zipcode'],
				$config['renter_city'],$config['renter_country'],$config['renter_phone'],$config['renter_mobile'],$config['renter_email'],$config['renter_url'],
			);
		// Logger::debug(' <-- setRenterInfo: ' . print_r(self::$arrValPaymentModule, true));
	}
	static public function setDates() {
		Logger::debug(' --> Logger::setdates');
		$configMgr = new ConfigMgr();
		$config = $configMgr->getConfigs();
		self::$arrValDate = array(
				date("y"),date("Y"),date("n"),date("m"),date("j"),date("d"),date("Y-m-d H:i:s")
			);
		// Logger::debug(' <-- setRenterInfo: ' . print_r(self::$arrValPaymentModule, true));
	}

	static public function tag($str, $tagMode = ""){
		$arrTagFinal = array_merge(self::$arrTagReservation,self::$arrTagTenant,self::$arrTagTenancy,self::$arrTagUser,self::$arrTagPayment,self::$arrTagRenter,self::$arrTagDate);
		$arrValFinal = array_merge(self::$arrValReservation,self::$arrValTenant,self::$arrValTenancy,self::$arrValUser,self::$arrValPayment,self::$arrValRenter,self::$arrValDate);
		// Logger::debug(' --> TAGGER -- arrTagFinal: ' . print_r($arrTagFinal, true));
		// Logger::debug(' --> TAGGER -- arrValFinal: ' . print_r($arrValFinal, true));

		// Logger::debug(' --> TAGGER -- tagMode: ' . $tagMode);
		if ($tagMode == "preview"){
			Logger::debug(' --> TAGGER::tag: ' . $tagMode);
			return $str;
		}else{
			return str_replace($arrTagFinal, $arrValFinal, html_entity_decode($str));
		}
	}

}
?>