<?php
namespace Modules\Admin\ExportData\ClientInvoices;

class Export
{
	/**
	 * Gets the sorted existing configs form DB
	 * @param array $fieldsCodes
	 * @return array
	 */
	public function getRulesList(Array $criteriaFields, Array $fieldsCodes)
	{
		global $DBTExportData_clientInvoices;

		$bindVars = [];
		// get existing configurations from db
		$getConfigsSQL = "SELECT `serviceCode`, `location`, `calculationType`, `rowType`, `clientType`, `currency`, `advanceInvoice`, `field`, `value`,
			CONCAT_WS('|', RPAD(`serviceCode`, 2, ' '), RPAD(`location`, 10, ' '), RPAD(`calculationType`, 2, ' '), RPAD(`rowType`, 15, ' '), RPAD(`clientType`, 20, ' '), RPAD(`currency`, 3, ' '), `advanceInvoice`) as `criteriaFieldsOrder`
			FROM `$DBTExportData_clientInvoices` AS clientInvoices
			WHERE
				1";

		$getConfigsSQL.=" AND clientInvoices.field IN (".str_pad('',count($fieldsCodes)*2-1,'?,').")";
		$bindVars = $fieldsCodes;

		if ($criteriaFields['serviceCode']) {
			$getConfigsSQL.=" AND clientInvoices.serviceCode IN (?, '*')";
			$bindVars[] = $criteriaFields['serviceCode'];
		}

		if ($criteriaFields['location']) {
			$getConfigsSQL.=" AND clientInvoices.location IN (?, '*')";
			$bindVars[] = $criteriaFields['location'];
		}

		if ($criteriaFields['calculationType']) {
			$getConfigsSQL.=" AND clientInvoices.calculationType IN (?, '*')";
			$bindVars[] = $criteriaFields['calculationType'];
		}

		if ($criteriaFields['rowType']) {
			$getConfigsSQL.=" AND clientInvoices.rowType IN (?, '*')";
			$bindVars[] = $criteriaFields['rowType'];
		}

		if ($criteriaFields['clientType']) {
			$getConfigsSQL.=" AND clientInvoices.clientType IN (?, '*')";
			$bindVars[] = $criteriaFields['clientType'];
		}

		if ($criteriaFields['currency']) {
			$getConfigsSQL.=" AND clientInvoices.currency IN (?, '*')";
			$bindVars[] = $criteriaFields['currency'];
		}

		if (isset($criteriaFields['advanceInvoice'])) {
			$getConfigsSQL.=" AND clientInvoices.advanceInvoice IN (?, '*')";
			$bindVars[] = $criteriaFields['advanceInvoice'];
		}

		$getConfigsSQL.=" ORDER BY criteriaFieldsOrder ASC";

		$existingConfigsData = \DB::getInstance()->Execute($getConfigsSQL, $bindVars);
		return $existingConfigsData->getAll();
	}
}