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

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

		$bindVars = [];
		// get existing configurations from db
		$getConfigsSQL = "SELECT `serviceCode`, `rowType`, `location`, `vatType`, `currency`, `field`, `value`,
			CONCAT_WS('|', RPAD(`serviceCode`, 2, '#'), RPAD(`rowType`, 20, '#'), RPAD(`location`, 10, '#'), RPAD(`vatType`, 50, '#'), RPAD(`currency`, 3, '#')) as `criteriaFieldsOrder`
			FROM `$DBTExportData_supplierInvoices` AS supplierInvoices
			WHERE
				1";

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

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

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

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

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

		$getConfigsSQL.=" ORDER BY criteriaFieldsOrder ASC";

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