<?php

namespace Modules\RemoteData\InfoBox;


class View_Customer extends \App\Mvc\View_RemoteDataInfoBoxEntityAbstract
{

	/**
	 * (non-PHPdoc)
	 * @see \App\Mvc\View_RemoteDataInfoBoxEntityAbstract::getEntityRemoteDetails()
	 */
	protected function getEntityRemoteDetails(\App\Entity\SelectAbstract $entity)
	{

		// load global config
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();
		$_LANG = \App\Loader_Lang::getInstance()->getAll();

		$defCurr = \App\Config\Currencies::getInstance()->getDefaultCurrency();

		// the output object
		$output = \Engine\RemoteData\InfoBox\Container_Main::create( $entity->name )
			->setShortTitle($entity->name)
			->setId(sprintf("%s.%s", __CLASS__, $entity->getId()));


		if (!\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Customers-remoteDetails')) {

			$output->addField( \Engine\RemoteData\InfoBox\Field_String::create(null, $_LANG['noAccessToOption']) );
			return $output;
		}

		// dashboard
		if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToSection('Modules/Partners/Customers/Dashboard')) {
			$icon = \Engine\RemoteData\InfoBox\Icon\Icon::create('quickNav');
			$icon->setTooltip($this->lang['customer']['option']['dashboard']);
			$icon->setJsCallback("customerDashboard('{$entity->getId()}');");
			$icon->setIcon("quickNav");
			$output->addIcon($icon);
		}

		// add frequent buyer card
		if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Customers/FrequentBuyerCards-insert')) {
			$icon = \Engine\RemoteData\InfoBox\Icon\Icon::create('insert');
			$icon->setTooltip($this->lang['customer']['option']['insertCard']);
			$icon->setJsCallback("Popup2.create().setId('cardInsertWindow').setUrl(MVC.appUrl('Partners/Customers/FrequentBuyerCards', 'insert', {'idCustomer': {'id':'{$entity->getId()}'}})).setDimensions(760, 570).show();");
			$icon->setIcon("card");
			$output->addIcon($icon);
		}

		// customer update button
		if (\App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Customers-update')) {
			$icon = \Engine\RemoteData\InfoBox\Icon\Icon::create('edit');
			$icon->setTooltip($this->lang['customer']['option']['update']);
			$icon->setJsCallback("customerUpdate('{$entity->getId()}');");
			$output->addIcon($icon);
		}

		// customer profile edit
		if ( \App\UserAccess\CurrentUserAccessFast::getInstance()->hasAccessToOption('Modules/Partners/Customers-profile')) {
			$icon = \Engine\RemoteData\InfoBox\Icon\Icon::create('profile');
			$icon->setTooltip($this->lang['customer']['option']['profile']);
			$icon->setJsCallback("Popup2.create().setId('customerProfile').setUrl( MVC.appUrl('Partners/Customers/Profile', 'index', { 'id': '{$entity->getId()}'}) ).setDimensions(700, 500).show();return false;");
			$output->addIcon($icon);
		}

		// BASIC INFO -----------------------------------------------------------------------------
		$cont1 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['general']['titles']['general']);
		$output->addContainer($cont1);

		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['general']['fields']['id'], $entity->getId()) );

		$name = $entity->nameStandard;
		if($CFG['useAlternativeNames']['customers'] && $entity->nameLocal) {
			$name .= sprintf(" (%s)", $entity->nameLocal);
		}
		$middleName = $entity->middleName;
		if($CFG['useAlternativeNames']['customers'] && $entity->middleName2) {
			$middleName .= sprintf(" (%s)", $entity->middleName2);
		}
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['name'], $name) );
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['middleName'], $middleName) );
		$cont1->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['customer']['fields']['corporateName'], \Entity\Corporate::select($entity->idCorporate)->alias)->setEntity('corporate', $entity->idCorporate) );
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['department'], $entity->department) );
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['type'], $_LANG['generalData']['personTypes'][$entity->type]) );
		$cont1->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['customer']['fields']['idParent'], \Entity\Customer::select($entity->idParent)->name)->setEntity('customer', $entity->idParent) );
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['locked'], $entity->locked?$_LANG['yes']:'')->setStyle('bold') );
		$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['segment'], $entity->segment->name) );
		$cont1->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['customer']['fields']['manager'], $entity->accountManager->name)->setEntity('user', $entity->idAccountManager) );
		if ($entity->flag) { //TODO add real support for icons
			$cont1->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['flag'], sprintf('<a class="imgIcon icon-marker%s"></a>%s', $entity->flag, \App\Config\CustomersFlags::getInstance()->get($entity->flag))) );
		}

		// Duplicated Customer info
		if ($entity->idRealCustomer) {
			$cont9 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['realCustomer'])->setHidden(true);
			$output->addContainer($cont9);
			$cont9->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create(null, \Entity\Customer::select($entity->idRealCustomer)->name)->setEntity('customer', $entity->idRealCustomer) );
		}

		if ($entity->duplicatedPassengers) {
			$cont10 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['duplicatedPassengers'])->setHidden(true);
			$output->addContainer($cont10);
			foreach ($entity->duplicatedPassengers as $idPassenger) {
				$cont10->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create(null, \Entity\Customer::select($idPassenger)->name)->setEntity('customer', $idPassenger) );
			}

		}

		// DEBIT BALANCE
		if ($entity->equivDebitBalance) {
			$equivBalance = [
				'amount' => 	$entity->equivDebitBalance,
				'currency' => $defCurr,
				'displayCurrency' =>	sprintf("%s (%s)", $defCurr, $this->lang['customer']['fields']['equivalent']),
			];
			$cont1->addField(\Engine\RemoteData\InfoBox\Field_Price::create($this->lang['customer']['fields']['debitBalance'], $equivBalance));

			$c3 = \Engine\RemoteData\InfoBox\Container_Simple::create();
			$cont1->addContainer($c3);

			$c3->setCollapsible(false);
			$c3->setType('section');

			foreach ($entity->debitBalanceDetails as $currency=>$value) {
				$c3->addField(  \Engine\RemoteData\InfoBox\Field_Price::create($currency, ['amount'=>$value, 'currency'=>$currency]));
			}
		}

		// CREDIT BALANCE
		if ($entity->equivCreditBalance) {
			$equivCreditBalance = ['amount'=>$entity->equivCreditBalance, 'currency'=>$defCurr, 'displayCurrency'=>sprintf("%s (%s)", $defCurr, $this->lang['corporate']['fields']['equivalent'])];
			$cont1->addField( \Engine\RemoteData\InfoBox\Field_Price::create($this->lang['customer']['fields']['creditBalance'], $equivCreditBalance) );

			$c4 = \Engine\RemoteData\InfoBox\Container_Simple::create();
			$cont1->addContainer($c4);

			$c4->setCollapsible(false);
			$c4->setType('section');

			foreach ($entity->creditBalanceDetails as $currency=>$value) {
				$c4->addField(  \Engine\RemoteData\InfoBox\Field_Price::create($currency, ['amount'=>$value, 'currency'=>$currency]));
			}
		}

		// OPERATIONAL BALANCE
		if ($entity->equivOperationalBalance) {
			$equivOperationalBalance = ['amount'=>$entity->equivOperationalBalance, 'currency'=>sprintf("%s (%s)", $defCurr, $this->lang['corporate']['fields']['equivalent'])];
			$cont1->addField( \Engine\RemoteData\InfoBox\Field_Price::create($this->lang['customer']['fields']['operationalBalance'], $equivOperationalBalance) );

			$c4 = \Engine\RemoteData\InfoBox\Container_Simple::create();
			$cont1->addContainer($c4);

			$c4->setCollapsible(false);
			$c4->setType('section');

			foreach ($entity->operationalBalanceDetails as $currency=>$value) {
				$c4->addField(  \Engine\RemoteData\InfoBox\Field_Price::create($currency, ['amount'=>$value, 'currency'=>$currency]));
			}
		}


		// PERSONAL INFO
		$cont8 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['personalInfo']);
		$output->addContainer($cont8);

		$cont8->addField( \Engine\RemoteData\InfoBox\Field_Date::create($this->lang['customer']['fields']['birthday'], \Engine\DateTime::createFromIsoDate($entity->birthday)) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['ID_series'], $entity->ID_series) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['ID_number'], $entity->ID_number) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_Date::create($this->lang['customer']['fields']['ID_releaseDate'], \Engine\DateTime::createFromIsoDate($entity->ID_releaseDate)) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['ID_releaseBy'], $entity->ID_releaseBy) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_Date::create($this->lang['customer']['fields']['ID_expireDate'], \Engine\DateTime::createFromIsoDate($entity->ID_expireDate)) );
		$cont8->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['PNC'], $entity->PNC) );

		// CONTACT INFO
		$cont2 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['general']['titles']['contact']);
		$output->addContainer($cont2);

		$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['address'], $entity->address) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['deliveryAddress'], $entity->deliveryAddress) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['composedAddress'], $entity->composedAddress) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['composedDeliveryAddress'], $entity->composedDeliveryAddress) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['zipCode'], $entity->zipCode) );
		if ($entity->cityId) {
			$cont2->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['general']['fields']['city'], $entity->city->name)->setEntity('city', $entity->cityId) );
		} elseif ($entity->countryCode) {
			$cont2->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['country'], $entity->country->name) );
		}
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_Telephone::create($this->lang['customer']['fields']['telephone'], $entity->telephone) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_Telephone::create($this->lang['customer']['fields']['telephoneMobile'], $entity->telephoneMobile) );
		$cont2->addField( \Engine\RemoteData\InfoBox\Field_Email::create($this->lang['customer']['fields']['email'], $entity->email) );

		// BANK INFO
		$cont3 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['bank'])->setHidden(true);
		$output->addContainer($cont3);

		$cont3->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['bank'], $entity->bank->name) );
		$cont3->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['bankAccount'], $entity->bankAccount) );

		// FB CARDS INFO
		$cont4 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['fbCards']);
		$output->addContainer($cont4);

		$fbCardsList = \Entity\Customer::select($entity->getId())->frequentBuyerCards;
		if ($fbCardsList) {
			foreach ($fbCardsList as $idCard=>$card) {
				//TODO add suppliers using EntityInfoBoxes
				$suppNames = [];
				foreach ($card['idSuppliers'] as $idSupp) {
					$suppNames[] = \Entity\Supplier::select($idSupp)->alias;
				}
				$fbCard = sprintf("%s (%s)", $card['cardNumber'], implode(", ", $suppNames));
				$cont4->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create(null, $fbCard)->setEntity('frequentBuyerCard', $idCard) );
			}
		}

		// PASSPORTS
		$contP = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['customer']['titles']['passports']);
		$contP->setHidden(true);
		$output->addContainer($contP);

		$i = 1;
		foreach ($entity->passports as $pass) {
			$fld1 = \Engine\RemoteData\InfoBox\Field_String::create($this->lang['customer']['fields']['document'].' #'.$i, $pass['number'].($pass['defaultPassport']?' (default)':''));
			$fld2 = \Engine\RemoteData\InfoBox\Field_String::create('&bull; '.$this->lang['customer']['fields']['type'], $_LANG['generalData']['passportTypes']['type'][$pass['type']]);
			$fld3 = \Engine\RemoteData\InfoBox\Field_String::create('&bull; '.$this->lang['customer']['fields']['name'], trim(sprintf("%s %s", $pass['lastName'], $pass['firstName'])));
			$fld4  =\Engine\RemoteData\InfoBox\Field_Date::create('&bull; '.$this->lang['customer']['fields']['issueDate'], \Engine\DateTime::create($pass['issueDate']));
			$fld5 = \Engine\RemoteData\InfoBox\Field_Date::create('&bull; '.$this->lang['customer']['fields']['expireDate'], \Engine\DateTime::create($pass['expireDate']));
			$fld6 = \Engine\RemoteData\InfoBox\Field_String::create('&bull; '.$this->lang['customer']['fields']['citizenship'], \Entity\Country::select($pass['citizenship'])->name);
			$fld1->setStyle('bold');

			$contP->addField( $fld1 );
			$contP->addField( $fld2 );
			$contP->addField( $fld3 );
			$contP->addField( $fld4 );
			$contP->addField( $fld5 );
			$contP->addField( $fld6 );

			$i++;
		}

		// MISC INFO ------------------------------------------------------------------------------
		$cont6 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['general']['titles']['misc'])->setHidden(true);
		$output->addContainer($cont6);
		$cont6->addField( \Engine\RemoteData\InfoBox\Field_Remarks::create($this->lang['general']['fields']['remarks'], $entity->remarks) );

		// PROCESSED REMARKS
		$cRmk = \Engine\RemoteData\InfoBox\Container_ProcessedRemarks::create($this->lang['general']['fields']['processedRemarks'])->setHidden(true);
		$cRmk->addRemarkFields('customer', $entity->processedRemarks);
		$output->addContainer($cRmk);


		// UPDATE INFO
		$cont7 = \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['general']['titles']['updates'])->setHidden(true);
		$output->addContainer($cont7);

		$cont7->addField( \Engine\RemoteData\InfoBox\Field_DateTime::create($this->lang['general']['fields']['addTime'], \Engine\DateTime::createFromTimestamp($entity->addTime)) );
		$cont7->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['general']['fields']['addUser'], $entity->addUser->name)->setEntity('user', $entity->idAddUser) );
		$cont7->addField( \Engine\RemoteData\InfoBox\Field_DateTime::create($this->lang['general']['fields']['updateTime'], \Engine\DateTime::createFromTimestamp($entity->lastUpdateTime)) );
		$cont7->addField( \App\RemoteData\InfoBox\Field_EntityInfoBox::create($this->lang['general']['fields']['updateUser'], $entity->updateUser->name)->setEntity('user', $entity->idUpdateUser) );
		if ($entity->updatesCount) {
			$cont7->addField( \Engine\RemoteData\InfoBox\Field_String::create($this->lang['general']['fields']['updatesCount'], $entity->updatesCount) );
		}

		//Customer profile files
		$customerProfileFilesContainer	= \Engine\RemoteData\InfoBox\Container_Simple::create($this->lang['general']['titles']['files']);
		$customerProfileFilesContainer->setType('ol');
		$customerProfileFilesContainer->setCollapsible(true);
		$customerProfileFilesContainer->setHidden(true);
		$output->addContainer($customerProfileFilesContainer);

		foreach ($entity->filesList as $file) {
			$fileField = \Engine\RemoteData\InfoBox\Field_Url::create('', [
				'label' => \Engine\File::getName($file),
				'value' => \Engine\Mvc\Dispatcher::getInstance()->getAppUrl('Modules/Partners/Customers', 'downloadFile', [
					'idCustomer' => $entity->getId(),
					'file' => $file
				]),
			]);

			$customerProfileFilesContainer->addField($fileField);
		}

		return $output;
	}

}
