<?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).
 *
 *******************************************************************************
*/
	$status = getPost('status');
	$action = getPost('action');
	$reservationid = getPost('reservationid');
	$lease_date = getPost('lease_date');
	$cbtracking = getPost('cbtracking');

// print_r($_POST);

/*
	--------------------------------------
	DASHBOARD actions
	--------------------------------------
*/
	if(!empty($action) && ($action == "SET_LEASE_DATE" || $action == "CLEAR_LEASE_DATE" || $action == "DELETE_RESERV" || $action == "LEASE_RESENT" || $action == "NEXT_STEP" || $action == "REQUEST_BALANCE")) {
		Logger::info(' action: [' . $action . ']');
		if ($action == "SET_LEASE_DATE"){
			$res = $reservationMgr->getReservation($reservationid);
			$arrReservation = $reservationMgr->isReservationAvailable($res[0]->arrival_date, $res[0]->departure_date, $res[0]->tenancy_id, ReservationMgr::RESERV_LEASE_SENT);
			// TODO: Move this into the isReservationAvailable function and add a parameter to exclude current reservation in the search.
			foreach($arrReservation as $k => $v) {
				if($v->reservation_id == $reservationid) {
					Logger::debug('  Removing reservation ID: ' . $v->reservation_id);
					unset($arrReservation[$k]);
				}
			}
			if (empty($arrReservation)){
				Logger::debug('  arrReservation is EMPTY: ' . print_r($arrReservation, true));
				$reserv = array();
				$reserv['reservation_id'] = $reservationid;
				$reserv['lease_date'] = $lease_date;
				$reserv['status'] = ReservationMgr::RESERV_LEASE_SENT;
				$res = $reservationMgr->update($reserv);
				if ($res == 1) {
					$msgType = "success";
					$msg = $tr->translate("msgSuccess");
				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}
			}else{
				Logger::debug('  arrReservation is NOT EMPTY: ' . print_r($arrReservation, true));
				$msgType = "error";
				$msg = $tr->translate("msgAlreadyBooked");
				foreach ($arrReservation as $res) {
					$msg .= "<hr>ID: ". $res->reservation_id;
					$msg .= "<br>".  $tr->translate("Name") . ": " . $res->tenant_lastname . " " . $res->tenant_name;
					$msg .= "<br>" . $tr->translate("From") . "/" . $tr->translate("To") . ": " . date($config['date_format'], strtotime($res->arrival_date)) . " / " . date($config['date_format'], strtotime($res->departure_date));
					$msg .= "<br>" . $tr->translate("Status") . ": " . $res->status;
					$msg .= "<br>" . $tr->translate("Price") . ": " . $res->price;
				}
			}
		}

		if ($action == "CLEAR_LEASE_DATE") {
			$reserv = array();
			$reserv['reservation_id'] = $reservationid;
			$reserv['lease_date'] = "NULL";
			$reserv['status'] = ReservationMgr::RESERV_OPTION;
			$res = $reservationMgr->update($reserv);
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
		}
		if ($action == "DELETE_RESERV") {
			$mail = $mailMgr->getMail(4);
			$tagger->setReservationId($reservationid);
			$reserv = $reservationMgr->getReservation($reservationid);
			$res = $reservationMgr->delete($reservationid);
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
				// Do not send mail if Status is 0 (New reservation)
				if ($reserv[0]->status > 0) {
					if (isset($mail) && !empty($mail[0]->enable)){
						$mail[0]->from = $config['renter_email'];
						$mail[0]->to = $tagger->tag($mail[0]->to);
						$mail[0]->cc = $tagger->tag($mail[0]->cc);
						$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
						$mail[0]->subject = $tagger->tag($mail[0]->subject);
						$mail[0]->content = $tagger->tag(htmlspecialchars_decode($mail[0]->content));
						require_once ('config/Mailer.php');
						$m = new Mailer($config);
						$r = $m->sendMail($mail);
						if (!$r) {
							$msgType = "error";
							$msg = $tr->translate("msgMailError");
						}
					}
				}
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
		}

		if ($action == "LEASE_RESENT") {
			$reserv['reservation_id'] = $reservationid;
			$reserv['lease_date'] = date('Y-m-d H:i:s');
			$mail = $mailMgr->getMail(9);
			$res = $reservationMgr->update($reserv);
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");

				if (isset($mail) && !empty($mail[0]->enable)){
					// Logger::debug(' --> mail before tagging: ' . print_r($mail, true));
					$tagger->setReservationId($reservationid);
					$mail[0]->from = $config['renter_email'];
					$mail[0]->to = $tagger->tag($mail[0]->to);
					$mail[0]->cc = $tagger->tag($mail[0]->cc);
					$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
					$mail[0]->subject = $tagger->tag($mail[0]->subject);
					$mail[0]->content = $tagger->tag(htmlspecialchars_decode($mail[0]->content));
					// Logger::debug(' --> mail after tagging: ' . print_r($mail, true));
					require_once ('config/Mailer.php');
					$m = new Mailer($config);
					$r = $m->sendMail($mail);
					if (!$r) {
						$msgType = "error";
						$msg = $tr->translate("msgMailError");
					}
				}
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
		}

		if ($action == "NEXT_STEP") {
			Logger::debug('Entering action: ' . $action);
			$res = $reservationMgr->getReservation($reservationid);
			if ($config['allow_duplicate_reservation'] && ($status <= ReservationMgr::RESERV_OPTION)){
				Logger::debug('  Duplicate allowed AND Status = ' . $status);
				Logger::debug('  arrReservation is set to EMPTY');
				$arrReservation = array();
			}else{
				if ($status == ReservationMgr::RESERV_OPTION){
					$arrReservation = $reservationMgr->isReservationAvailable($res[0]->arrival_date, $res[0]->departure_date, $res[0]->tenancy_id, ReservationMgr::RESERV_OPTION);
				}else{
					$arrReservation = $reservationMgr->isReservationAvailable($res[0]->arrival_date, $res[0]->departure_date, $res[0]->tenancy_id, ReservationMgr::RESERV_LEASE_SENT);
				}
				
				// TODO: Move this into the isReservationAvailable function and add a parameter to exclude current reservation in the search.
				foreach($arrReservation as $k => $v) {
					if($v->reservation_id == $reservationid) {
						Logger::debug('  Removing reservation ID: ' . $v->reservation_id);
						unset($arrReservation[$k]);
					}
				}
			}

			if (empty($arrReservation)){
				$reserv = array();
				$reserv['reservation_id'] = $reservationid;
				$reserv['status'] = $status;
				switch ($status) {
					case ReservationMgr::RESERV_OPTION:
						$price = getPost('reserv_price');
						$deposit = ($price == '') ? 0 : round($config['lease_deposit_percent'] * $price / 100, 2);
						$reserv['price'] = $price;
						$reserv['deposit'] = number_format((float)$deposit, 2, '.', '');
						$reserv['status'] = ReservationMgr::RESERV_OPTION;
						// $mail = $mailMgr->getMail(1);
						$mail = NULL;
						break;
					case ReservationMgr::RESERV_LEASE_SENT:
						$deposit = getPost('deposit_montant');
						$reserv['deposit'] = number_format((float)$deposit, 2, '.', '');
						$reservationMgr->update($reserv);
						$tagger->setReservationId($reservationid);
						// set the status here otherwise the update is not successful
						$mail = $mailMgr->getMail(2);

						include_once('business/LeaseContentMgr.php');
						include_once('business/ConfigMgr.php');
						$leaseContentMgr = new LeaseContentMgr();
						$arrLeaseContent = $leaseContentMgr->getLease($res[0]->tenancy_id);
						if (!empty($arrLeaseContent)){
							$reserv['lease_date'] = date('Y-m-d H:i:s');
							/////////////////////  PDF  ////////////////////
							$filename = LEASE_PATH . "/" . $tagger->tag($config['lease_filename']) . '.pdf';
							Logger::debug(' --> lease filename: ' . $filename);
							require_once('lib/myPdf.php');
							$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
							$pdf->SetOutput("F");
							$pdf->SetPageBreak($leaseContentMgr->getPageBreak($res[0]->tenancy_id));
							$pdf->SetFileName($filename);
							$pdf->SetImageFilename(LEASE_IMAGE_PATH . "/lease_" . $res[0]->tenancy_id . ".jpg");
							$pdf->SetSigningFileName(LEASE_IMAGE_PATH . "/signing_" . $res[0]->tenancy_id . ".jpg");
							$pdf->SetDuplicateLease($config['lease_create_2copy']);
							$pdf->SetDateFormat($config['date_format']);
							$pdf->SetLeaseContentTitle($tr->translate("leaseContentTitle"));
							// $pdf->SetLeaseContentSubTitle($res[0]->tenancy_name);
							$pdf->SetLeaseContentInitials($tr->translate("leaseContentInitials"));
							$pdf->SetLeaseContentPage($tr->translate("leaseContentPage"));
							$pdf->SetLeaseContentSigningHeader($tr->translate("leaseContentSigningHeader"));
							$pdf->SetLeaseContentSigningTenant($tr->translate("leaseContentSigningTenant"));
							$pdf->SetLeaseContentSigningLandlord($tr->translate("leaseContentSigningLandlord"));
							$pdf->SetLeaseContentSigningTenant2($tr->translate("leaseContentSigningTenant2"));
							$pdf->BuildContent($arrLeaseContent, $action);
							/////////////////////  PDF  ////////////////////
							$mail[0]->file[] = array($filename => "application/pdf");
						}else{
							Logger::warn(' --> No lease defined for this tenancy');
							// $msgType = "warning";
							// $msg = "Pas de contrat définit pour cete location";
						}
						break;
					case ReservationMgr::RESERV_VALIDATE:
						$amount = getPost('payment_montant');
						if (isset($cbtracking) && ($cbtracking == "on") && ($amount > 0)){
							$payment = array();
							$payment['payment_date'] = date('Y-m-d H:i:s');
							$payment['reservation_id'] = $reservationid;
							$payment['method'] = getPost('payment_method');
							$payment['type'] = $config['tracking_payment'];
							$payment['amount'] = $amount;
							$resPayment = $paymentMgr->addPayment($payment);
						}
						$mail = $mailMgr->getMail(3);
						break;
					case ReservationMgr::RESERV_CLOSED:
						$amount = getPost('payment_montant');
						if (isset($cbtracking) && ($cbtracking == "on") && ($amount > 0)){
							$payment = array();
							$payment['payment_date'] = date('Y-m-d H:i:s');
							$payment['reservation_id'] = $reservationid;
							$payment['method'] = getPost('payment_method');
							$payment['type'] = $tr->translate("thPaymentTypeBalance");
							$payment['amount'] = $amount;
							$resPayment = $paymentMgr->addPayment($payment);
						}
						$reserv['paid'] = 1;
						break;
				}

				$res = $reservationMgr->update($reserv);
				if ($res == 1) {
					$msgType = "success";
					$msg = $tr->translate("msgSuccess");
					if (isset($mail) && !empty($mail[0]->enable)){
						$tagger->setReservationId($reservationid);
						if (isset($resPayment)){
							$tagger->setPaymentId($resPayment);
						}
						$mail[0]->from = $config['renter_email'];
						$mail[0]->to = $tagger->tag($mail[0]->to);
						$mail[0]->cc = $tagger->tag($mail[0]->cc);
						$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
						$mail[0]->subject = $tagger->tag($mail[0]->subject);
						$mail[0]->content = $tagger->tag(htmlspecialchars_decode($mail[0]->content));

						require_once ('config/Mailer.php');
						$m = new Mailer($config);
						$r = $m->sendMail($mail);
						if (!$r) {
							$msgType = "error";
							$msg = $tr->translate("msgMailError");
						}
						if (!$config['lease_keep_on_server']) {
							$tagger->setReservationId($reservationid);
							unlink($filename);
						}
					}
					// Send a mail if payment has been recorded
					if (isset($resPayment)) {
						$mail = $mailMgr->getMail(5);
						if (isset($mail) && !empty($mail[0]->enable)){
							$tagger->setReservationId($reservationid);
							$tagger->setPaymentId($resPayment);
							// Logger::debug(' --> mail before tagging: ' . print_r($mail, true));
							$mail[0]->from = $config['renter_email'];
							$mail[0]->to = $tagger->tag($mail[0]->to);
							$mail[0]->cc = $tagger->tag($mail[0]->cc);
							$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
							$mail[0]->subject = $tagger->tag($mail[0]->subject);
							$mail[0]->content = $tagger->tag($mail[0]->content);
							// Logger::debug(' --> mail after tagging: ' . print_r($mail, true));
							include_once ('config/Mailer.php');
							$m = new Mailer($config);
							$r = $m->sendMail($mail);
							if (!$r) {
								$msgType = "error";
								$msg = $tr->translate("msgMailError");
							}
						}
					}

				}else{
					$msgType = "error";
					$msg = $tr->translate("msgError");
				}

			}else{
				Logger::debug('  arrReservation is NOT EMPTY: ' . print_r($arrReservation, true));
				$msgType = "error";
				$msg = $tr->translate("msgAlreadyBooked");
				foreach ($arrReservation as $res) {
					$msg .= "<hr>ID: ". $res->reservation_id;
					$msg .= "<br>".  $tr->translate("Name") . ": " . $res->tenant_lastname . " " . $res->tenant_name;
					$msg .= "<br>" . $tr->translate("From") . "/" . $tr->translate("To") . ": " . date($config['date_format'], strtotime($res->arrival_date)) . " / " . date($config['date_format'], strtotime($res->departure_date));
					$msg .= "<br>" . $tr->translate("Status") . ": " . $res->status;
					$msg .= "<br>" . $tr->translate("Price") . ": " . $res->price;
				}
			}
			Logger::debug('Leaving action: ' . $action);
		}
		if ($action == "REQUEST_BALANCE") {
			Logger::debug('Entering action: ' . $action);
			// TODO: implement new column in DB to store the balance date
			// $reserv['reservation_id'] = $reservationid;
			// $reserv['balance_date'] = date('Y-m-d H:i:s');
			$mail = $mailMgr->getMail(8);
			Logger::debug(' --> mail content: ' . print_r($mail, true));
			// $res = $reservationMgr->update($reserv);
			$res = 1;
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");

				if (isset($mail) && !empty($mail[0]->enable)){
					// Logger::debug(' --> mail before tagging: ' . print_r($mail, true));
					$tagger->setReservationId($reservationid);
					$mail[0]->from = $config['renter_email'];
					$mail[0]->to = $tagger->tag($mail[0]->to);
					$mail[0]->cc = $tagger->tag($mail[0]->cc);
					$mail[0]->bcc = $tagger->tag($mail[0]->bcc);
					$mail[0]->subject = $tagger->tag($mail[0]->subject);
					$mail[0]->content = $tagger->tag(htmlspecialchars_decode($mail[0]->content));
					// Logger::debug(' --> mail after tagging: ' . print_r($mail, true));
					require_once ('config/Mailer.php');
					$m = new Mailer($config);
					$r = $m->sendMail($mail);
					if (!$r) {
						$msgType = "error";
						$msg = $tr->translate("msgMailError");
					}
				}
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
			Logger::debug('Leaving action: ' . $action);
		}
		echo '<div class="alert alert-'.$msgType . '">
			<strong>' . $msg . '</strong>
			</div>';
	}

/*
	--------------------------------------
	TENANT actions
	--------------------------------------
*/
	if (!empty($action) && ($action == "UPDATE_TENANT" || $action == "DELETE_TENANT" || $action == "ADD_TENANT")) {
		Logger::info('BEGIN: [' . $action . ']');
		if ($action == "ADD_TENANT") {
			$tenant2 = array();
			$tenant2['title'] = getPost('inputTitle');
			$tenant2['name'] = getPost('inputName');
			$tenant2['lastname'] = getPost('inputLastname');
			$tenant2['address1'] = getPost('inputAddress1');
			$tenant2['address2'] = getPost('inputAddress2');
			$tenant2['zipcode'] = getPost('inputZipcode');
			$tenant2['city'] = getPost('inputCity');
			$tenant2['country'] = getPost('inputCountry');
			$tenant2['phone'] = getPost('inputPhone');
			$tenant2['cellphone'] = getPost('inputCellphone');
			$tenant2['fax'] = getPost('inputFax');
			$tenant2['email'] = getPost('inputEmail');
			$tenant2['newsletter'] = getPost('inputNewsletter');
			$tenant2['comment'] = getPost('inputComment');
			$tenant2['reference'] = getPost('inputReference');
			$tenant2['language'] = getPost('inputLanguage');
			$res = $tenantMgr->insert($tenant2);
			if ($res > 0) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
		}
		if ($action == "UPDATE_TENANT") {
			$tenant2 = array();
			$tenant2['title'] = getPost('inputTitle');
			$tenant2['name'] = getPost('inputName');
			$tenant2['lastname'] = getPost('inputLastname');
			$tenant2['address1'] = getPost('inputAddress1');
			$tenant2['address2'] = getPost('inputAddress2');
			$tenant2['zipcode'] = getPost('inputZipcode');
			$tenant2['city'] = getPost('inputCity');
			$tenant2['country'] = getPost('inputCountry');
			$tenant2['phone'] = getPost('inputPhone');
			$tenant2['cellphone'] = getPost('inputCellphone');
			$tenant2['fax'] = getPost('inputFax');
			$tenant2['email'] = getPost('inputEmail');
			$tenant2['newsletter'] = getPost('inputNewsletter');
			$tenant2['comment'] = getPost('inputComment');
			$tenant2['reference'] = getPost('inputReference');
			$tenant2['language'] = getPost('inputLanguage');
			$tenant2['tenant_id'] = $tenantid;
			$res = $tenantMgr->update($tenant2);
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
			
		}
		if ($action == "DELETE_TENANT") {
			$res = $tenantMgr->delete($tenantid);
			if ($res == 1) {
				$msgType = "success";
				$msg = $tr->translate("msgSuccess");
			}else{
				$msgType = "error";
				$msg = $tr->translate("msgError");
			}
		}
		Logger::info('END: [' . $action . ']');
		echo '<div class="alert alert-'.$msgType . '">
			<strong>' . $msg . '</strong>
			</div>';
	}

?>