<?php

// CHECK IF ANY OF THE LOOP RECORD COLUMNS WERE SELECTED //////////////////////////////////////////
$loopRecColumns = [
	'row_calculationName',
];
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 = 500;
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 = [];

		if ($tableColumns['row_calculationName'] and $thisRow['row_serviceCode'] and $thisRow['row_locationCode'] and is_numeric($thisRow['row_calculationCode']) and $thisRow['row_calculationCode']>=0) {
			$updateColumns['row_calculationName'] = \App\Config\Services_Calculations::getInstance()->getServiceLocationCalculationName($thisRow['row_serviceCode'], $thisRow['row_locationCode'], $thisRow['row_calculationCode']);
		}

		// FINISH AND EXECUTE SQL -----------------------------------------------------------------
		if ($updateColumns) {
			$colsList = implode(', ', array_map(function($col){ return "`{$col}` = ?"; }, array_keys($updateColumns)));
			$updateRecordSQL = "UPDATE `$reportTable` SET {$colsList} WHERE row_internalId='".$thisRow['row_internalId']."'";
			$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);


