<?php

// CHECK IF ANY OF THE LOOP RECORD COLUMNS WERE SELECTED //////////////////////////////////////////
$loopRecColumns = [
	'serv_definedPsgListStd', 'serv_ticketNumberList',
	'inv_estProfitInvCurr', 'inv_estProfitDefCurr', 'inv_estProfitWorkCurr',
	'bal_profitBaseDefCurr', 'bal_profitVatDefCurr', 'inv_idsList',
	'serv_pax_a', 'serv_pax_c', 'serv_pax_i', 'ord_corporateList', 'ord_idsList', 'inv_cashingListDoc', 'inv_cashingListDocTypes',
	'bal_profitVatPercentCfg'
];
if (!array_intersect($availableTableColumns, $loopRecColumns)) {
	return ;
}

// START THE LOOP RECORDS ROUTINE /////////////////////////////////////////////////////////////////
$recordsCountSQL = "SELECT COUNT(*) FROM `$reportTable`";
$recordsCount = $db->GetOne($recordsCountSQL);

// BREAK INTO RECORDS GROUPS //////////////////////////////////////////////////////////////////////
$groupSize = 1000;
for ($startGroup = 0; $startGroup < $recordsCount; $startGroup += $groupSize) {
	// refresh report status
	refreshReportStatus('processingRecords', 'loopResults', $startGroup/$recordsCount*100);

	// GET RECORDS TO BE UPDATED //////////////////////////////////////////////////////////////////
	$getRecordsListSQL = "SELECT * FROM `$reportTable` LIMIT ".$startGroup.", ".$groupSize;
	$recordsList = $db->GetAll($getRecordsListSQL);

	// check SQL
	if ($db->ErrorNo()) killReport("Could not run SQL in report. SQL: ".$getServicesListSQL);

	// UPDATE RECORDS ONE BY ONE //////////////////////////////////////////////////////////////////
	foreach ($recordsList as $thisRow) {

		$updateColumns = [];

		// SERVICE DETAILS ------------------------------------------------------------------------
		if ($tableColumns['serv_definedPsgListStd'] or
			$tableColumns['bal_profitBaseDefCurr'] or $tableColumns['bal_profitVatDefCurr'] or
			$tableColumns['inv_estProfitInvCurr'] or $tableColumns['inv_estProfitDefCurr'] or $tableColumns['inv_estProfitWorkCurr'] or
			$tableColumns['serv_pax_a'] or $tableColumns['serv_pax_c'] or $tableColumns['serv_pax_i'] or $tableColumns['inv_idsList']
		) {
			$serv = new \App\ReportsData\EntityFields\Service($thisRow['serv_id']);
			if ($tableColumns['serv_definedPsgListStd']) {
				$updateColumns['serv_definedPsgListStd'] = (String)$serv->getValue('definedPassengersNameListStd');
			}
			if ($tableColumns['bal_profitBaseDefCurr']) {
				$updateColumns['bal_profitBaseDefCurr'] = $serv->getValue('balanceProfitBaseDefCurr');
			}
			if ($tableColumns['bal_profitVatDefCurr']) {
				$updateColumns['bal_profitVatDefCurr'] = $serv->getValue('balanceProfitVatDefCurr');
			}

			// invoice estimated profit
			if ($tableColumns['inv_estProfitInvCurr'] or $tableColumns['inv_estProfitDefCurr'] or $tableColumns['inv_estProfitWorkCurr']) {
				$issVals = $serv->getValue('invoiceIssueValues');
				$rfndVals = $serv->getValue('invoiceRefundValues');
				$estIssProfit = $issVals['commission']['val']+$issVals['commission']['vat'] + $issVals['discount']['val']+$issVals['discount']['vat'] + $issVals['serviceFee']['val']+$issVals['serviceFee']['vat'];
				$estRfndProfit = $rfndVals['commission']['val']+$rfndVals['commission']['vat'] + $rfndVals['discount']['val']+$rfndVals['discount']['vat'] + $rfndVals['serviceFee']['val']+$rfndVals['serviceFee']['vat'];
				$estProfit = $estIssProfit + $estRfndProfit;
				if ($tableColumns['inv_estProfitInvCurr']) {
					$updateColumns['inv_estProfitInvCurr'] = $estProfit;
				}
				if ($tableColumns['inv_estProfitDefCurr']) {
					$updateColumns['inv_estProfitDefCurr'] = $estProfit*$serv->getValue('invoiceCurrencyRate');
				}
				if ($tableColumns['inv_estProfitWorkCurr']) {
					$updateColumns['inv_estProfitWorkCurr'] = $estProfit*$serv->getValue('invoiceCurrencyRate')/$serv->getValue('invoiceWorkCurrencyRate');
				}
			}

			// service pax
			if ($tableColumns['serv_pax_a'] or $tableColumns['serv_pax_c'] or $tableColumns['serv_pax_i']) {
				$paxDetails = $serv->getValue('paxDetails');

				foreach($paxDetails as $type=>$cnt) {
					if ($tableColumns['serv_pax_'.$type]) {
						$updateColumns['serv_pax_'.$type] = $cnt;
					}
				}
			}

			// invoices list
			if ($tableColumns['inv_idsList']) {
				$updateColumns['inv_idsList'] = implode(', ', (array)$serv->getValue('invoicesIds'));
			}
		}

		if ($tableColumns['serv_ticketNumberList'] and $thisRow['serv_ticketNumberList']) {
			$tkts = array_filter( (array)json_decode($thisRow['serv_ticketNumberList'], true) );
			if ($tkts) {
				$updateColumns['serv_ticketNumberList'] = implode(', ', $tkts);
			} else {
				$updateColumns['serv_ticketNumberList'] = '';
			}
		}

		if ($tableColumns['ord_corporateList']) {
			$order = new \App\ReportsData\EntityFields\Order($thisRow['ord_id']);
			$idCorporates = $order->getValue('idCorporates');

			if ($idCorporates) {
				$corporates = [];
				foreach ($idCorporates as $idCorp) {
					$corpObj = new \App\ReportsData\EntityFields\Corporate($idCorp);
					$corporates[] = $corpObj->getValue('alias');
				}

				$updateColumns['ord_corporateList'] = implode(', ', $corporates);
			}
			else {
				$updateColumns['ord_corporateList'] = '';
			}
		}

		if ($tableColumns['inv_cashingListDoc']) {
			$inv = new \App\ReportsData\EntityFields\ClientInvoice($thisRow['inv_id']);
			$updateColumns['inv_cashingListDoc'] = (String)$inv->getValue('cashingDocListConverted');
		}

		if ($tableColumns['bal_profitVatPercentCfg']) {
			$updateColumns['bal_profitVatPercentCfg'] = \App\Config\BalancedServiceVatPercent::getInstance()->getServiceCalculationVatPercent($thisRow['off_serviceCode'], $thisRow['off_locationCode'], $thisRow['off_calculationTypeCode'])/100;
		}


		// FINISH AND EXECUTE SQL -----------------------------------------------------------------
		if ($updateColumns) {
			$colsList = implode(', ', array_map(function($col){ return "`{$col}` = ?"; }, array_keys($updateColumns)));
			$updateRecordSQL = "UPDATE `$reportTable` SET {$colsList} WHERE serv_id='".$thisRow['serv_id']."'";
			$updateRecordEx = $db->Execute($updateRecordSQL, array_values($updateColumns));
			if ($db->ErrorNo()) {
				killReport("Could not run SQL in report. SQL: ".$updateRecordSQL);
			}
		}

	}
}

// cleanup last records list array
unset($recordsList);


