<?php
namespace App\GenDocument\SpecialObject;

class BalancedServices extends TableAbstract
{

	protected function table_populateRows()
	{
		// get global $CFG
		$CFG = \Engine\Loader_Cfg::getInstance()->getGlobal();

		$balanceEnt = \Entity\Balance::select($this->idPivot);


		// 1. CLIENT INVOICES ROWS
		$rowsTmp = [];
		foreach ($balanceEnt->clientInvoiceRowsList as $idServiceBulk=>$invRowsList) {

			$idService = ($idServiceBulk[0]=='R'?substr($idServiceBulk, 1):$idServiceBulk);
			$isRefund = ($idServiceBulk[0]=='R'?true:false);
			$servEnt  = \Entity\Service::select($idService);

			foreach ($invRowsList as $idRow=>$rowDetails) {
				$invEnt = \Entity\Invoice::select($rowDetails['idInvoice']);
				$valueInInvCurrency = $rowDetails['pricePrintValue'] + $rowDetails['vatPrintValue'];

				// create row
				$groupKey = sprintf("%s-%s-%s", $rowDetails['idInvoice'], $idService, $rowDetails['special']);

				if (!$rowsTmp[$servEnt->serviceCode]['income'][$groupKey]) {
					$rowsTmp[$servEnt->serviceCode]['income'][$groupKey] = [
						'serviceName' 			=> $servEnt->service,
						'incomeOrExpense' 		=> 'income',
						'serviceDetails' 		=> sprintf("%s%s, %s, %s, %s - %s", $servEnt->service, ($isRefund?' [R]':''), $servEnt->destinationCity->name, $servEnt->order->customerOwner->name, \Engine\DateTime::createFromIsoDate($servEnt->startDate)->format("d-M-Y"), \Engine\DateTime::createFromIsoDate($servEnt->endDate)->format("d-M-Y")),
						'invoiceNumber' 		=> $invEnt->invoiceNumber,
						'invoiceDate' 			=> $invEnt->invoiceDate,
						'partnerName' 			=> ($invEnt->idCustomer?$invEnt->customer->name:$invEnt->corporate->alias),
						'valueInInvCurrency'	=> $valueInInvCurrency,
						'invCurrency' 			=> $invEnt->currency,
					];
				}
				else {
					$rowsTmp[$servEnt->serviceCode]['income'][$groupKey]['valueInInvCurrency'] += $valueInInvCurrency;
				}
			}

		}


		// 2. SUPPLIER INVOICES ROWS
		foreach ($balanceEnt->supplierInvoiceRowsList as $idRow) {
			$rowEnt = \Entity\SupplierInvoiceRow::select($idRow);
			$invEnt = $rowEnt->supplierInvoice;
			$valueInInvCurrency = $rowEnt->priceValue + $rowEnt->vatValue;

			// create row
			$groupKey = sprintf("%s", $invEnt->getId());

			if (!$rowsTmp[$rowEnt->serviceCode]['expense'][$groupKey]) {
				$rowsTmp[$rowEnt->serviceCode]['expense'][$groupKey] = [
					'serviceName' 			=> $rowEnt->serviceName,
					'incomeOrExpense' 		=> 'expense',
					'serviceDetails' 		=> $rowEnt->serviceName,
					'invoiceNumber' 		=> $invEnt->invoiceNumber,
					'invoiceDate' 			=> $invEnt->invoiceDate,
					'partnerName' 			=> $invEnt->supplier->alias,
					'valueInInvCurrency'	=> $valueInInvCurrency,
					'invCurrency' 			=> $invEnt->currency,
				];
			}
			else {
				$rowsTmp[$rowEnt->serviceCode]['expense'][$groupKey]['valueInInvCurrency'] += $valueInInvCurrency;
			}

		}


		// RETURN THE ROWS IN THE SPECIAL OBJECT'S FORMAT /////////////////////////////////////////

		$rows = [];
		foreach ($rowsTmp as $serviceCode=>$incomeExpenses) {

			// service header first
			$row = [
				'serviceName' => [
					'content'=>\App\Config\Services_Basic::getAdmin()->getServiceName($serviceCode),
					'type'=>'string'
				],
			];
			$rows[] = $row;

			// service rows
			$subtotal = 0;
			foreach ($incomeExpenses as $incomeOrExpense=>$serviceRows) {
				foreach ($serviceRows as $rowTmp) {

					$valueInDefCurrency = \App\CurrencyExchange\Rates::getInstance($rowTmp['invoiceDate'])->convert($rowTmp['valueInInvCurrency'], $rowTmp['invCurrency'], $CFG['currencies']['defaultCurrency']);

					if ($incomeOrExpense=='income') {
						$subtotal += $valueInDefCurrency;
						$displayValueInInvCurrency = $rowTmp['valueInInvCurrency'];
						$displayValueInDefCurrency = $valueInDefCurrency;
					}
					else {
						$subtotal -= $valueInDefCurrency;
						$displayValueInInvCurrency = (-1)*$rowTmp['valueInInvCurrency'];
						$displayValueInDefCurrency = (-1)*$valueInDefCurrency;
					}

					// create row info
					$row = [
						'serviceName' => [
							'content'=>'',
							'type'=>'string'
						],
						'incomeOrExpense' => [
							'content'=>$incomeOrExpense,
							'type'=>'string'
						],
						'serviceDetails' => [
							'content'=>$rowTmp['serviceDetails'],
							'type'=>'string'
						],
						'invoiceNumber' => [
							'content'=>$rowTmp['invoiceNumber'],
							'type'=>'string'
						],
						'invoiceDate' => [
						    'content' => $rowTmp['invoiceDate'],
							'type'=>'date'
						],
						'partnerName' => [
							'content'=>$rowTmp['partnerName'],
							'type'=>'string'
						],
						'valueInInvCurrency' => [
							'content'=>$displayValueInInvCurrency,
							'type'=>'price'
						],
						'invCurrency' => [
							'content'=>$rowTmp['invCurrency'],
							'type'=>'string'
						],
						'valueInDefCurrency' => [
							'content'=>$displayValueInDefCurrency,
							'type'=>'price'
						],
					];

					$rows[] = $row;
				}
			}

			// service subtotal last
			$row = [
				'invCurrency' => [
					'content'=>$this->settings['tableSubtotalRow'],
					'type'=>'string'
				],
				'valueInDefCurrency' => [
					'content'=>$subtotal,
					'type'=>'price'
				],
			];
			$rows[] = $row;
		}

		$this->tableRows = $rows;
	}

}
