<?php

namespace Modules\Admin\ImportEntities\Model\Import;

class OfferProfileRulesInsert extends \Modules\Admin\ImportEntities\Model\ImportAbstract
{

	/**
	 * The list of fields available for this import.
	 * @var array
	 */
	protected $fields = [ 'name', 'servicesCode', 'departureAreaCode', 'destinationAreaCode',
		'classCode', 'className', 'companyId', 'supplierId', 'supplierCategory', 'bookingOffice', 'operation', 'offerGlobalArea', 'offerGlobalDestination', 'flightType',
		'servicePriceOperation', 'servicePriceValue', 'servicePriceCurrency', 'totalPriceOperation', 'totalPriceValue', 'totalPriceCurrency',
		'extResSystem', 'reissue', 'miceProject', 'offerLocation',
		'serviceFeeMode', 'serviceFeeAppliedFrom', 'serviceFeeValue', 'serviceFeeCurrency', 'serviceFeePercent',
		'commissionIncluded', 'commissionValue', 'commissionCurrency', 'commissionPercent',
	];

	/**
	 * Used for displaying some info in the form
	 * @var array
	 */
	public $allowsMultiple = ["servicesCode", "departureAreaCode", "destinationAreaCode",
		"className", "classCode", "companyId", "supplierId", "bookingOffice", "supplierCategory", "operation", "offerGlobalArea", "globalDestination", "flightType", 'miceProject',
	];


	/**
	 * {@inheritDoc}
	 * @see \Modules\Admin\ImportEntities\Model\ImportAbstract::process()
	 */
	public function process()
	{
		$_LANG = \App\Loader_Lang::getInstance()->getGlobal();

		$messagesFromImport = new \App\MessagesCollector();
		$count = 0;

		foreach($this->fileData as $row) {
			$count++;
			try {
				\DB::startTransaction();

				$offerProfileRuleObj = \Entity\OfferProfileRule::insert();

				$offerProfileRuleObj->active 	= TRUE;
				$offerProfileRuleObj->name 		= $row['name'];

				// validity
				$offerProfileRuleObj->startDate = '0000-00-00';
				$offerProfileRuleObj->endDate = '9999-12-31';

				// corporate list
				$corpList = [];

				if ($row['companyId']) {
					$corpList = array_map('trim', explode(',', $row['companyId']));
				}
				$offerProfileRuleObj->idCorporatesList = $corpList;


				// criteria
				$offerProfileRuleObj->criteria = $this->createCriterionList($row);

				// commission
				if (strlen($row['commissionPercent']) or strlen($row['commissionValue'])) {
					$offerProfileRuleObj->commissionDetails = $this->createOfferDetailsCommission($row);
				} else {
					$offerProfileRuleObj->commissionDetails = null;
				}

				// discount
				$offerProfileRuleObj->discountDetails = null;

				// service fee
				if ($row['serviceFeeMode']) {
					$offerProfileRuleObj->serviceFeeDetails = $this->createOfferDetailsServiceFee($row);
				}
				else {
					$offerProfileRuleObj->serviceFeeDetails = null;
				}

				$offerProfileRuleObj->save();
				$idRule = $offerProfileRuleObj->getId();

				\DB::commitTransaction();
				$messagesFromImport->addSuccess(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['offerProfileRules']['saveOk'], $idRule));
			}
			catch (\App\Entity\Exception $e) {
				\DB::rollbackTransaction();
				$messagesFromImport->addWarning(sprintf($_LANG['Admin']['ImportEntities']['index']['msgs']['offerProfileRules']['saveError'], $count));
				$messagesFromImport->appendMessages($e->getMessagesCollector());
			}
		}

		return $messagesFromImport;

	}

	/**
	 *
	 * @param array $row
	 */
	private function createCriterionList(Array $row)
	{
		$criteria = [];

		// suppliers
		if ($row['supplierId']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_Supplier('equal', array_map('trim', explode(',', $row['supplierId'])));
		}

        // booking office
        if ($row['bookingOffice']) {
            $criteria[] = new \App\OfferProfileRules\Criterion_ImportedServiceBookOffice('equal', array_map('trim', explode(',', $row['bookingOffice'])));
        }

		// services code
		if ($row['servicesCode']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_ServiceCode('equal', array_map('trim', explode(',', $row['servicesCode'])));
		}

		// operations
		if ($row['operation']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_Operation('equal', array_map('trim', explode(',', $row['operation'])));
		}

		// itinerary service class name
		if ($row['className']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_ItineraryServiceClassName('equal', array_map('trim', explode(',', $row['className'])));
		}

		// itinerary service class code
		if ($row['classCode']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_ItineraryServiceClassCode('equal', array_map('trim', explode(',', $row['classCode'])));
		}

		// offer departure country zone
		if ($row['departureAreaCode']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_OfferDeparture_CountryZone('equal', array_map('trim', explode(',', $row['departureAreaCode'])));
		}

		// offer destination country zone
		if ($row['destinationAreaCode']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_OfferDestination_CountryZone('equal', array_map('trim', explode(',', $row['destinationAreaCode'])));
		}

		// offer global area
		if ($row['offerGlobalArea']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_GlobalArea('equal', array_map('trim', explode(',', $row['offerGlobalArea'])));
		}

		// global destination
		if ($row['offerGlobalDestinaton']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_GlobalDestination('equal', array_map('trim', explode(',', $row['offerGlobalDestination'])));
		}
		// flight type
		if ($row['flightType']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_ItineraryTripType('equal', array_map('trim', explode(',', $row['flightType'])));
		}

		// service price
		if ($row['servicePriceOperation']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_ServicePrice($row['servicePriceOperation'], $row['servicePriceValue'], $row['servicePriceCurrency']);
		}

		// total price
		if ($row['totalPriceOperation']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_TotalPrice($row['totalPriceOperation'], $row['totalPriceValue'], $row['totalPriceCurrency']);
		}

		// passenger type
		if ($row['passengerType']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_FirstCustomerType('equal', array_map('trim', explode(',', $row['passengerType'])));
		}

		// extResSystem
		if ($row['extResSystem']) {
			// user inputs as extResSystem the external system CODE => we need to turn this to id
			$extResSystemId = \Entity\ExtResSystem::getSystemIdByCode(trim($row['extResSystem']));
			$criteria[] = new \App\OfferProfileRules\Criterion_ExtResSystem('equal', [$extResSystemId]);
		}

		// reissue
		if ($row['reissue']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_Reissue('equal', [$row['reissue']]);
		}

		// miceProject
		if ($row['miceProject']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_MiceProject('equal', array_map('trim', explode(',', $row['miceProject'])));
		}

		// offerLocation
		if ($row['offerLocation']) {
			$criteria[] = new \App\OfferProfileRules\Criterion_OfferLocation('equal', [$row['offerLocation']]);
		}

        // supplierCategory
        if ($row['supplierCategory']) {
            $criteria[] = new \App\OfferProfileRules\Criterion_SupplierCategory('equal', array_map('trim', explode(',', $row['supplierCategory'])));
        }

		return $criteria;
	}

	/**
	 * Create offerDetailsCommission object
	 * @param Array $row
	 * @return \App\OfferProfileRules\OfferDetails_Commission()
	 */
	private function createOfferDetailsCommission(Array $row)
	{
		$commDet = new \App\OfferProfileRules\OfferDetails_Commission();
		$commDet->included =	trim($row['commissionIncluded']);

		if (strlen($row['commissionPercent'])) {
			$commDet->percent = $row['commissionPercent'];
		}
		elseif (strlen($row['commissionValue'])) {
			$commDet->currency = 	$row['commissionCurrency'];
			$commDet->value = 		$row['commissionValue'];
		}

		return $commDet;
	}

	/**
	 * Create offer details service fee object
	 * @param array $row
	 * @return \App\OfferProfileRules\OfferDetails_ServiceFee()
	 */
	private function createOfferDetailsServiceFee(Array $row)
	{
		$serviceFeeDet = new \App\OfferProfileRules\OfferDetails_ServiceFee();

		$serviceFeeDet->mode 			= trim($row['serviceFeeMode']);
		$serviceFeeDet->percentSource 	= trim($row['serviceFeeAppliedFrom']);

		$percentServiceFee = $valueServiceFee = $currencyServiceFee = '';

		if ($row['serviceFeeMode'] == 'percent') {
			$percentServiceFee = trim($row['serviceFeePercent']);
		}
		else {
			$currencyServiceFee = trim($row['serviceFeeCurrency']);
			$valueServiceFee = trim($row['serviceFeeValue']);
		}

		if ($percentServiceFee != '') {
			$serviceFeeDet->percent = $percentServiceFee;
		}
		elseif ($valueServiceFee != '') {
			$serviceFeeDet->currency = $currencyServiceFee;
			$serviceFeeDet->value = $valueServiceFee;
		}
		return $serviceFeeDet;
	}
}