<?php

namespace App\GenDocument\SpecialObject;

/**
 * The class generates the content of the reservationCumulativeOffer special object. Each record
 * represents a service.
 * @author Gabriel
 */
class ReservationCumulativeOffer extends TableAbstract
{

	/**
	 * The list of service totals.
	 * @var array
	 */
	private $totals=[];


	/**
	 * Populates the servicesList and totals attributes.
	 * @see TableAbstract::table_populateRows()
	 */
	protected function table_populateRows()
	{

		// LOOP THROUGH EACH SERVICE ON THIS RESERVATION //////////////////////////////////////////

		$rows = [];
		$totals = [];
		$idx=0;

		// see which service codes are allowed to be displayed
		$allowedServiceCodesBulk = explode(",", $this->settings['filterServices']);
		// trim() each specified service code
		$allowedServiceCodes = [];
		foreach($allowedServiceCodesBulk as $serviceCode){
			$serviceCode = trim($serviceCode);
			if ($serviceCode) {
				$allowedServiceCodes[$serviceCode] = $serviceCode;
			}
		}

		// get services in the correct order
		if ($this->extraParams['servicesList']) {
			$selectedServicesList = $this->extraParams['servicesList'];
		} else {
			$selectedServicesList = array_keys(\Entity\Order::select($this->idPivot)->servicesList);
		}
		// compose a list of services that are selected and in the correct order
		$servicesList = [];
		foreach ( \Entity\Order::select($this->idPivot)->sortedServicesSegmentsFinal as $serviceComponent) {
			if ( !in_array($serviceComponent['idService'], $servicesList) and in_array($serviceComponent['idService'], $selectedServicesList) ) {
				$servicesList[] = $serviceComponent['idService'];
			}
		}

		foreach($servicesList as $idServ) {

			// get service object
			$serv = \Entity\Service::select($idServ);

			// skip non-OK services
			if ($serv->statusOp!='OK') continue;

			if ($allowedServiceCodes && !$allowedServiceCodes[$serv->serviceCode]){
				continue;	// skip processing, go to the next service in the list
			}

			$idx++;

			$off = $serv->chosenOffer;


			// COLLECT INFO INTO A NEW ROW --------------------------------------------------------
			$row = [];

			// current number
			$row['currentNumber'] = ['content'=>$idx];
			//service
			$row['service'] = ['content'=>$serv->service];
			// destination
			$row['destination'] = ['content'=>$serv->chosenOffer->destinationCity->name];
			if ($serv->chosenOffer->destinationCountry->name) {
				$row['destination']['content'] .= " ({$serv->chosenOffer->destinationCountry->name})";
			}
			// passengers
			$psgs=[];
			foreach($serv->idCustomersList as $idCust) {
				$psgs[]=\Entity\Customer::select($idCust)->name;
			}
			$row['passengers'] =  ['content'=>implode(', ', $psgs)];
			// tkt nos
			$row['ticketNumber'] =  ['content'=>implode(', ', $serv->passengersTicketsList)];
			// ext res det
			$row['extResId'] = ['content'=>$serv->chosenOffer->externalSystemReservationId];
			$row['extResDate'] =  ['content' => $serv->chosenOffer->externalSystemReservationDate, 'type' => 'date'];
			// supplier details
			$row['supplier'] = ['content'=>$serv->chosenOffer->supplier->alias];
			// supplier service
			$row['supplierService'] = ['content'=>$off->relevantProductName];

			// start/end date
 			$row['startDate'] = ['content'=> $serv->chosenOffer->startDate, 'type' => 'date'];
			$row['endDate'] = ['content'=> $serv->chosenOffer->endDate, 'type' => 'date'];
			// service attributes
			$servAttr=[];
			if ($serv->categoryReadable) $servAttr[]=$serv->categoryReadable;
			if ($serv->productTypeReadable) $servAttr[]=$serv->productTypeReadable;
			if ($serv->multiplierReadable) $servAttr[]=$serv->multiplierReadable;
			$row['serviceAttributes']= ['content'=>implode(', ', $servAttr)];
			// service attributes one by one
			$row['serviceCategory']= ['content'=>$serv->categoryReadable];
			$row['serviceProductType']= ['content'=>$serv->productTypeReadable];
			$row['serviceMultiplier']= ['content'=>$serv->multiplierReadable];
			$row['serviceSource']= ['content'=>$serv->serviceSourceReadable];
			// prices
			$row['priceSupplierPrice']= ['content'=>round($off->supplierWorkValue+$off->supplierWorkVat, 2), 'type'=>'price'];
			$row['priceCommission']= ['content'=>round($off->commissionWorkValue+$off->commissionWorkVat, 2), 'type'=>'price'];
			$row['priceServicePrice']= ['content'=>round($off->supplierWorkValue+$off->supplierWorkVat+$off->commissionWorkValue+$off->commissionWorkVat, 2), 'type'=>'price'];
			$row['priceDiscount']= ['content'=>round(-$off->discountWorkValue-$off->discountWorkVat, 2), 'type'=>'price'];
			$row['priceServiceFee']= ['content'=>round($off->serviceFeeWorkValue+$off->serviceFeeWorkVat, 2), 'type'=>'price'];
			$row['priceTax']= ['content'=>round($off->taxWorkValue+$off->taxWorkVat, 2), 'type'=>'price'];
			$row['priceTotal']= ['content'=>round($off->offerWorkTotal, 2), 'type'=>'price'];
			$row['currency']= ['content'=>$off->totalCurrency];
			// offer equiv totals
			$row['priceTotalDefCurr']= ['content'=>round($off->offerTotalDefCurr, 2), 'type'=>'price'];
			$row['priceTotalWorkCurr']= ['content'=>round($off->offerTotalWorkCurr, 2), 'type'=>'price'];

			// determine the prices
			$totals['priceTotalDefCurr']+=round($off->offerTotalDefCurr, 2);
			$totals['priceTotalWorkCurr']+=round($off->offerTotalWorkCurr, 2);

			$rows[]=$row;

		}

		$this->totals = $totals;
		$this->tableRows = $rows;

	}


	/**
	 * Defines the table footer (the totals row).
	 */
	protected function render_table_addTableFoot()
	{

		// if no totals set to be displayed - method is skipped
		if (!$this->settings['showTotals']) return;

		// the totals row
		$finalRow = new \DTMControl_table_tr();

		// loop through each cell and fill in its content
		foreach($this->tableColumns as $col=>$nothing) {

			// determine cell content (total price or blank row)
			if ($col=='priceTotalDefCurr' or $col=='priceTotalWorkCurr') {
				$cellContent=$this->totals[$col];
			} else {
				$cellContent='';
			}

			// add cell to the row
			$finalRow->add_td(
				[
					'fontFamily'=>$this->settings['totalsFont'],
					'style_bold'=>(bool)$this->settings['totalsTextStyle']['bold'],
					'style_italic'=>(bool)$this->settings['totalsTextStyle']['italic'],
					'style_underline'=>(bool)$this->settings['totalsTextStyle']['underline'],
					'fontSize'=>$this->settings['totalsFontSize'],
					'color'=>$this->settings['totalsTextColor'],
					'backgroundColor'=>$this->settings['totalsBackgroundColor'],
					'text'=>$cellContent,
					'colspan'=>1,
					'align'=>"right"
				]
			);

		}

		// associate this row to the table
		$this->table->add_tr($finalRow);

	}


}
