<?php
include ("_config/addCfg.php");
include ("_includes/addInc.php");

if(!$R['idService']){
	die('invalid request');
}

$closePopup = false;

$service = \Entity\Service::select($R['idService']);
$offerList = array_reverse($service->offersList, true);

///////////////////////////////////////////////////////////////////////////////////////////////////
// SUBMIT BUTTON WAS PRESSED //////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if ($R['saveData']) {

	// save this data to the DB, use a transaction
	DB::startTransaction();

	try {
		foreach ($R['offer'] as $idOffer=>$offerData) {

			$offer = \Entity\Offer::update($idOffer);

			$offerSel = \Entity\Offer::selectForUpdate($idOffer);

			$productNameCfg = \App\Config\Services_GeneralAttributes::getInstance()->getServiceProductName($offerSel->serviceCode);
			if ($productNameCfg['type']!='none') {
				if ($offerData['serviceSupplierProduct']['id']) {
					$offer->idSupplierProduct = $offerData['serviceSupplierProduct']['id'];
				}
				else {
					$offer->idSupplierProduct = 0;
					$offer->productName = $offerData['serviceSupplierProduct']['title'];
				}
			}

			if (!$offerSel->mainFieldsBlocked) {
				list($country, $city) = explode("|", $offerData['departure']['city']['id'] );
				$offer->departureCountryCode = $country;
				$offer->departureCityId = $city;
				$offer->departureStationCode = $offerData['departure']['airport']['id'];
				$offer->startDatetime = \Engine\DateTime::create($offerData['departure']['date']);

				list($country, $city) = explode("|", $offerData['destination']['city']['id'] );
				$offer->destinationCountryCode = $country;
				$offer->destinationCityId = $city;
				$offer->destinationStationCode = $offerData['destination']['airport']['id'];
				if (\App\Config\Services_Fields::getInstance()->getServiceFieldType($offerSel->serviceCode, 'endDatetime') != 'invisible') {
					$offer->endDatetime = \Engine\DateTime::create($offerData['destination']['date']);
				}

			}

			// set other fields -these are always available
			$offer->externalSystemReservationId = $offerData['extResId'];
			$offer->externalSystemReservationDate = $offerData['extResDate'] ? : null;
			$offer->confirmationNumber = $offerData['confirmationNumber'];
			$offer->optionDate = $offerData['optionDate'] ? : null;

			// FORM OF PAYMENT --------------------------------------------------------------------
			$offer->formOfPayment = $offerData['formOfPayment'];
			// for CC - set all related values
			if (in_array($offerData['formOfPayment'], $CFG['offers']['formOfPaymentWithCardDetails'])) {

				if ($offerData['formOfPaymentCcType']=='new') {

					$autoTruncateDt = \Engine\DateTime::createFromIsoDate( max($service->startDate, TODAY_ISO) );
					$autoTruncateDt->add(new \DateInterval('P'.$CFG['pciDss']['storeOriginalNumberPeriod'].'D'));

					$ccStorage = new \App\Utils\CreditCard\Storage();
					$idNewCard = $ccStorage->addCard($offerData['formOfPaymentCcDet']['number'], $offerData['formOfPaymentCcDet']['company'], $offerData['formOfPaymentCcDet']['expireYm']?:null, 'offerFop', $idOffer, $autoTruncateDt->formatDateIso());

					$offer->paymentCcEntityType = 'manual';
					$offer->paymentCcEntityId = $idNewCard;

				} else {
					list($fopEntType, $fopEntId) = explode('_', $offerData['formOfPaymentCcType']);
					$offer->paymentCcEntityType = $fopEntType;
					$offer->paymentCcEntityId = $fopEntId;
				}

				$offer->paymentCcApprovalCode = $offerData['formOfPaymentCcApprovalCode'];
				$offer->paymentCcValue = $offerData['formOfPaymentCcPay']['value'];
				$offer->paymentCcCurrency = $offerData['formOfPaymentCcPay']['value']?$offerData['formOfPaymentCcPay']['currency']:'';

			}
			// for non-CC - reset all values in case something was set here
			else {
				$offer->paymentCcEntityType = '';
				$offer->paymentCcEntityId = 0;
				$offer->paymentCcApprovalCode = '';
				$offer->paymentCcValue = 0;
				$offer->paymentCcCurrency = '';
			}

			// FORM OF CASHING --------------------------------------------------------------------
			$offer->formOfCashing = $offerData['formOfCashing'];
			// for CC - set all related values
			if (in_array($offerData['formOfCashing'], $CFG['offers']['formOfCashingWithCardDetails'])) {

				if ($offerData['formOfCashingCcType']=='new') {

					$autoTruncateDt = \Engine\DateTime::createFromIsoDate( max($service->startDate, TODAY_ISO) );
					$autoTruncateDt->add(new \DateInterval('P'.$CFG['pciDss']['storeOriginalNumberPeriod'].'D'));

					$ccStorage = new \App\Utils\CreditCard\Storage();
					$idNewCard = $ccStorage->addCard($offerData['formOfCashingCcDet']['number'], $offerData['formOfCashingCcDet']['company'], $offerData['formOfCashingCcDet']['expireYm']?:null, 'offerFoc', $idOffer, $autoTruncateDt->formatDateIso());

					$offer->cashingCcEntityType = 'manual';
					$offer->cashingCcEntityId = $idNewCard;

				} else {
					list($focEntType, $focEntId) = explode('_', $offerData['formOfCashingCcType']);
					$offer->cashingCcEntityType = $focEntType;
					$offer->cashingCcEntityId = $focEntId;
				}

				$offer->cashingCcApprovalCode = $offerData['formOfCashingCcApprovalCode'];

			}
			// for non-CC - reset all values in case something was set here
			else {
				$offer->cashingCcEntityType = '';
				$offer->cashingCcEntityId = 0;
				$offer->cashingCcApprovalCode = '';
			}


			$offer->save();
		}

		DB::commitTransaction();

		$closePopup = true;

		$showMessage['success'] = $_LANG['reservations']['offerDetails']['messages']['saveOK'];


	} catch (\App\MessagesException $e) {
		\DB::rollbackTransaction();
		$showMessage['error'] = $e->getMessagesCollector()->getMessageBulk();
	} catch (\App\Entity\Exception $e) {
		\DB::rollbackTransaction();
		$e->decorate($showMessage);
	}

} else {

	foreach($offerList as $idOffer=>$x){

		$offer = \Entity\Offer::select($idOffer);

		$o = [];
		$productNameCfg = \App\Config\Services_GeneralAttributes::getInstance()->getServiceProductName($offer->serviceCode);
		if ($productNameCfg['type']!='none') {
			$o['serviceSupplierProduct']['id'] = 	$offer->idSupplierProduct;
			$o['serviceSupplierProduct']['title'] = ($offer->idSupplierProduct?null:$offer->productName);
		}
		$o['departure']['city']['id'] = 		implode("|", [$offer->departureCountryCode, $offer->departureCityId]);
		$o['departure']['airport']['id'] = 		$offer->departureStationCode;
		$o['departure']['date'] = 				$offer->startDatetime->formatDatetimeIso();

		$o['destination']['city']['id'] = 		implode("|", [$offer->destinationCountryCode, $offer->destinationCityId]);
		$o['destination']['airport']['id'] = 	$offer->destinationStationCode;
		$o['destination']['date'] = 			$offer->endDatetime->formatDatetimeIso();

		$o['extResId'] = 						$offer->externalSystemReservationId;
		$o['extResDate'] = 						$offer->externalSystemReservationDate;
		$o['confirmationNumber'] = 				$offer->confirmationNumber;
		$o['optionDate'] =	 					$offer->optionDate;

		$o['formOfPayment'] =	 				$offer->formOfPayment;
		if ($offer->paymentCcEntityType and $offer->paymentCcEntityId) {
			$o['formOfPaymentCcType'] =	 		$offer->paymentCcEntityType.'_'.$offer->paymentCcEntityId;
		}
		$o['formOfPaymentCcApprovalCode'] =		$offer->paymentCcApprovalCode;
		$o['formOfPaymentCcPay'] =				['value'=>$offer->paymentCcValue, 'currency'=>$offer->paymentCcCurrency];

		$o['formOfCashing'] =	 				$offer->formOfCashing;
		if ($offer->cashingCcEntityType and $offer->cashingCcEntityId) {
			$o['formOfCashingCcType'] =	 		$offer->cashingCcEntityType.'_'.$offer->cashingCcEntityId;
		}
		$o['formOfCashingCcApprovalCode'] =		$offer->cashingCcApprovalCode;

		$R['offer'][$idOffer] = $o;
	}
}


///////////////////////////////////////////////////////////////////////////////////////////////////
// DISPLAY THE FORM ///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
if(!$closePopup){

	// decide if we need hours as well
	$showTime = ( \App\Config\Services_Fields::getInstance()->getServiceFieldType($service->serviceCode, 'durationType') == 'daysTime') ;

	// generate the form
	$form = \Engine\Form\General::create();
	$form->setStyle('width', '300');

	// for every offer, create a new container and display its details in there
	$offerList = array_reverse($service->offersList, true);
	$fopFlds = $focFlds = $fopCcType = $focCcType = $fopCcDet = $focCcDet = $fopCcVal = [];
	foreach($offerList as $idOffer=>$x){
		// get complete offer details
		$offer = \Entity\Offer::select($idOffer);

		$fieldset = \Engine\Form\Container\Fieldset::create(sprintf("%s %s, %s", number_format($offer->offerWorkTotal, 2), $offer->totalCurrency, $offer->supplier->companyFull));
		$fieldset->setCollapsible();
		$form->addContainer($fieldset);

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// serviceSupplierProduct
		$productNameCfg = \App\Config\Services_GeneralAttributes::getInstance()->getServiceProductName($offer->serviceCode);
		$serviceSupplierProduct = new \App\Form\Input\Autocomplete_SupplierProduct();
		$serviceSupplierProduct->setLabel($productNameCfg['fieldFinalName']);
		$serviceSupplierProduct->setName("offer[{$idOffer}][serviceSupplierProduct]");
		$serviceSupplierProduct->setValue($R['offer'][$idOffer]['serviceSupplierProduct']['id']);
		$serviceSupplierProduct->setDisplayValue($R['offer'][$idOffer]['serviceSupplierProduct']['title']);
		$serviceSupplierProduct->setClearOnCancel(false);
		$serviceSupplierProduct->setInvisible($productNameCfg['type']=='none');
// 		if ($offer->mainFieldsBlocked) {
// 			$serviceSupplierProduct->setDisabled(true);
// 		}
		$fieldset->addElement($serviceSupplierProduct);


		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// departure country
		$location = new \App\Form\Input\Autocomplete_CountryCity();
		$location->setLabel($_LANG['reservations']['offerDetails']['fields']['departure_country']);
		$location->setName("offer[{$idOffer}][departure][city]");
		$location->setValue($R['offer'][$idOffer]['departure']['city']['id']);
		$location->onChange("$('offer_{$idOffer}__departure__airport__title_').value = ''; $('offer_{$idOffer}__departure__airport_').value = '';");
		if ($offer->mainFieldsBlocked) {
			$location->setDisabled(true);
		}
		$fieldset->addElement($location);

		// departure airport
		$airport = new \App\Form\Input\Autocomplete_Station($_LANG['reservations']['offerDetails']['fields']['departure_airport'],
			"offer[{$idOffer}][departure][airport]");
		$airport->setValue($R['offer'][$idOffer]['departure']['airport']['id']);
		$airport->onChange("
			if(selectedItem.countryName){
				$('offer_{$idOffer}__departure__city__title_').value = (selectedItem.cityId?selectedItem.cityName:selectedItem.countryName);
				$('offer_{$idOffer}__departure__city_').value =  '%s|%s'.sprintf(selectedItem.countryCode, selectedItem.cityId);
			}else{
				$('offer_{$idOffer}__destination__city_').value =  '';
			}");
		if ($offer->mainFieldsBlocked) {
			$airport->setDisabled(true);
		}
		$fieldset->addElement($airport);


		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// destination country
		$location = new \App\Form\Input\Autocomplete_CountryCity();
		$location->setLabel($_LANG['reservations']['offerDetails']['fields']['destination_country']);
		$location->setName("offer[{$idOffer}][destination][city]");
		$location->setValue($R['offer'][$idOffer]['destination']['city']['id']);
		$location->onChange("$('offer_{$idOffer}__destination__airport__title_').value = ''; $('offer_{$idOffer}__destination__airport_').value = '';");
		if ($offer->mainFieldsBlocked) {
			$location->setDisabled(true);
		}
		$fieldset->addElement($location);

		// destination airport
		$airport = new \App\Form\Input\Autocomplete_Station($_LANG['reservations']['offerDetails']['fields']['destination_airport']);
		$airport->setName("offer[{$idOffer}][destination][airport]");
		$airport->setValue($R['offer'][$idOffer]['destination']['airport']['id']);
		$airport->onChange("
			if(selectedItem.countryName){
				$('offer_{$idOffer}__destination__city__title_').value = (selectedItem.cityId?selectedItem.cityName:selectedItem.countryName);
				$('offer_{$idOffer}__destination__city_').value =  '%s|%s'.sprintf(selectedItem.countryCode, selectedItem.cityId);
			}else{
				$('offer_{$idOffer}__destination__city_').value =  '';
			}");
		if ($offer->mainFieldsBlocked) {
			$airport->setDisabled(true);
		}
		$fieldset->addElement($airport);


		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// start/end dates
		if ($showTime) {
			$startDateTime = new \Engine\Form\Input\Datetime();
		} else {
			$startDateTime = new \Engine\Form\Input\Date();
		}
		$startDateTime->setLabel($_LANG['reservations']['offerDetails']['fields']['departure_datetime']);
		$startDateTime->setName("offer[{$idOffer}][departure][date]");
		$startDateTime->setValue($R['offer'][$idOffer]['departure']['date']);
		$startDateTime->setMandatory(true);
		if ($offer->mainFieldsBlocked) {
			$startDateTime->setDisabled(true);
		}
		$fieldset->addElement($startDateTime);

		$endDatetimeVisibility = \App\Config\Services_Fields::getInstance()->getServiceFieldType($offer->serviceCode, 'endDatetime');
		if ($endDatetimeVisibility!='invisible') {
			if ($showTime) {
				$endDateTime = new \Engine\Form\Input\Datetime();
			} else {
				$endDateTime = new \Engine\Form\Input\Date();
			}
			$endDateTime->setLabel($_LANG['reservations']['offerDetails']['fields']['destination_datetime']);
			$endDateTime->setName("offer[{$idOffer}][destination][date]");
			$endDateTime->setValue($R['offer'][$idOffer]['destination']['date']);
			if ($endDatetimeVisibility=='mandatory') {
				$endDateTime->setMandatory(true);
			}
			if ($offer->mainFieldsBlocked) {
				$endDateTime->setDisabled(true);
			}
			$fieldset->addElement($endDateTime);
		}

		$offConfCfg = \App\Config\Services_OfferFields::getInstance()->get($offer->serviceCode);

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// external system reservation id
		if ($offConfCfg['externalSystemReservationId']!='invisible') {
			$extResId = new \Engine\Form\Input\Text($_LANG['reservations']['offerDetails']['fields']['extResId'], "offer[{$idOffer}][extResId]", $R['offer'][$idOffer]['extResId']);
			if ($offConfCfg['externalSystemReservationId']=='mandatory') {
				$extResId->setMandatory();
			}
			$fieldset->addElement($extResId);
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// external system reservation date
		if ($offConfCfg['externalSystemReservationDate']!='invisible') {
			$extResDate = new \Engine\Form\Input\Date($_LANG['reservations']['offerDetails']['fields']['extResDate'], "offer[{$idOffer}][extResDate]", $R['offer'][$idOffer]['extResDate']);
			if ($offConfCfg['externalSystemReservationDate']=='mandatory') {
				$extResDate->setMandatory();
			}
			$fieldset->addElement($extResDate);
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// confirmation number
		if ($offConfCfg['confirmationNumber']!='invisible') {
			$confNo = new \Engine\Form\Input\Text($_LANG['reservations']['offerDetails']['fields']['confirmationNumber'], "offer[{$idOffer}][confirmationNumber]", $R['offer'][$idOffer]['confirmationNumber']);
			if ($offConfCfg['confirmationNumber']=='mandatory') {
				$confNo->setMandatory();
			}
			$fieldset->addElement($confNo);
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// option date
		if ($offConfCfg['optionDate']!='invisible') {
			$optionDate = new \Engine\Form\Input\Date($_LANG['reservations']['offerDetails']['fields']['optionDate'], "offer[{$idOffer}][optionDate]", $R['offer'][$idOffer]['optionDate']);
			if ($offConfCfg['optionDate']=='mandatory') {
				$optionDate->setMandatory();
			}
			$fieldset->addElement($optionDate);
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// form of payment
		if ($offConfCfg['formOfPayment']!='invisible') {
			$fopFlds[$idOffer] = new \App\Form\Input\Select_OfferFormOfPayment($_LANG['reservations']['offerDetails']['fields']['fop'], "offer[{$idOffer}][formOfPayment]", $R['offer'][$idOffer]['formOfPayment']);
			$fopFlds[$idOffer]->showDefaultOption();
			if ($offConfCfg['formOfPayment']=='mandatory') {
				$fopFlds[$idOffer]->setMandatory();
			}
			$fieldset->addElement($fopFlds[$idOffer]);
		}

		// form of payment type
		if ($offConfCfg['formOfPayment']!='invisible') {
			$fopCcType[$idOffer] = new \App\Form\Input\Select_CreditCards($_LANG['reservations']['offerDetails']['fields']['fopPayType'], "offer[{$idOffer}][formOfPaymentCcType]", $R['offer'][$idOffer]['formOfPaymentCcType']);
			$fopCcType[$idOffer]->addAgencyCards(true);
			$fopCcType[$idOffer]->addCorporatesCards($service->order->idCorporatesList);
			$fopCcType[$idOffer]->addCustomersCards($service->idCustomersList);
			if ($offer->paymentCcEntityType=='manual' and $offer->paymentCcEntityId) {
				$fopCcType[$idOffer]->addManualCards( [ $offer->paymentCcEntityId ] );
			}
			$fopCcType[$idOffer]->addNewCard(true);
			$fopCcType[$idOffer]->showDefaultOption();
			$fieldset->addElement($fopCcType[$idOffer]);
		}

		// form of payment CC details
		if ($offConfCfg['formOfPayment']!='invisible') {
			$fopCcDet[$idOffer] = new \App\Form\Input\CreditCardDetails($_LANG['reservations']['offerDetails']['fields']['fopPayDet'], "offer[{$idOffer}][formOfPaymentCcDet]", $R['offer'][$idOffer]['formOfPaymentCcDet']);
			$fieldset->addElement($fopCcDet[$idOffer]);

			$fopCcType[$idOffer]->setControlledElements( [ 'new'=>[$fopCcDet[$idOffer]] ], 'disable' );
		}

		// CC - payment approval code
		if ($offConfCfg['formOfPayment']!='invisible') {
			$fopCcApprCode[$idOffer] = new \Engine\Form\Input\Text($_LANG['reservations']['offerDetails']['fields']['fopPayApprCode'], "offer[{$idOffer}][formOfPaymentCcApprovalCode]", $R['offer'][$idOffer]['formOfPaymentCcApprovalCode']);
			$fieldset->addElement($fopCcApprCode[$idOffer]);
		}

		// CC - payment value
		if ($offConfCfg['formOfPayment']!='invisible') {
			$fopCcVal[$idOffer] = new \App\Form\Input\Price($_LANG['reservations']['offerDetails']['fields']['fopPayAmnt'], "offer[{$idOffer}][formOfPaymentCcPay]", $R['offer'][$idOffer]['formOfPaymentCcPay']);
			$fieldset->addElement($fopCcVal[$idOffer]);
		}

		// control visibility of CC fields
		if ($offConfCfg['formOfPayment']!='invisible') {
			$ctrlElem = [];
			foreach ($CFG['offers']['formOfPaymentWithCardDetails'] as $fopNeedsCc) {
				$ctrlElem[$fopNeedsCc] = [$fopCcType[$idOffer], $fopCcDet[$idOffer], $fopCcApprCode[$idOffer], $fopCcVal[$idOffer]];
			}
			$fopFlds[$idOffer]->setControlledElements( $ctrlElem );
		}


		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// form of cashing
		if ($offConfCfg['formOfCashing']!='invisible') {
			$focFlds[$idOffer] = new \App\Form\Input\Select_OfferFormOfCashing($_LANG['reservations']['offerDetails']['fields']['foc'], "offer[{$idOffer}][formOfCashing]", $R['offer'][$idOffer]['formOfCashing']);
			$focFlds[$idOffer]->showDefaultOption();
			if ($offConfCfg['formOfCashing']=='mandatory') {
				$focFlds[$idOffer]->setMandatory();
			}
			$fieldset->addElement($focFlds[$idOffer]);
		}

		// form of cashing type
		if ($offConfCfg['formOfCashing']!='invisible') {
			$focCcType[$idOffer] = new \App\Form\Input\Select_CreditCards($_LANG['reservations']['offerDetails']['fields']['focPayType'], "offer[{$idOffer}][formOfCashingCcType]", $R['offer'][$idOffer]['formOfCashingCcType']);
			$focCcType[$idOffer]->addCorporatesCards($service->order->idCorporatesList);
			$focCcType[$idOffer]->addCustomersCards($service->idCustomersList);
			if ($offer->cashingCcEntityType=='manual' and $offer->cashingCcEntityId) {
				$focCcType[$idOffer]->addManualCards( [ $offer->cashingCcEntityId ] );
			}
			$focCcType[$idOffer]->addNewCard(true);
			$focCcType[$idOffer]->showDefaultOption();
			$fieldset->addElement($focCcType[$idOffer]);
		}

		// form of cashing CC details
		if ($offConfCfg['formOfCashing']!='invisible') {
			$focCcDet[$idOffer] = new \App\Form\Input\CreditCardDetails($_LANG['reservations']['offerDetails']['fields']['focPayDet'], "offer[{$idOffer}][formOfCashingCcDet]", $R['offer'][$idOffer]['formOfCashingCcDet']);
			$fieldset->addElement($focCcDet[$idOffer]);

			$focCcType[$idOffer]->setControlledElements( [ 'new'=>[$focCcDet[$idOffer]] ], 'disable' );
		}

		// CC - cashing approval code
		if ($offConfCfg['formOfCashing']!='invisible') {
			$focCcApprCode[$idOffer] = new \Engine\Form\Input\Text($_LANG['reservations']['offerDetails']['fields']['focPayApprCode'], "offer[{$idOffer}][formOfCashingCcApprovalCode]", $R['offer'][$idOffer]['formOfCashingCcApprovalCode']);
			$fieldset->addElement($focCcApprCode[$idOffer]);
		}

		// control visibility of CC fields
		if ($offConfCfg['formOfCashing']!='invisible') {
			$ctrlElem = [];
			foreach ($CFG['offers']['formOfCashingWithCardDetails'] as $focNeedsCc) {
				$ctrlElem[$focNeedsCc] = [ $focCcType[$idOffer], $focCcDet[$idOffer], $focCcApprCode[$idOffer] ];
			}
			$focFlds[$idOffer]->setControlledElements( $ctrlElem );
		}

	}

	$form->addElement(new \Engine\Form\Input\Hidden('', 'saveData', 1));
}


// ------------------------------------------------------------------------------------------------
$smarty->assign('pageTitle', 		$_LANG['reservations']['offerDetails']['pageTitle']);
$smarty->assign('sectionTitle', 	$_LANG['reservations']['offerDetails']['headerTitle']);

$smarty->assign("reloadParent", $reloadParent);

$smarty->assign("closePopup", $closePopup);

$smarty->display('index.tpl');
