<?php

Lib::loadClass('RouteToolBase');
Lib::loadClass('UI');
Lib::loadClass('Response');
Lib::loadClass('Request');

// index.php?_route=UrlAction_Bocian  - uruchamia defaultAction
class RouteTool_Bocian extends RouteToolBase {

public static $helpEmailTo = 'biuro@bialnet.com.pl'; // todo:email na który zostanie wysłane zapytanie z formularza POMOCY

	public static $FIELD_LIST_PRACOWNICY = [
		'ID',
		'imiona',
		'nazwisko',
		'nip',
		'pesel',
		'regon',
		'source',
		'jednostka_organizacyjna',
		'A_STATUS',
		'A_STATUS_INFO',
		'L_APPOITMENT_USER',
		// 'Adresy' // 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*'
	];
	public static $FIELD_LIST_KONTRAHENCI = [
		'ID',
		'Nazwa_grupy_kapitalowej',
		'Pelna_nazwa_kontrahenta',
		'Numer_kontrahenta',
		'Skrocona_Nazwa_Kontrahenta',
		'Typ_kontrahenta',
		'NIP',
		'KRS',
		'REGON',
		'PESEL',
		'Forma_prawna_dzialalnosci',
		'Ulica',
		'Numer_budynku',
		'Numer_mieszkania_lokalu',
		'Miejscowosc',
		'Kod_pocztowy',
		'Kraj',
		'Telefon',
		'Fax',
		'Mail',
		'A_ADM_COMPANY',
		'A_CLASSIFIED',
		'Dodano',
		'Podmiot_dominujacy',
		'Tytul_dokumentu',
		'ownCompany',
		'uwagi',
	];

	function aboutAction() { $this->sendPageView('page-about.view.php'); }
	function trainingAction() { $this->sendPageView('page-training.view.php'); }
	function offerAction() { $this->sendPageView('page-offer.view.php'); }
	function helpFormAction() { $this->sendPageView('page-help.view.php', [ $this, '_helpFormBeforeViewTrigger' ]); }
	function _helpFormBeforeViewTrigger($args) {
		$messageValidate = array();
		if ( V::get('button_send', 0, $args) == 1 ) {
			// fields form
			$helpName    		= htmlentities(V::get('help_name', 0, $args));
	    $helpEmail    		= htmlentities(V::get('help_email', 0, $args));
	    $helpDescription  = htmlentities(V::get('help_description', 0, $args));

			if ( empty($helpDescription) && !filter_var($helpEmail, FILTER_VALIDATE_EMAIL)) {
				$messageValidate['error'] = 1;
			}

			$noticeRequest = 'Email: ' . $helpEmail . "; Treść zgłoszenia: " . $helpDescription;

			// data for create insert in DB
			$idQualityNotice = DB::getPDO()->insert('QUALITY_NOTICES', [
				'NOTICE_INITIAL_TYPE'	=> 'BAD_PROCESS',
				'ID_PROCES' => '1', //todo: ustalić ID procesu - ustawiłem defaultowo 1!!!!!
				'NOTICE_REQUEST' => $noticeRequest,
				'NOTICE_REPLY' => '',
				'NOTICE_REPLY_TYPE' => 'BAD_PROCESS',
				'L_APPOITMENT_DATE' => 'NOW()',
				'L_APPOITMENT_USER' => User::getLogin(),
				'ADM_ACCOUNT' => User::getLogin(),
				'THIS_SINGLE_WASTE_COST' => '',
				'WASTE_COST_COMMENT' => '',
				'THIS_SINGLE_FIX_COST' => '',
				'YEAR_COST_FOREACST_OF_SUCH_PROBLEM_WITH_FIXING' => '',
				'FIX_COST_COMMENT' => '',
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()'
			]);

			if( $idQualityNotice > 0 ) {
					$messageValidate['success'] = 'send';
			} else {
				$messageValidate['error'] = 2;
			}

			/*
			TODO: dodać możliwość wysyłania maila używajac mail()
				// Data fpr create mail
		    $to      = self::$helpEmailTo; // uzupełnić mail
		    $subject = 'Bocian - formularz pomocy';
		    $message = "Zgłaszający: " . $helpName . " \r\n  E-mail: " . $helpEmail . ". \r\n Treść wiadomości:\r\n " . $helpDescription;
		    $headers = 'From: '. self::$helpEmailTo . "\r\n" .
		        'Reply-To: '. self::$helpEmailTo . "\r\n" .
		        'X-Mailer: PHP/' . phpversion();

		    $sendMail = mail($to, $subject, $message, $headers);

				if( $sendMailResponse == true ) {
						$responseSendMail = true;
						$messageValidate['success'] = 'send';

				} else {
					$messageValidate['error'] = 2;
				}
			*/
		}
		return [
			'messageValidate' => $messageValidate,
		];
	}
	function sendPageView($templateFile, $beforeViewTrigger = null) {
		UI::gora();
		echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
		echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
		Theme::top();
		$tmplPath = __FILE__ . '.' . $templateFile;
		if (!file_exists($tmplPath)) throw new Exception("Template file not exists '{$templateFile}'");

		if ($beforeViewTrigger && is_callable($beforeViewTrigger)) {
			$data = $beforeViewTrigger($_POST);
			if (is_array($data) && !empty($data)) {
				extract($data);
			}
		}
		include($tmplPath);
		UI::dol();
	}

	function defaultAction() {
		UI::gora();
		echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
		echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
		Theme::top();
		//echo '<div id="smad-wrapper">'; // todo: sprawdzi  czy można usunać
		echo '<div class="container-bi_audit_form_pracownicy_raport" style="display: none;"></div>';
		echo '<div class="container-bi_audit_form_kontrahenci_raport" style="display: none;"></div>';
		echo '<div class="container-bi-audit_form_operacyjna_baza_zgloszen" style="display:none;"></div>';
	//	echo '<div class="container-bi_audit_form_raport_data" style="display: none;"></div>';

		UI::inlineJS(__FILE__ . '.view.js', [
			'BASE_URLS' => Request::getPathUri(),
			'URL_FETCH_KONTRAHENCI_POWIAZANIA' => $this->getLink('fetchEnergaRumKontrahenciPowiazaniaAjax'),
			'URL_FETCH_TEST_KRS' => $this->getLink('fetchTestKrsAjax'),
			'URL_FETCH_TEST_CEIDG' => $this->getLink('fetchTestCeidgAjax'),
			'URL_FETCH_PRACOWNICY' => $this->getLink('fetchPracownicyAjax'),
			'URL_FETCH_PRACOWNICY_IDS_AJAX' => $this->getLink('fetchPracownicyIdsAjax'),
			'URL_FETCH_KONTRAHENCI' => $this->getLink('fetchKontrahenciAjax'),
			'URL_FETCH_KONTRAHENCI_IDS_AJAX' => $this->getLink('fetchKontrahenciIdsAjax'),
			'URL_CREATE_PRACOWNICY_GROUP' => $this->getLink('createPracownicyGroupAjax'),
			'URL_CREATE_KONTRAHENCI_GROUP' => $this->getLink('createKontrahenciGroupAjax'),
			'URL_ADD_PRACOWNICY_TO_GROUP' => $this->getLink('addPracownicyToGroupAjax'),
			'URL_REMOVE_PRACOWNICY_FROM_GROUP' => $this->getLink('removePracownicyFromGroupAjax'),
			'URL_CREATE_PRACOWNICY' => $this->getLink('createPracownikAjax'),
			'URL_CREATE_KONTRAHENCI' => $this->getLink('createKontrahentAjax'),
			'URL_ADD_KONTRAHENCI_TO_GROUP' => $this->getLink('addKontrahenciToGroupAjax'),
			'URL_REMOVE_KONTRAHENCI_FROM_GROUP' => $this->getLink('removeKontrahenciFromGroupAjax'),
			'URL_FETCH_GROUP_PRACOWNICY' => $this->getLink('fetchGroupPracownicyAjax'),
			'URL_FETCH_GROUP_KONTRAHENCI' => $this->getLink('fetchGroupKontrahenciAjax'),
			'URL_GENERATE_BI_AUDIT_RAPORT_AJAX' => $this->getLink('generateBiAuditRaportAjax'),
			'DBG' => V::get('DBG', 0, $_GET),
			'VIEW_KONTRAHENCI' => $this->defaultViewFormBiAudit([], 'KONTRAHENCI'),
			'VIEW_PRACOWNICY' => $this->defaultViewFormBiAudit([], 'PRACOWNICY'),
			'VIEW_OPERACYJNA_BAZA_ZGLOSZEN' => $this->defaultViewFormBiAudit([], 'OPERACYJNA_BAZA_ZGLOSZEN'),
			'URL_FORM_DATA_CSV_FILE_AJAX' => $this->getLink('formDataCsvFileAjax'),
			'URL_SAVE_FORM_CSV_FILE_AJAX' => $this->getLink('saveFormCsvFileAjax'),
			'URL_TABLE_POWIAZANIA' => Router::getRoute('ViewTableAjax', [ 'namespace' => "default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA" ]),
			'FIELD_LIST_PRACOWNICY' => array_merge(
				array_map(function ($fieldName) {
					return "f_{$fieldName}";
				}, self::$FIELD_LIST_PRACOWNICY),
				[
					'f_Adresy',
				]
			),
			'FIELD_LIST_KONTRAHENCI' => array_map(function ($fieldName) {
				return "f_{$fieldName}";
			}, self::$FIELD_LIST_KONTRAHENCI),
			'CURRENT_DATE' => date("j.n.Y"),
		]);
		echo UI::h('script', ['src'=>"static/vendor.js?v=48ea11d6", 'type'=>"text/javascript"]);
		UI::inlineJS(__FILE__ . '.addItemToRaport.js', [
			'URL_FETCH_FROM_BAZA' => $this->getLink('fetchFromBazaAjax'),
			'URL_SAVE_TO_DB' => $this->getLink('saveToPracownicyAjax'),
			'DBG' => V::get('DBG', 0, $_GET),
			'FUNCTION_NAME' => "createPracownikAjax",
		]);
		UI::inlineJS(__FILE__ . '.addItemToRaport.js', [
			'URL_FETCH_FROM_BAZA' => $this->getLink('fetchFromBazaAjax'),
			'URL_SAVE_TO_DB' =>$this->getLink('saveToKontrahenciAjax'),
			'DBG' => V::get('DBG', 0, $_GET),
			'FUNCTION_NAME' => "createKontrahentAjax",
		]);
		UI::inlineJS(__FILE__ . '.graphShowHide.js', [
			'DBG' => V::get('DBG', 0, $_GET),
			'FIELD_LIST_PRACOWNICY' => array_merge(
				array_map(function ($fieldName) {
					return "f_{$fieldName}";
				}, self::$FIELD_LIST_PRACOWNICY),
				[
					'f_Adresy',
				]
			),
			'FIELD_LIST_KONTRAHENCI' => array_map(function ($fieldName) {
				return "f_{$fieldName}";
			}, self::$FIELD_LIST_KONTRAHENCI),
		]);

		echo '</div>'; // #smad-wrapper
		UI::dol();
	}


	public function saveToPracownicyAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'saveToPracownicyAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function saveToPracownicyAjax($args) {
		DBG::log($args, 'array', "saveToPracownicyAjax args");
		$baza = V::get('baza', '', $args);
		$item = V::get('item', [], $args);
		if (empty($item)) throw new Exception("Brak danych do zapisania");
		switch ($baza) {
			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->saveKRSToPracownicyAjax($item);
			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->saveKRSPersonToPracownicyAjax($item);
			case 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI': return $this->saveKontrahentToPracownicyAjax($item);
			case 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY': return $this->savePracownikToPracownicyAjax($item);
			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->saveVATpToPracownicyAjax($item);
			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->saveMSIGToPracownicyAjax($item);
			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->saveMSIGPersonToPracownicyAjax($item);
			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->saveCEIDGToPracownicyAjax($item);

		}
	}
	//   "@primaryKey": "161323",
  //   "A_kod": "80-299",
  //   "A_kraj": "POLSKA",
  //   "A_miejscowosc": "GDAŃSK",
  //   "A_nrDomu": "54C",
  //   "A_nrLokalu": null,
  //   "A_poczta": "GDAŃSK",
  //   "A_ulica": "BARNIEWICKA",
  //   "ID": "161323",
  //   "S_kraj": "POLSKA",
  //   "S_miejscowosc": "GDAŃSK",
  //   "S_wojewodztwo": "POMORSKIE",
  //   "krs": "0000223476",
  //   "nazwa": "BIALL Sp. z o.o.",
  //   "nip": "6040018535",
  //   "regon": "193106935",
	function saveKRSToPracownicyAjax($item) {
		$companyName = V::get('nazwa', '', $item);
		$companyNip = V::get('nip', '', $item);
		$comapanyRegon = V::get('regon', '', $item);
		$comapanyKrs = V::get('krs', '', $item);
		$companyStreet = V::get('A_ulica', '', $item);
		$companyHomeNumber = V::get('A_nrDomu', '', $item);
		$companyNumber = V::get('A_nrLokalu', '', $item);
		$companyPostCode = V::get('A_kod', '', $item);
		$companyCity = V::get('A_miejscowosc', '', $item);

		// validate
		//if (!$companyName) throw new Exception("Nie podano nazwy");
		//if (!$companyNip) throw new Exception("Nie podano nip");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
			'imiona' => $companyName,
			'nip' => ($companyNip) ? $companyNip : NULL,
			'regon' => ($comapanyRegon) ? $comapanyRegon : NULL,
			'krs' => ($comapanyKrs) ? $comapanyKrs : NULL,
			'ulica' => $companyStreet,
			'nr' => $companyHomeNumber,
			'nrLokalu' => $companyNumber,
			'kodPocztowy' => $companyPostCode,
			'miejscowosc' => $companyCity,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function saveMSIGToPracownicyAjax($item) {
		$companyName = V::get('nazwa', '', $item);
		$companyNip = V::get('nip', '', $item);
		$comapanyRegon = V::get('regon', '', $item);
		$comapanyKrs = V::get('krs', '', $item);
		$companyStreet = V::get('A_ulica', '', $item);
		$companyHomeNumber = V::get('A_nrDomu', '', $item);
		$companyNumber = V::get('A_nrLokalu', '', $item);
		$companyPostCode = V::get('A_kod', '', $item);
		$companyCity = V::get('A_miejscowosc', '', $item);

		// validate
		//if (!$companyName) throw new Exception("Nie podano nazwy");
		//if (!$companyNip) throw new Exception("Nie podano nip");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
			'imiona' => $companyName,
			'nip' => ($companyNip) ? $companyNip : NULL,
			'regon' => ($comapanyRegon) ? $comapanyRegon : NULL,
			'krs' => ($comapanyKrs) ? $comapanyKrs : NULL,
			'ulica' => $companyStreet,
			'nr' => $companyHomeNumber,
			'nrLokalu' => $companyNumber,
			'kodPocztowy' => $companyPostCode,
			'miejscowosc' => $companyCity,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function saveKRSPersonToPracownicyAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personPesel = V::get('pesel', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
				'imiona' => $personName,
				'nazwisko' => $personSurname,
				'pesel' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveMSIGPersonToPracownicyAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personPesel = V::get('pesel', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
				'imiona' => $personName,
				'nazwisko' => $personSurname,
				'pesel' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveCEIDGToPracownicyAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personEnterprise = V::get('firma','',$item);
		$personNip = V::get('nip', '', $item);
		$personRegon = V::get('regon', '', $item);
		$personLocal = V::get('lokal', '', $item);
		$personPostalCode = V::get('kodPocztwy', '', $item);
		$personCity = V::get('miejscowosc', '', $item);
		$personBuilding = V::get('budynek', '', $item);
		$personStreet = V::get('ulica', '', $item);
		$personName.=' ';
		$personName.=$personEnterprise;
		$personEnterprise.=' ';
		$personEnterprise.=$personSurname;

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
			'imie' => $personName,
			'nazwisko' => $personEnterprise,
			'ulica' => $personStreet,
			'nr' => $personBuilding,
			'nrLokalu' => $personLocal,
			'kodPocztowy' => $personPostalCode,
			'miejscowosc' => $personCity,
			'regon' => ($personRegon) ? $personRegon : NULL,
			'nip' => ($personNip) ? $personNip : NULL,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveVATpToPracownicyAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personNip = V::get('nip', '', $item);
		$personRegon = V::get('regon', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
			'imie' => $personName,
			'nazwisko' => $personSurname,
			'regon' => ($personRegon) ? $personRegon : NULL,
			'nip' => ($personNip) ? $personNip : NULL,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveKontrahentToPracownicyAjax($item) {
		// companyName: document.getElementById('companyName').value,
		// companyNip: document.getElementById('companyNip').value,
		// comapanyRegon: document.getElementById('comapanyRegon').value,
		DBG::log($item, 'array', "argumenty do wpisania");
		$companyName = V::get('companyName', '', $item);
		$companyNip = V::get('companyNip', '', $item);
		$companyRegon = V::get('companyRegon', '', $item);
		$companyPesel = V::get('companyPesel', '', $item);
		$companyStreet = V::get('companyStreet', '', $item);
		$companyNumber = V::get('companyNumber', '', $item);
		$companyNumberLocal = V::get('companyNumberLocal', '', $item);
		$companyPostCode = V::get('companyPostCode', '', $item);
		$companyCity = V::get('companyCity', '', $item);
		$companyKrs = V::get('companyKrs', '', $item);

		// validate
		if (!$companyName) throw new Exception("Nie wpisano nazwy");
		if (!$companyNip) throw new Exception("Nie wpisano nip");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
				'nazwisko' => $companyName,
				'nip' => ($companyNip) ? $companyNip : NULL,
				'regon' => ($companyRegon) ? $companyRegon : NULL,
				'pesel' => $companyPesel,
				'ulica' => $companyStreet,
				'nr' => $companyNumber,
				'nrLokalu' => $companyNumberLocal,
				'kodPocztowy' => $companyPostCode,
				'miejscowosc' => $companyCity,
				'krs' => $companyKrs,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function savePracownikToPracownicyAjax($item) {
		$personName = V::get('personName', '', $item);
		$personSurname = V::get('personSurname', '', $item);
		$personNip = V::get('personNip', '', $item);
		$personPesel = V::get('personPesel', '', $item);

		// validate
		if (!$personName) throw new Exception("Nie wpisano imienia");
		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
				'imiona' => $personName,
				'nazwisko' => $personSurname,
				'nip' => ($personNip) ? $personNip : NULL,
				'pesel' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}

		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}

	public function saveToKontrahenciAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'saveToKontrahenciAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function saveToKontrahenciAjax($args) {
		DBG::log($args, 'array', "saveToKontrahenciAjaxActionAjax args");
		$baza = V::get('baza', '', $args);
		$item = V::get('item', [], $args);
		if (empty($item)) throw new Exception("Brak danych do zapisania");
		switch ($baza) {
			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->saveKRSToKontrahenciAjax($item);
			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->saveKRSPersonToKontrahenciAjax($item);
			case 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI': return $this->saveKontrahentToKontrahenciAjax($item);
			case 'default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY': return $this->savePracownikToKontrahenciAjax($item);
			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->saveVATpToKontrahenciAjax($item);
			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->saveMSIGToKontrahenciAjax($item);
			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->saveMSIGPersonToKontrahenciAjax($item);
			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->saveCEIDGToKontrahenciAjax($item);
		}
	}

	function saveKRSToKontrahenciAjax($item) {
		$companyName = V::get('nazwa', '', $item);
		$companyNip = V::get('nip', '', $item);
		$companyRegon = V::get('regon', '', $item);
		$companyKrs = V::get('krs', '', $item);
		$companyStreet = V::get('A_ulica', '', $item);
		$companyNumberBuilding = V::get('A_nrDomu', '', $item);
		$companyNumberLocal = V::get('A_nrLokalu', '', $item);
		$companyPostCode = V::get('A_kod', '', $item);
		$companyCountry = V::get('A_kraj', '', $item);
		$companyCity = V::get('A_miejscowosc', '', $item);

		// validate
		//if (!$companyName) throw new Exception("Nie podano nazwy");
		//if (!$companyNip) throw new Exception("Nie podano nip");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
			'Pelna_nazwa_kontrahenta' => $companyName,
			'NIP' => ($companyNip) ? $companyNip : NULL,
			'REGON' => ($companyRegon) ? $companyRegon : NULL,
			'KRS' => ($companyKrs) ? $companyKrs : NULL,
			'Ulica' => $companyStreet,
			'Numer_mieszkania_lokalu' => $companyNumberLocal,
			'Numer_budynku' => $companyNumberBuilding,
			'Kod_pocztowy' => $companyPostCode,
			'Miejscowosc' => $companyCity,
			'Kraj' => $companyCountry,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function saveMSIGToKontrahenciAjax($item) {
		$companyName = V::get('nazwa', '', $item);
		$companyNip = V::get('nip', '', $item);
		$comapanyRegon = V::get('regon', '', $item);
		$comapanyKrs = V::get('krs', '', $item);
		$companyStreet = V::get('A_ulica', '', $item);
		$companyNumberBuilding = V::get('A_nrDomu', '', $item);
		$companyNumberLocal = V::get('A_nrLokalu', '', $item);
		$companyPostCode = V::get('A_kod', '', $item);
		$companyCountry = V::get('A_kraj', '', $item);
		$companyCity = V::get('A_miejscowosc', '', $item);

		// validate
		//if (!$companyName) throw new Exception("Nie podano nazwy");
		//if (!$companyNip) throw new Exception("Nie podano nip");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
			'Pelna_nazwa_kontrahenta' => $companyName,
			'NIP' => ($companyNip) ? $companyNip : NULL,
			'REGON' => ($comapanyRegon) ? $comapanyRegon : NULL,
			'KRS' => ($comapanyKrs) ? $comapanyKrs : NULL,
			'Ulica' => $companyStreet,
			'Numer_mieszkania_lokalu' => $companyNumberLocal,
			'Numer_budynku' => $companyNumberBuilding,
			'Kod_pocztowy' => $companyPostCode,
			'Miejscowosc' => $companyCity,
			'Kraj' => $companyCountry,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function saveCEIDGToKontrahenciAjax($item) {
		$personFirstName = V::get('imie', '', $item);
		$personLastName = V::get('nazwisko', '', $item);
		$personNip = V::get('nip', '', $item);
		$personEnterprise = V::get('firma', '', $item);
		$personStreet = V::get('ulica', '', $item);
		$personNumber = V::get('budynek', '', $item);
		$personNumberLocal = V::get('lokal', '', $item);
		$personPostalCode = V::get('kodPocztowy', '', $item);
		$personCity = V::get('miejscowosc', '', $item);
		$personCountry = V::get('kraj', '', $item);
		$personFirstName .= ' ';
		$personFirstName .= $personEnterprise;
		$personEnterprise .= ' ';
		$personEnterprise .= $personLastName;


		// validate
		//if (!$personFirstName) throw new Exception("Nie podano nazwy");
		//if (!$personNip) throw new Exception("Nie podano nip");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
			'Pelna_nazwa_kontrahenta' => $personEnterprise,
			//'Skrocona_Nazwa_Kontrahenta' => $personFirstName,
			'NIP' => ($personNip) ? $personNip : NULL,
			'REGON' => ($personRegon) ? $personRegon : NULL,
			'Ulica' => $personStreet,
			'Numer_mieszkania_lokalu' => $personNumber,
			'Numer_budynku' => $personNumber,
			'Kod_pocztowy' => $personPostalCode,
			'Miejscowosc' => $personCity,
			'Kraj' => $personCountry,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function saveKRSPersonToKontrahenciAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personPesel = V::get('pesel', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
				//'Skrocona_Nazwa_Kontrahenta' => $personName,
				'Pelna_nazwa_kontrahenta' => $personSurname,
				'PESEL' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveMSIGPersonToKontrahenciAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personPesel = V::get('pesel', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
				//'Skrocona_Nazwa_Kontrahenta' => $personName,
				'Pelna_nazwa_kontrahenta' => $personSurname,
				'PESEL' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveVATpToKontrahenciAjax($item) {
		$personName = V::get('imiona', '', $item);
		$personSurname = V::get('nazwisko', '', $item);
		$personPesel = V::get('pesel', '', $item);

		// validate
		//if (!$personName) throw new Exception("Nie podano imienia");
		//if (!$personSurname) throw new Exception("Nie podano nazwiska");

		$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
			//'Skrocona_Nazwa_Kontrahenta' => $personName,
			'Pelna_nazwa_kontrahenta' => $personSurname,
			'PESEL' => ($personPesel) ? $personPesel : NULL,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}
	function saveKontrahentToKontrahenciAjax($item) {
		// companyName: document.getElementById('companyName').value,
		// companyNip: document.getElementById('companyNip').value,
		// comapanyRegon: document.getElementById('comapanyRegon').value,

		$companyName = V::get('companyName', '', $item);
		$companyNip = V::get('companyNip', '', $item);
		$companyRegon = V::get('companyRegon', '', $item);
		$companyPesel = V::get('companyPesel', '', $item);
		$companyStreet = V::get('companyStreet', '', $item);
		$companyNumber = V::get('companyNumber', '', $item);
		$companyNumberLocal = V::get('companyNumberLocal', '', $item);
		$companyPostCode = V::get('companyPostCode', '', $item);
		$companyCity = V::get('companyCity', '', $item);
		$companyKrs = V::get('companyKrs', '', $item);

		// validate
		if (!$companyName) throw new Exception("Nie wpisano nazwy");
		if (!$companyNip) throw new Exception("Nie wpisano nip");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
				'Pelna_nazwa_kontrahenta' => $companyName,
				'NIP' => ($companyNip) ? $companyNip : NULL,
				'REGON' => ($comapanyRegon) ? $comapanyRegon : NULL,
				'PESEL' => ($companyPesel) ? $companyPesel : NULL,
				'Ulica' => ($companyStreet) ? $companyStreet : NULL,
				'Numer_budynku' => ($companyNumber) ? $companyNumber : NULL,
				'Numer_mieszkania_lokalu' => ($companyNumberLocal) ? $companyNumberLocal : NULL,
				'Kod_pocztowy' => ($companyPostCode) ? $companyPostCode : NULL,
				'Miejscowosc' => ($companyCity) ? $companyCity : NULL,
				'KRS' => ($companyKrs) ? $companyKrs : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano podmiot",
			'type' => "success",
		];
	}
	function savePracownikToKontrahenciAjax($item) {
		$personName = V::get('personName', '', $item);
		$personSurname = V::get('personSurname', '', $item);
		$personNip = V::get('personNip', '', $item);
		$personPesel = V::get('personPesel', '', $item);

		// validate
		if (!$personName) throw new Exception("Nie wpisano imienia");
		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");
		try{
			$idOd = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
				//'Skrocona_Nazwa_Kontrahenta' => $personName,
				'Pelna_nazwa_kontrahenta' => $personSurname,
				'NIP' => ($personNip) ? $personNip : NULL,
				'PESEL' => ($personPesel) ? $personPesel : NULL,
				'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
				'A_RECORD_CREATE_DATE' => 'NOW()',
			]);
		} catch( PDOException $e){
			if($e->errorInfo[1]== 1062){
				throw new Exception("Ta osoba jest już w bazie danych");
			}
			else{
				throw new Exception("Błąd bazy danych");
			}
		}
		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}


	/**
	*  Dodanie nowego pracownika
	*/
	public function createPracownikAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'createPracownikAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function createPracownikAjax($args) {
		DBG::log($args, 'array', "args");
		$personName = V::get('personName', '', $args);
		$personSurname = V::get('personSurname', '', $args);
		$personNip = V::get('personNip', '', $args);
		$personPesel = V::get('personPesel', '', $args);
		$personRegon = V::get('personRegon', '', $args);

		// validate
		if (!$personName) throw new Exception("Nie wpisano imienia");
		if (!$personSurname) throw new Exception("Nie wpisano  nazwiska");


		$idPracownik = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY', [
			'imiona' => $personName,
			'nazwisko' => $personSurname,
			'nip' => ($personNip) ? $personNip : NULL,
			'pesel' => ($personPesel) ? $personPesel : NULL,
			'regon' => ($personRegon) ? $personRegon : NULL,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano osobę",
			'type' => "success",
		];
	}

	/**
	*  Dodanie nowego kontrahenta
	*/
	public function createKontrahentAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'createKontrahentAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function createKontrahentAjax($args) {
		$companyFullName = V::get('companyFullName', '', $args);
		$companyShortName = V::get('$companyShortName', '', $args);
		$companyNameGroup = V::get('companyNameGroup', '', $args);
		$companyKrs = V::get('companyKrs', '', $args);
		$companyNip = V::get('companyNip', '', $args);
		$companyPesel = V::get('companyPesel', '', $args);
		$companyFax = V::get('companyFax', '', $args);
		$companyTelefon = V::get('companyTelefon', '', $args);
		$companyMail = V::get('companyMail', '', $args);
		$companyStreet = V::get('companyStreet', '', $args);
		$companyNumberBuilding = V::get('companyNumberBuilding', '', $args);
		$companyNumberLocal = V::get('companyNumberLocal', '', $args);
		$companyPostCode = V::get('companyPostCode', '', $args);
		$companyPlace = V::get('companyPlace', '', $args);
		$companyCountry = V::get('companyCountry', '', $args);
		$companyTypeCompany = V::get('companyTypeCompany', '', $args);
		$companyTitleDocument = V::get('companyTitleDocument', '', $args);
		$companyDesc = V::get('companyDesc', '', $args);

		// validate
		if (!$companyFullName) throw new Exception("Nie wpisano pełnej nazwy kontrahenta");


		$idKontrahent = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI', [
			'Pelna_nazwa_kontrahenta' => $companyFullName,
			'Skrocona_Nazwa_Kontrahenta' => ($companyShortName) ? $companyShortName : null,
			'Nazwa_grupy_kapitalowej' => ($companyNameGroup) ? $companyNameGroup : null,
			'KRS' => ($companyKrs) ? $companyKrs : null,
			'NIP' => ($companyNip) ? $companyNip : null,
			'PESEL' => ($companyPesel) ? $companyPesel : null,
			'Fax' => ($companyFax) ? $companyFax : null,
			'Telefon' => ($companyTelefon) ? $companyTelefon : null,
			'Mail' => ($companyMail) ? $companyMail : null,
			'Ulica' => ($companyStreet) ? $companyStreet : null,
			'Numer_budynku' => ($companyNumberBuilding) ? $companyNumberBuilding : null,
			'Numer_mieszkania_lokalu' => ($companyNumberLocal) ? $companyNumberLocal : null,
			'Kod_pocztowy' => ($companyPostCode) ? $companyPostCode : null,
			'Miejscowosc' => ($companyPlace) ? $companyPlace : null,
			'Kraj' => ($companyCountry) ? $companyCountry : null,
			'Typ_kontrahenta' => ($companyTypeCompany) ? $companyTypeCompany : null,
			'Tytul_dokumentu' => ($companyTitleDocument) ? $companyTitleDocument : null,
			'uwagi' => ($companyDesc) ? $companyDesc  : null,

			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
		]);

		return [
			'msg' => "Dodano podmiot/kontrahenta",
			'type' => "success",
		];
	}


/**
 * Funkcja ajax do odebrania danych z przesłanego pliku CSV do parsowania
 */
	public function formDataCsvFileAjaxAction() {
		Response::sendTryCatchJson(array($this, 'formDataCsvFileAjax'));
	}

/**
 * Funkcja parsuje dane wgrywanego plku csv i zwraca dane w inputach
 */
public function formDataCsvFileAjax() {

	if (!file_exists($_FILES['file']['tmp_name'])) throw new Exception("Wybierz plik do przesłania.");

	$file = file($_FILES['file']['tmp_name']);
	//$showCheckbox = V::get('showCheckbox', '', $args);
	$showCheckbox = V::get('showCheckbox', 0, $_REQUEST, 'string');

	// parsujemy csv to tablicy
	$arrayDataCsv = $this->csvToArray($file, ';', '"', '\n\r');


		$i = 0;
		// tworzymy rekordy
		foreach ( $arrayDataCsv as $line ) {

			$viewFormCol .= '<tr>';
			foreach ( $line as $keyData => $rowData ) {
								// utworzenie nagłówków tabeli
								if( $i == 0)  { $header .= '<td style="min-width:160px">' . $keyData . '</td>'; }
								// utworzenie inputa do edycji
								$viewFormCol .= '<td style="min-width:160px"><input type="text" name="item['.$i.']['.$keyData.']" value="'.$rowData .'" class="form-control input-lg" /></td>';

			 }
			 $viewFormCol .= '</tr>';

			 $i++;

		}

		// pokaz checkbox jeśli ma status showCheckbox
		if ( $showCheckbox == 'yes' ) {
			$viewFormCol .= '<div style="margin: 10px 0"><input type="checkbox" name="override" value="1" /> Nadpisz wszystkie rekordy w bazie danych</div';
		}
		$viewFormHtml = '<div id="smad-window-modal" style="overflow-x: scroll;">
		<div class="table-responsive padding-0" >
		<form method="POST" id="formDataFromCsv" class="form-horizontal"><table class="table table-bordered table-hover table-striped" height="5"><thead><tr>'. $header .'</tr></thead><tbody id="smad-csv-data">'. $viewFormCol .'</tbody></table></form></div>
		</div>';

		//return $viewFormHtml;
		return [
			'type' => 'success',
			'msg' => 'OK',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'view' => $viewFormHtml,
			]
		];

	}


	/**
	 * Funkcja ajax do odebrania danych z przesłanego formularza z parsowanego CSV
	 */
	public function saveFormCsvFileAjaxAction() {
		Response::sendTryCatchJson(array($this, 'saveFormCsvFileAjax'), $args = 'JSON_FROM_REQUEST_BODY');
		//Response::sendTryCatchJson(array($this, 'saveFormCsvFileAjax'));
	}


/**
 * Funkcja ajax do zapisania danych z przesłanego formularza z parsowanego CSV
 */
	public function saveFormCsvFileAjax($args) {
		//dane z formularza
		$formData = V::get('formData', '', $args);
		$enumType = V::get('enumType', '', $args);

		$override = false; // false - nie nadpisujemy danych
		$arrayInfo = array();
		$arrayInfo['insert'] = 0;
		$arrayInfo['update'] = 0;
		$arrayInfo['error'] = 0;

		// pobranie nazwy tabeli z db
		$table = $this->getNameTableByEnum( strtoupper($enumType) );

		if ( $table == null ) throw new Exception('Błąd zapisu. Tabela w db nie istnieje');
		// unserialize data from serialize in javascript
		parse_str($formData, $resultArrayFormdata);

		if ( count($resultArrayFormdata['item']) == 0) {
			throw new Exception("Wystapił problem podczas przesyłania danych - brak przesłanych danych.");
		}

		// ustawienie true jeśli wyrabno nadpisanie danych
		if ( isset($resultArrayFormdata['override']) ) { $override = true; }  // aktualizuj rekordy/nadpisz istniejace


		// dodanie/aktualizacjia wpisu
		foreach ( $resultArrayFormdata['item'] as $line ) {

				$response = $this->saveDataToDb($table, $line, $override);

			 // tworzymy listę informacji o liczbie nowych/zaktualizowanych/z błedami rekordów
			 $arrayInfo = $this->responseCountListInfoAboutSaveData($response, $arrayInfo);
		}

		// utworzenie komunikatów
		if ( isset($arrayInfo['insert']) ) { $textInsert = "Liczba nowych rekordów: (" . $arrayInfo['insert'] . ");"; }
		if ( isset($arrayInfo['error']) ) { $textError = "Liczba nie zapisanych rekordów (" . $arrayInfo['insert'] . ");"; }

		return [
			'msg' => "Zapisano dane. " . $textInsert . " " . $textError ,
			'type' => "success",
		];

	}

	/**
	 * Count list
	 */
	public function responseCountListInfoAboutSaveData($response, $arrayInfo) {

		if (!is_array($response)) throw new Exception('Wystapił bład podczas zapisu danych');
		$countData = array();

		switch(key($response)) {
			case 'insert':
				$countData['insert'] = $arrayInfo['insert'] + 1;
				break;
			case 'error':
				$countData['error'] = $arrayInfo['insert'] + 1;
				break;
		}

		return $countData;
	}

	/**
	 * Function parse csv to array
	 * @param $filename - file data from FILE
	 * @param $delimiter - delimiter
	 * @param $enclosure -
	 * @param $escape -
	 */
	function csvToArray($filedata , $delimiter=';', $enclosure='"', $escape = '\\') {
	  if(!$filedata || empty($filedata)) return false;

	  $header = null;
	  $data = array();

	  foreach( $filedata as $line) {
	    $values = str_getcsv( $line, $delimiter, $enclosure, $escape );
	    if(!$header) $header = $values;
	    else $data[] = array_combine( $header, $values );
	  }

	  return $data;
	}

	/**
	 *  Save data in database
	 */
	public function saveDataToDb( $table, $arrayData, $override = false ) {
		$response = array();

		try {
			if ($override) {
				DB::getPDO()->insertOrUpdate($table, array_merge($arrayData, [
					'@insert' => [
						'A_RECORD_CREATE_DATE' => 'NOW()',
						'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
					],
					'@update' => array_merge($arrayData, [
						'A_RECORD_UPDATE_DATE' => 'NOW()',
						'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
					]),
				]));
			} else {
				$responseInsert = DB::getPDO()->insert($table, array_merge($arrayData, [
					'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
					'A_RECORD_CREATE_DATE' => 'NOW()',
				]));
			}

				$response['insert'] = 1;

		} catch (Exception $e) {
					DBG::log($e);
					$response['error'] = 1;
		}

		return $response;
	}


	/**
	 * Get name table by enum
	 */
	public function getNameTableByEnum($type) {

		$nameTable = null;
			switch ($type) {
					case 'KONTRAHENCI':
						$nameTable = 'BI_audit_ENERGA_RUM_KONTRAHENCI';
					break;
					case 'PRACOWNICY':
						$nameTable = 'BI_audit_ENERGA_PRACOWNICY';
					break;
			}

			return $nameTable;
	}



	public function fetchEnergaRumKontrahenciPowiazaniaAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchEnergaRumKontrahenciPowiazaniaAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function fetchEnergaRumKontrahenciPowiazaniaAjax($args) {
		$id = V::get('ID', 26, $_REQUEST, 'int');

		$items = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'A_ADM_COMPANY',
				'L_APPOITMENT_USER',
				'A_CLASSIFIED',
				'A_STATUS',
				'A_STATUS_INFO',
				'BI_analiza_maxDepth',
				'BI_analiza_minDepth',
				'BI_analiza_onlyTargets',
				'BI_analiza_reloadCache',
				'FILE_STATUS',
				'FILE_STATUS_info',
				'L_APPOITMENT_USER',
				'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
				'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
				'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row:BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_row',
				'default_db__x3A__BI_audit_KW_requested_person:BI_audit_KW_requested_person',
			],
			'f_ID' => "{$id}",
		])->getItems([
			'limit' => 10
		]);

		// $items = [
		// 	[ 'ID' => 1, 'L_APPOITMENT_INFO' => 'x', 'BI_analiza_depth' => 'a', 'FILE_STATUS' => 1, 'FILE_STATUS_info' => 'test1'],
		// 	[ 'ID' => 2, 'L_APPOITMENT_INFO' => 'y', 'BI_analiza_depth' => 'b', 'FILE_STATUS' => 0, 'FILE_STATUS_info' => 'test2'],
		// 	[ 'ID' => 3, 'L_APPOITMENT_INFO' => 'z',  'BI_analiza_depth' => 'c', 'FILE_STATUS' => 1, 'FILE_STATUS_info' => 'test3'],
		// ];

		return [
			'type' => 'success',
			'msg' => 'OK',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'items' => $items,
				'view' => $this->showPowiazaniaEnergaRumKontrahenciPowiazania($items),
			]
		];
	}


public function showPowiazaniaEnergaRumKontrahenciPowiazania($items) {

	$view = '<form class="form-horizontal" method="post">
						<table class="table table-bordered table-hover table-striped" height=5>
									 <thead>
										 <tr style="">
										 		<td width=1><input type="checkbox" name="checkAll" id="checkAll" /></td>
											 <td width=1>ID</td>
											 <td>Adnotacje</td>
											 <td>Głębokość analizy</td>
											 <td>Status raportu</td>
											 <td>Status raportu - informacje</td>
										 </tr>
									 </thead>
									 <tbody>
					';

		foreach ($items as $key => $row) {
				$view .= '<tr>
				<td><input type="checkbox" name="prID[]" value="'.$row['ID'].'" onClick="checkAll()"/></td>
								<td align="right">'.$row["ID"].'</td>
								<td align="right">'.$row["L_APPOITMENT_INFO"].'</td>
								<td align="right">'.$row["BI_analiza_depth"].'</td>
								<td align="right">'.$row["FILE_STATUS"].'</td>
								<td align="right">'.$row["FILE_STATUS_info"].'</td>';
		}
		$view .= '</tbody></table></form>';


		return $view;
}




	public function fetchTestKrsAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchTestKrsAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function fetchTestKrsAjax($args) {
		$id = V::get('ID', 1, $_REQUEST, 'int');
		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS/BI_audit_KRS')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'A_kod',
				'A_kraj',
				'A_miejscowosc',
				'A_nrDomu',
				'A_nrLokalu',
				'A_poczta',
				'A_ulica',
				'ID',
				'S_gmina',
				'S_kraj',
				'S_miejscowosc',
				'S_powiat',
				'S_wojewodztwo',
				'dataDokumentu',
				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
				'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
				'krs',
				'nazwa',
				'nip',
				'regon',
			],
			'f_ID' => "{$id}",
		])->getItems([
			'limit' => 10
		]);

		return [
			'type' => 'success',
			'msg' => 'KRS',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'items' => $items,
			]
		];
	}

	public function fetchTestCeidgAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchTestCeidgAjax')); // , $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function fetchTestCeidgAjax($args) {
		$id = V::get('ID', 0, $_REQUEST, 'int');
		$items = ACL::getAclByNamespace('default_db/BI_audit_CEIDG/BI_audit_CEIDG')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'budynek',
				'firma',
				'gmina',
				'identyfikatorWpisu',
				'imie',
				'kodPocztowy',
				'kraj',
				'lokal',
				'miejscowosc',
				'nazwisko',
				'nip',
				'poczta',
				'powiat',
				'regon',
				'ulica',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ID',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/budynek',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/gmina',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/kodPocztowy',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/lokal',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/miejscowosc',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nazwa',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nip',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/poczta',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/powiat',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ulica',
				'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/wojewodztwo',
				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/ID',
				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/nip',
				'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/regon',
			],
			// 'f_ID' => $id,
		])->getItems([
			'limit' => 10
		]);

		return [
			'type' => 'success',
			'msg' => 'CEIDG',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'items' => $items,
			]
		];
	}

	public function fetchKontrahenciIdsAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchKontrahenciIdsAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function fetchKontrahenciIdsAjax($args) {
		$idGroup = V::get('filter_idGroup', 0, $args, 'int');
		if ($idGroup < 0) $idGroup = 0;
		$backRefFilter = [];
		if ($idGroup > 0) {
			$backRefFilter['__backRef'] = [
				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				'primaryKey' => $idGroup,
				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
			];
		}

		$searchParams = []; // TODO: ???

		$filtersParams = [];
		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
			return ('f_' === substr($key, 0, 2));
		});
		foreach ($fieldFilterKeys as $key) {
			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
		}

		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
		$query = $acl->buildQuery(array_merge([
			'cols' => [
				'ID',
			],
			//'f_ID' => $id,
			'limit' => 0,
			// 'limitstart' => $limitstart, // offset
			// 'order_by' => 'ID', // sortowanie po kolumnie
			// 'order_dir' => 'DESC', // kierunek sortowania
			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
		], $searchParams, $filtersParams, $backRefFilter));
		// $total = $query->getTotal();
		$items = $query->getItems();

		return [
			'type' => 'success',
			'msg' => 'kontrahenci ids',
			'body' => [
				'ids' => array_map( V::makePick('ID'), $items ),
			],
			'__DBG_args' => $args,
			'__DBG_$idGroup' => $idGroup,
			'__DBG_$filtersParams' => $filtersParams,
			'__DBG_$backRefFilter' => $backRefFilter,
		];
	}
	/**
	 * KONTRAHENCI
	 */
	public function fetchKontrahenciAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchKontrahenciAjax'), $args = $_REQUEST);
	}
	public function fetchKontrahenciAjax($args) {
		$idGroup = V::get('filterIdGroup', 0, $args, 'int'); // TODO: dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
		if ($idGroup < 0) $idGroup = 0;

		$limit = 20;

		$limitstart = V::get('limitstart', 0, $args, 'int');
		if ($limitstart < 0) $limitstart = 0;

		$page = V::get('page', 0, $args, 'int');
		$limitstart = ($page - 1) * $limit;

		$search = V::get('search', '', $args);
		$searchParams = [];
		if (!empty($search)) {
			$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
			$searchParams['ogc:Filter'] = '
				<ogc:Filter>
			    <ogc:Or>
			      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
			        <ogc:PropertyName>NIP</ogc:PropertyName>
			        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
			      </ogc:PropertyIsLike>
			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
			        <ogc:PropertyName>Nazwa_grupy_kapitalowej</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
			      </ogc:PropertyIsLike>
			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
			        <ogc:PropertyName>Pelna_nazwa_kontrahenta</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
			      </ogc:PropertyIsLike>
			    </ogc:Or>
			  </ogc:Filter>
			';
		}
// ogc filter w środku ogcand potem ogcnot potem PropertyIsEqualTo
		$backRefFilter = [];
		if ($idGroup > 0) {
			$backRefFilter['__backRef'] = [
				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				'primaryKey' => $idGroup,
				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
			];
			// - ID
			// - ID_USER - id usera który stworzył grupę (tylko dla niego będzie widoczna)
			// - NAZWA - nazwa grupy
			// - 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_KONTRAHENCI' minOccurs="0" maxOccurs="unbounded"
		}

		$filtersParams = [];
		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
			return ('f_' === substr($key, 0, 2));
		});
		foreach ($fieldFilterKeys as $key) {
			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
		}
		DBG::log($filtersParams, 'Kontrahenci $filtersParams');
		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
		$query = $acl->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
								'ID',
								'Nazwa_grupy_kapitalowej',
								'Pelna_nazwa_kontrahenta',
								'Numer_kontrahenta',
								'Skrocona_Nazwa_Kontrahenta',
								'Typ_kontrahenta',
								'NIP',
								'KRS',
								'REGON',
								'PESEL',
					 			'Forma_prawna_dzialalnosci',
					 			'Ulica',
					 			'Numer_budynku',
					 			'Numer_mieszkania_lokalu',
					 			'Miejscowosc',
								'Kod_pocztowy',
								'Kraj',
								'Telefon',
								'Fax',
								'Mail',
								'A_ADM_COMPANY',
								'A_CLASSIFIED',
								'Dodano',
								'Podmiot_dominujacy',
								'Tytul_dokumentu',
								'ownCompany',
								'uwagi',
			],
			//'f_ID' => $id,
			'limit' => $limit,
			'limitstart' => $limitstart, // offset
			'order_by' => 'ID', // sortowanie po kolumnie
			'order_dir' => 'DESC', // kierunek sortowania
		], $searchParams, $filtersParams, $backRefFilter));
		$total = $query->getTotal();
		$items = $query->getItems();

		$pagination = array();
		$pagination['total_items'] = $total;
		$pagination['size'] = ceil($total/$limit); // pages size
		$pagination['current'] = $page;
		$pagination['limit'] = $limit;
		if ($idGroup > 0) $pagination['filter_idGroup'] = $idGroup;

		return [
			'type' => 'success',
			'msg' => 'showKontrajenci',
			'body' => [
				'items' => $items,
				//'view' => $this->htmlViewFormBiAudit($items, 'KONTRAHENCI'),
				'pagination' => $pagination
			],
			'__DBG_args' => $args,
			'__DBG_$idGroup' => $idGroup,
			'__DBG_$filtersParams' => $filtersParams,
			'__DBG_$backRefFilter' => $backRefFilter,
		];
	}


	public function fetchFromBazaAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchFromBazaAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
	public function fetchFromBazaAjax($args) {
		$baza = V::get('baza', '', $args);
		$query = V::get('query', '', $args);
		$query = trim($query);
		if (strlen($query) < 3) throw new Exception("Query must be more then 2 chars");

		$wordsQuery = [];
		if (false !== strpos($query, ' ')) {
			$words = explode(' ', $query);
			DBG::log($words, 'array', "\$words from \$query({$query}) - 1");
			$words = array_map('trim', $words);
			DBG::log($words, 'array', "\$words from \$query({$query}) - 2");
			$words = array_filter($words, function ($word) {
				return (strlen($word) > 2);
			});
			DBG::log($words, 'array', "\$words from \$query({$query}) - 3");
			if (empty($words)) throw new Exception("Query words must be more then 2 chars");
			$wordsQuery = $words;
		} else {
			$wordsQuery[] = $query;
		}

		switch ($baza) {
			case 'default_db/BI_audit_KRS/BI_audit_KRS': return $this->fetchFromKRS($wordsQuery);
			case 'default_db/BI_audit_KRS_person/BI_audit_KRS_person': return $this->fetchFromKRSPerson($wordsQuery);
			case 'default_db/BI_audit_MSIG/BI_audit_MSIG': return $this->fetchFromMSIG($wordsQuery);
			case 'default_db/BI_audit_MSIG_person/BI_audit_MSIG_person': return $this->fetchFromMSIGPerson($wordsQuery);
			case 'default_db/BI_audit_taxpayer/BI_audit_taxpayer': return $this->fetchFromVATp($wordsQuery);
			case 'default_db/BI_audit_CEIDG/BI_audit_CEIDG': return $this->fetchFromCEIDG($wordsQuery);
			default: throw new Exception("Unsupported database");
		}
	}
	function generateOgcFilterFromWords($wordsQuery, $searchableFields) {
		return '<ogc:Filter><ogc:And>' .
			implode("\n", array_map(function ($word) use ($searchableFields) {
				return '<ogc:Or>' . implode("\n", array_map(function ($fieldName) use ($word) {
					return '<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
						<ogc:PropertyName>' . $fieldName . '</ogc:PropertyName>
						<ogc:Literal>' . "*{$word}*" . '</ogc:Literal>
					</ogc:PropertyIsLike>';
				}, $searchableFields)) . '</ogc:Or>';
			}, $wordsQuery)) .
		'</ogc:And></ogc:Filter>';
	}
	function fetchFromKRS($wordsQuery) {
		$query = implode(" ", $wordsQuery);
		if (empty($wordsQuery)) throw new Exception("Empty search");
		$searchableFields = [];
		$searchableFields[] = 'nazwa';
		$searchableFields[] = 'nip';
		$searchableFields[] = 'S_miejscowosc';
		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS/BI_audit_KRS')->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
				'A_kod',
				'A_kraj',
				'A_miejscowosc',
				'A_nrDomu',
				'A_nrLokalu',
				'A_poczta',
				'A_ulica',
				'ID',
				// 'S_gmina',
				'S_kraj',
				'S_miejscowosc',
				// 'S_powiat',
				'S_wojewodztwo',
				// 'dataDokumentu',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
				'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
				'krs',
				'nazwa',
				'nip',
				'regon',
			],
			// 'f_ID' => "{$id}",
		], $searchParams))->getItems([
			'limit' => 10
		]);
		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

		return [
			'type' => 'success',
			'msg' => 'KRS',
			'__args' => $args,
			'body' => [
				'items' => array_map(function ($item) {
					$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
					$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
					$item['nazwa'] = $nazwa;
					$item['label'] = "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}";
					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

					return $item;

					// return [
					// 	'ID' => $item['ID'],
					// 	'nazwa' => $shortNazwa,
					// 	'nip' => $item['nip'],
					// 	'krs' => $item['krs'],
					// 	'regon' => $item['regon'],
					// 	'S_miejscowosc' => $item['S_miejscowosc'],
					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
					// ];
				}, $items),
			]
		];
	}

	function fetchFromKRSPerson($wordsQuery) {
		$query = implode(" ", $wordsQuery);
		if (empty($wordsQuery)) throw new Exception("Empty search");
		$searchableFields = [];
		$searchableFields[] = 'nazwisko';
		$searchableFields[] = 'imiona';
		$searchableFields[] = 'pesel';
		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
		$items = ACL::getAclByNamespace('default_db/BI_audit_KRS_person/BI_audit_KRS_person')->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
				'nazwisko',
				'imiona',
				'pesel',
				'ID',
				// 'dataDokumentu',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
			],
			// 'f_ID' => "{$id}",
		], $searchParams))->getItems([
			'limit' => 10
		]);
		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

		return [
			'type' => 'success',
			'msg' => 'KRS person',
			'__args' => $args,
			'body' => [
				'items' => array_map(function ($item) {
					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
					//$nazwa = $item['nazwisko'];
					//$item['nazwa'] = $nazwa;
					$item['label'] = "{$item['nazwisko']}, {$item['imiona']}, {$item['pesel']}";
					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

					return $item;

					// return [
					// 	'ID' => $item['ID'],
					// 	'nazwa' => $shortNazwa,
					// 	'nip' => $item['nip'],
					// 	'krs' => $item['krs'],
					// 	'regon' => $item['regon'],
					// 	'S_miejscowosc' => $item['S_miejscowosc'],
					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
					// ];
				}, $items),
			]
		];
	}

	function fetchFromVATp($query){
			$ogcSearch = "*{$query}*";
			$searchParams = [];
			$searchParams['ogc:Filter'] = '
				<ogc:Filter>
					<ogc:Or>
						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
							<ogc:PropertyName>nazwisko</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
						</ogc:PropertyIsLike>
						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
							<ogc:PropertyName>imiona</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
						</ogc:PropertyIsLike>
						<ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
							<ogc:PropertyName>pesel</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
						</ogc:PropertyIsLike>
					</ogc:Or>
				</ogc:Filter>
			';
			$items = ACL::getAclByNamespace('default_db/BI_audit_taxpayer/BI_audit_taxpayer')->buildQuery(array_merge([
				'cols' => [ // TODO:? propertyName = []
					'nip',
					'ID',
					// 'dataDokumentu',
					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
					// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
					// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
				],
				// 'f_ID' => "{$id}",
			], $searchParams))->getItems([
				'limit' => 10
			]);
			DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

			return [
				'type' => 'success',
				'msg' => 'KRS person',
				'__args' => $args,
				'body' => [
					'items' => array_map(function ($item) {
						//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
						//$nazwa = $item['nazwisko'];
						//$item['nazwa'] = $nazwa;
						$item['label'] = "{$item['nip']}";
						// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

						return $item;

						// return [
						// 	'ID' => $item['ID'],
						// 	'nazwa' => $shortNazwa,
						// 	'nip' => $item['nip'],
						// 	'krs' => $item['krs'],
						// 	'regon' => $item['regon'],
						// 	'S_miejscowosc' => $item['S_miejscowosc'],
						// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
						// ];
					}, $items),
				]
			];
		}

	function fetchFromMSIG($wordsQuery) {
		$query = implode(" ", $wordsQuery);
		if (empty($wordsQuery)) throw new Exception("Empty search");
		$searchableFields = [];
		$searchableFields[] = 'nazwa';
		$searchableFields[] = 'nip';
		$searchableFields[] = 'S_miejscowosc';
		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
		$items = ACL::getAclByNamespace('default_db/BI_audit_MSIG/BI_audit_MSIG')->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
				'A_kod',
				'A_kraj',
				'A_miejscowosc',
				'A_nrDomu',
				'A_nrLokalu',
				'A_poczta',
				'A_ulica',
				'ID',
				// 'S_gmina',
				'S_kraj',
				'S_miejscowosc',
				// 'S_powiat',
				'S_wojewodztwo',
				// 'dataDokumentu',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/ID',
				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/imiona',
				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/nazwisko',
				'default_db__x3A__BI_audit_MSIG_person:BI_audit_MSIG_person/pesel',
				'krs',
				'nazwa',
				'nip',
				'regon',
			],
			// 'f_ID' => "{$id}",
		], $searchParams))->getItems([
			'limit' => 10
		]);
		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

		return [
			'type' => 'success',
			'msg' => 'MSIG',
			'__args' => $args,
			'body' => [
				'items' => array_map(function ($item) {
					$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
					$nazwa = str_replace([ '„', '”' ], '', $item['nazwa']);
					$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", " Sp. z o.o.", $nazwa);
					$item['nazwa'] = $nazwa;
					$item['label'] = "{$nazwa}, " . implode(", ", array_filter([
						$item['A_miejscowosc'],
						$item['krs'],
						$item['nip'],
						$item['regon']
					], [ 'V', 'filterNotEmpty' ]));
					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

					return $item;

					// return [
					// 	'ID' => $item['ID'],
					// 	'nazwa' => $shortNazwa,
					// 	'nip' => $item['nip'],
					// 	'krs' => $item['krs'],
					// 	'regon' => $item['regon'],
					// 	'S_miejscowosc' => $item['S_miejscowosc'],
					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
					// ];
				}, $items),
			]
		];
	}

	function fetchFromMSIGPerson($wordsQuery) {
		$query = implode(" ", $wordsQuery);
		if (empty($wordsQuery)) throw new Exception("Empty search");
		$searchableFields = [];
		$searchableFields[] = 'nazwisko';
		$searchableFields[] = 'imiona';
		$searchableFields[] = 'pesel';
		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
		$items = ACL::getAclByNamespace('default_db/BI_audit_MSIG_person/BI_audit_MSIG_person')->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
				'nazwisko',
				'imiona',
				'pesel',
				'ID',
				// 'dataDokumentu',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/ID',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/krs',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/nazwa',
				// 'default_db__x3A__BI_audit_KRS_company:BI_audit_KRS_company/regon',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/ID',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/imiona',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/nazwisko',
				// 'default_db__x3A__BI_audit_KRS_person:BI_audit_KRS_person/pesel',
			],
			// 'f_ID' => "{$id}",
		], $searchParams))->getItems([
			'limit' => 10
		]);
		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

		return [
			'type' => 'success',
			'msg' => 'MSIG',
			'__args' => $args,
			'body' => [
				'items' => array_map(function ($item) {
					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
					//$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
					//$item['nazwa'] = $nazwa;
					$item['label'] = "{$item['nazwisko']}, {$item['imiona']}, {$item['pesel']}";
					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

					return $item;

					// return [
					// 	'ID' => $item['ID'],
					// 	'nazwa' => $shortNazwa,
					// 	'nip' => $item['nip'],
					// 	'krs' => $item['krs'],
					// 	'regon' => $item['regon'],
					// 	'S_miejscowosc' => $item['S_miejscowosc'],
					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
					// ];
				}, $items),
			]
		];
	}

	function fetchFromCEIDG($wordsQuery) {
		$query = implode(" ", $wordsQuery);
		if (empty($wordsQuery)) throw new Exception("Empty search");
		$searchableFields = [];
		$searchableFields[] = 'firma';
		$searchableFields[] = 'nazwisko';
		$searchableFields[] = 'imie';
		$searchableFields[] = 'miejscowosc';
		$searchParams = [ 'ogc:Filter' => $this->generateOgcFilterFromWords($wordsQuery, $searchableFields) ];
		$items = ACL::getAclByNamespace('default_db/BI_audit_CEIDG/BI_audit_CEIDG')->buildQuery(array_merge([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'budynek',
				'firma',
				'gmina',
				'identyfikatorWpisu',
				'imie',
				'kodPocztowy',
				'kraj',
				'lokal',
				'miejscowosc',
				'nazwisko',
				'nip',
				'poczta',
				'powiat',
				'regon',
				'ulica',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ID',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/budynek',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/gmina',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/kodPocztowy',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/lokal',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/miejscowosc',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nazwa',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/nip',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/poczta',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/powiat',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/ulica',
				// 'default_db__x3A__BI_audit_CEIDG_pelnomocnicy:BI_audit_CEIDG_pelnomocnicy/wojewodztwo',
				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/ID',
				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/nip',
				// 'default_db__x3A__BI_audit_CEIDG_powiazania:BI_audit_CEIDG_powiazania/regon',
			],
			// 'f_ID' => "{$id}",
		], $searchParams))->getItems([
			'limit' => 10
		]);
		DBG::log($items, 'array', "DBG: items query({$query}) from '{$baza}'");

		return [
			'type' => 'success',
			'msg' => 'CEIDG',
			'__args' => $args,
			'body' => [
				'items' => array_map(function ($item) {
					//$nazwa = str_replace([ '"', "'" ], '', $item['nazwa']);
					//$nazwa = str_replace("SPÓŁKA Z OGRANICZONĄ ODPOWIEDZIALNOŚCIĄ", "Sp. z o.o.", $nazwa);
					//$item['nazwa'] = $nazwa;
					$item['label'] = "{$item['firma']} {$item['imie']} {$item['nazwisko']}, {$item['miejscowosc']}, {$item['nip']}, {$item['regon']}";
					// 'searchLabel' => "{$item['nazwa']}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",

					return $item;

					// return [
					// 	'ID' => $item['ID'],
					// 	'nazwa' => $shortNazwa,
					// 	'nip' => $item['nip'],
					// 	'krs' => $item['krs'],
					// 	'regon' => $item['regon'],
					// 	'S_miejscowosc' => $item['S_miejscowosc'],
					// 	'label' => "{$nazwa}, {$item['A_miejscowosc']}, {$item['krs']}, {$item['nip']}, {$item['regon']}",
					// ];
				}, $items),
			]
		];
	}


	public function showTableKontrahenci($labels = []) {
		// TODO: use self::$FIELD_LIST_KONTRAHENCI
		$view = '<form class="form-horizontal" method="post">
						<table class="table table-bordered table-hover table-striped" height=5>
									 <thead>
										 <tr>
												<td width=1><input type="checkbox" name="checkAll" id="checkAll-KONTRAHENCI" /></td>
												<td width=1>' . V::get('ID', 'ID', $labels) . '</td>
												<td>' . V::get('Nazwa_grupy_kapitalowej', 'Nazwa grupy kapitalowej', $labels) . '</td>
												<td>' . V::get('Pelna_nazwa_kontrahenta', 'Pelna nazwa kontrahenta', $labels) . '</td>
												<td>' . V::get('Numer_kontrahenta', 'Numer kontrahenta', $labels) . '</td>
												<td>' . V::get('Skrocona_Nazwa_Kontrahenta', 'Skrócona nazwa kontrahenta', $labels) . '</td>
												<td>' . V::get('Typ_kontrahenta', 'Typ_kontrahenta', $labels) . '</td>
												<td>' . V::get('NIP', 'NIP', $labels) . '</td>
												<td>' . V::get('KRS', 'KRS', $labels) . '</td>
												<td>' . V::get('REGON', 'Regon', $labels) . '</td>
												<td>' . V::get('PESEL', 'PESEL', $labels) . '</td>
												<td>' . V::get('Forma_prawna_dzialalnosci', 'Forma prawna działalności', $labels) . '</td>
												<td>' . V::get('Ulica', 'Ulica', $labels) . '</td>
												<td>' . V::get('Numer_budynku', 'Numer budynku', $labels) . '</td>
												<td>' . V::get('Numer_mieszkania_lokalu', 'Numer mieszkania lokalu', $labels) . '</td>
												<td>' . V::get('Miejscowosc', 'Miejscowosc', $labels) . '</td>
												<td>' . V::get('Kod_pocztowy', 'Kod pocztowy', $labels) . '</td>
												<td>' . V::get('Kraj', 'Kraj', $labels) . '</td>
												<td>' . V::get('Telefon', 'Telefon', $labels) . '</td>
												<td>' . V::get('Fax', 'Fax', $labels) . '</td>
												<td>' . V::get('Mail', 'Mail', $labels) . '</td>
												<td>' . V::get('A_ADM_COMPANY', 'A_ADM_COMPANY', $labels) . '</td>
												<td>' . V::get('A_CLASSIFIED', 'A_CLASSIFIED', $labels) . '</td>
												<td>' . V::get('Dodano', 'Dodano', $labels) . '</td>
												<td>' . V::get('Podmiot_dominujacy', 'Podmiot dominujacy', $labels) . '</td>
												<td>' . V::get('Tytul_dokumentu', 'Tytul dokumentu', $labels) . '</td>
												<td>' . V::get('ownCompany', 'ownCompany', $labels) . '</td>
												<td>' . V::get('uwagi', 'uwagi', $labels) . '</td>
										 </tr>
										 <tr>
											<td style="padding:0" width=1><button style="padding:5px" id="filtersFieldRemoveBtn-KONTRAHENCI" onClick="return removeFiltersKontrahenci(event, this)" title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button></td>
											<td style="padding:0"><input style="padding:2px 8px; width:80px" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_ID" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Nazwa_grupy_kapitalowej" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Pelna_nazwa_kontrahenta" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_kontrahenta" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Skrocona_Nazwa_Kontrahenta" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Typ_kontrahenta" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_NIP" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_KRS" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_REGON" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_PESEL" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Forma_prawna_dzialalnosci" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Ulica" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_budynku" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Numer_mieszkania_lokalu" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Miejscowosc" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Kod_pocztowy" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Kraj" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Telefon" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Fax" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Mail" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_A_ADM_COMPANY" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_A_CLASSIFIED" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Dodano" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Podmiot_dominujacy" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_Tytul_dokumentu" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_ownCompany" value="" placeholder="%"></td>
											<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersKontrahenci(event, this)" onKeypress="return onKeypressFiltersKontrahenci(event, this)" type="text" name="f_uwagi" value="" placeholder="%"></td>
										 </tr>
										 </thead>
										 <tbody id="body-kontrahenci">
										 </tbody></table>
										 </form>
					';

		return $view;
	}

	// tworzenie grupy kontrahentów
	public function createKontrahenciGroupAjaxAction() {
		Response::sendTryCatchJson(array($this, 'createKontrahenciGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}

	public function createKontrahenciGroupAjax($args) {
		$nazwa = V::get('NAZWA', '', $args);
		// TODO: vlaidacja nazwy - sprawdzenie czy już nie występuje


		$idGroup = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_group', [
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
			'NAZWA' => $nazwa,
			'ID_USER' => User::getID()
		]);

		return [
			'msg' => "Utworzona grupę {$idGroup}",
			'type' => "success",
			'body' => [
				'id' => $idGroup,
				'nazwa' => $nazwa
			]
		];
	}


	// Dodanie do grupy filtra kontrahentów
	public function addKontrahenciToGroupAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'addKontrahenciToGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function addKontrahenciToGroupAjax($args) {
		$idGroup = V::get('idGroup', '', $args);
		$type = V::get('type', 'ids', $args);
		$kontrahenciIds = V::get('kontrahenciIds', '', $args);
		$filter = V::get('filter', '', $args);

		// validate
		if (!$idGroup) throw new Exception("Nie wybrano grupa");
		switch ($type) {
			case 'ids': {
				if (!$kontrahenciIds || count($kontrahenciIds) == 0) throw new Exception("Proszę wybrać kontrahentów");
			} break;
			case 'filter': {
				if (!isset($args['filter'])) throw new Exception("Proszę wybrać kontrahentów");
			} break;
			default: throw new Exception("Missing type");
		}
		$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'ID_USER',
				'NAZWA',
			],
			// 'f_ID_USER' => User::getID()
		])->getItem($idGroup);
		if (!$group) throw new Exception("Grupa nie istnieje");
		if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");

		if ('filter' === $type) {
			$args__idGroup = V::get('filterIdGroup', 0, $args['filter'], 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
			if ($args__idGroup < 0) $args__idGroup = 0;
			$search = V::get('search', '', $args['filter']);
			$searchParams = [];
			if (!empty($search)) {
				$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
				$searchParams['ogc:Filter'] = '
					<ogc:Filter>
				    <ogc:Or>
				      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
				        <ogc:PropertyName>NIP</ogc:PropertyName>
				        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
				      </ogc:PropertyIsLike>
				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
				        <ogc:PropertyName>Nazwa_grupy_kapitalowej</ogc:PropertyName>
								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
				      </ogc:PropertyIsLike>
				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
				        <ogc:PropertyName>Pelna_nazwa_kontrahenta</ogc:PropertyName>
								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
				      </ogc:PropertyIsLike>
				    </ogc:Or>
				  </ogc:Filter>
				';
			}

			$backRefFilter = [];
			if ($args__idGroup > 0) {
				$backRefFilter['__backRef'] = [
					'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
					'primaryKey' => $args__idGroup,
					'fieldName' => 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
				];
			}

			$filtersParams = [];
			$fieldFilterKeys = array_filter(array_keys($args['filter']), function ($key) {
				return ('f_' === substr($key, 0, 2));
			});
			foreach ($fieldFilterKeys as $key) {
				$filtersParams[ $key ] = '%' . $args['filter'][ $key ] . '%';
			}

			$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI');
			$query = $acl->buildQuery(array_merge([
				'cols' => ['ID'],
			], $searchParams, $filtersParams, $backRefFilter, [
				'limit' => 0
			]));
			$items = $query->getItems();

			$kontrahenciIds = array_map(function ($row) {
				return $row['ID'];
			}, $items);
		}

		ACL::addListRef(
			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
			$refPrimaryKey = $idGroup,
			$refListRemotePrimaryKey = $kontrahenciIds
		);

		return [
			'msg' => "Powiązano kontrahentów z grupą {$idGroup}",
			'type' => "success",
		];
	}

	public function removePracownicyFromGroupAjaxAction(){
		Response::sendTryCatchJson(array($this, 'removePracownicyFromGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function removePracownicyFromGroupAjax($args){
		$idGroup = V::get('idGroup', 0, $args, "int");
		$pracownicyIds = V::get('pracownicyIds', [], $args, 'array');
		if ($idGroup === 0){
			foreach ($pracownicyIds as $pracownikIds) {
				//TO DO Błąd do naprawienia
				//TO DO sprawdzanie czy już DELETED
				$affected = DB::getPDO()->update('BI_audit_ENERGA_PRACOWNICY', 'ID', $pracownikIds, [
					'A_STATUS' => 'DELETED',
					'A_RECORD_UPDATE_DATE' => 'NOW()',
				  'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
				]);
			}
			return [
				'msg' => "Usunięto osoby z systemu",
				'type' => "success",
			];
		} else {
			$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
				'cols' => [ // TODO:? propertyName = []
					'ID',
					'ID_USER',
					'NAZWA',
				],
				// 'f_ID_USER' => User::getID()
			])->getItem($idGroup);
			if (!$group) throw new Exception("Grupa nie istnieje");
			if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");

			ACL::removeListRef(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
				$refPrimaryKey = $idGroup,
				$refListRemotePrimaryKey = $pracownicyIds
			);

			return [
				'msg' => "Usunięto osoby z grupy {$idGroup}",
				'type' => "success",
			];
		}
	}


	public function removeKontrahenciFromGroupAjaxAction() {
		Response::sendTryCatchJson(array($this, 'removeKontrahenciFromGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function removeKontrahenciFromGroupAjax($args) {
		$idGroup = V::get('idGroup', 0, $args, "int");
		$kontrahenciIds = V::get('kontrahenciIds', [], $args, 'array');
		if ($idGroup === 0) {
			foreach ($kontrahenciIds as $kontrahentIds) {
				$affected = DB::getPDO()->update('BI_audit_ENERGA_RUM_KONTRAHENCI', 'ID', $kontrahentIds, [
					'A_STATUS' => 'DELETED',
					'A_RECORD_UPDATE_DATE' => 'NOW()',
				  'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
				]);
			}
			return [
				'msg' => "Usunięto kontrahentów z systemu",
				'type' => "success",
			];
		} else {
			$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
				'cols' => [ // TODO:? propertyName = []
					'ID',
					'ID_USER',
					'NAZWA',
				],
				// 'f_ID_USER' => User::getID()
			])->getItem($idGroup);
			if (!$group) throw new Exception("Grupa nie istnieje");
			if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");

			ACL::removeListRef(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
				$refPrimaryKey = $idGroup,
				$refListRemotePrimaryKey = $kontrahenciIds
			);

			return [
				'msg' => "Usunięto kontrahentów z grupy {$idGroup}",
				'type' => "success",
			];
		}
	}


	public function fetchGroupKontrahenciAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchGroupKontrahenciAjax'));
	}
	public function fetchGroupKontrahenciAjax() {
		$query = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'ID_USER',
				'NAZWA',
			],
			'f_ID_USER' => "=" . User::getID(),
			'f_A_STATUS' => "!DELETED",
		]);
		$itemsKontrahenci = $query->getItems();
		if (empty($itemsKontrahenci)) throw new AlertWarningException("Grupy nie istnieją");

		$arrayGroupKontrahenci = array();
		foreach ($itemsKontrahenci as $item) {
			// if (User::getID() != $item['ID_USER']) throw new Exception("Brak uprawnień do grupy");
			$arrayGroupKontrahenci[] = [
				'NAZWA' => $item['NAZWA'],
				'ID' => $item['ID'],
			];
		}

		return [
			'type' => 'success',
			'msg' => 'fetchGroupKontrahenciAjax',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'itemsGroupKontrahenci' => $arrayGroupKontrahenci
			]
		];
	}


	public function fetchPracownicyIdsAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchPracownicyIdsAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
 	public function fetchPracownicyIdsAjax($args) {
		$idGroup = V::get('filter_idGroup', 0, $args, 'int');
		if ($idGroup < 0) $idGroup = 0;
		$backRefFilter = [];
		if ($idGroup > 0) {
			$backRefFilter['__backRef'] = [
				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				'primaryKey' => $idGroup,
				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
			];
		}

		$searchParams = []; // TODO: ???

		$filtersParams = [];
		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
			return ('f_' === substr($key, 0, 2));
		});
		foreach ($fieldFilterKeys as $key) {
			$filtersParams[ $key ] = '%' . $args[ $key ] . '%';
		}

		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
		$query = $acl->buildQuery(array_merge([
			'cols' => [
				'ID',
			],
			//'f_ID' => $id,
			'limit' => 0,
			// 'limitstart' => $limitstart, // offset
			// 'order_by' => 'ID', // sortowanie po kolumnie
			// 'order_dir' => 'DESC', // kierunek sortowania
			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
		], $searchParams, $filtersParams, $backRefFilter));
		// $total = $query->getTotal();
		$items = $query->getItems();

		return [
			'type' => 'success',
			'msg' => 'pracownicy ids',
			'body' => [
				'ids' => array_map( V::makePick('ID'), $items ),
			],
			'__args' => $args,
			'__DBG_$idGroup' => $idGroup,
			'__DBG_$filtersParams' => $filtersParams,
			'__DBG_$backRefFilter' => $backRefFilter,
		];
	}
	/*
	 * PRACOWNICY
	 */
	public function fetchPracownicyAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchPracownicyAjax'), $args = $_REQUEST);
	}
	public function fetchPracownicyAjax($args) {

		$idGroup = V::get('filterIdGroup', 0, $args, 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
		if ($idGroup < 0) $idGroup = 0;

		$limit = 20;

		$page = V::get('page', 0, $args, 'int');
		$limitstart = ($page - 1) * $limit;

		$search = V::get('search', '', $args);
		$searchParams = [];
		if (!empty($search)) {
			$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
			$searchParams['ogc:Filter'] = '
				<ogc:Filter>
			    <ogc:Or>
			      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
			        <ogc:PropertyName>nip</ogc:PropertyName>
			        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
			      </ogc:PropertyIsLike>
			      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
			        <ogc:PropertyName>nazwisko</ogc:PropertyName>
							<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
			      </ogc:PropertyIsLike>
			    </ogc:Or>
			  </ogc:Filter>
			';
		}

		$backRefFilter = [];
		if ($idGroup > 0) {
			$backRefFilter['__backRef'] = [
				'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
				'primaryKey' => $idGroup,
				'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
			];
		}

		$filtersParams = [];
		$fieldFilterKeys = array_filter(array_keys($args), function ($key) {
			return ('f_' === substr($key, 0, 2));
		});
		foreach ($fieldFilterKeys as $key) {
			if ('f_ID' === $key) $filtersParams[ $key ] = '=' . $args[ $key ];
			else $filtersParams[ $key ] = '%' . $args[ $key ] . '%';
		}

		$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
		$query = $acl->buildQuery(array_merge([
			'cols' => array_merge(self::$FIELD_LIST_PRACOWNICY, [
				'default_db__x3A__BI_audit_ENERGA_PRACOWNICY_adresy:BI_audit_ENERGA_PRACOWNICY_adresy/*'
			]),
			//'f_ID' => $id,
			'limit' => $limit,
			'limitstart' => $limitstart, // offset
			'order_by' => 'ID', // sortowanie po kolumnie
			'order_dir' => 'DESC', // kierunek sortowania
			// 'f_nip' = "=12345", // szukamy dokładnie tej wartości - mysql: where nip = "12345"
			// 'f_nip' = "12345", // szukamy dokładnie tej wartości - mysql: where nip like "%12345%"
			// 'f_nip' = "12345%", // szukamy dokładnie tej wartości - mysql: where nip like "12345%"
			// 'f_ID' = "=12345", // szukamy dokładnie tej wartości - mysql: where ID = "12345"
		], $searchParams, $filtersParams, $backRefFilter));
		$total = $query->getTotal();
		$items = $query->getItems();

		$pagination = array();
		$pagination['total_items'] = $total;
		$pagination['size'] = ceil($total/$limit); // pages size
		$pagination['current'] = $page;
		$pagination['limit'] = $limit;
		// $idGroup = V::get('filterIdGroup', 0, $_REQUEST, 'int'); // TODO: dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
		if ($idGroup > 0) $pagination['filter_idGroup'] = $idGroup;

		// { // tworzenie własnego zapytanie mysql
		// 	$rootTableName = $acl->getRootTableName();
		// 	DB::getPDO()->fetchAll("
		// 		select t.*
		// 		from {$rootTableName} t
		// 		where t.ID in (
		// 			select x.ID
		// 			from ... x
		// 			where
		// 		)
		// 	");
		// }

		return [
			'type' => 'success',
			'msg' => 'showPracownicy',
			'body' => [
				'items' => $items,
				//'view' => $this->htmlViewFormBiAudit($items, 'PRACOWNICY'),
				'pagination' => $pagination
			],
			'__DBG_$idGroup' => $idGroup,
			'__DBG_$filtersParams' => $filtersParams,
			'__DBG_$backRefFilter' => $backRefFilter,
		];
	}



	public function showTablePracownicy($labels = []) {
		// TODO: use self::$FIELD_LIST_PRACOWNICY
			$view = '<form class="form-horizontal" method="post">
							<table class="table table-responsive table-bordered table-hover table-striped" height=5>
										 <thead>
											 <tr>
											 		<td width=1><input type="checkbox" name="checkAll" id="checkAll-PRACOWNICY" /></td>
													<td width=1>' . V::get('ID', 'ID', $labels) . '</td>
													<td>' . V::get('imiona', 'Imię/Imiona', $labels) . '</td>
													<td>' . V::get('nazwisko', 'Nazwisko', $labels) . '</td>
													<td>' . V::get('nip', 'NIP', $labels) . '</td>
													<td>' . V::get('pesel', 'Pesel', $labels) . '</td>
													<td>' . V::get('regon', 'Regon', $labels) . '</td>
													<td>' . V::get('source', 'source', $labels) . '</td>
													<td>' . V::get('jednostka_organizacyjna', 'jednostka_organizacyjna', $labels) . '</td>
													<td>' . V::get('A_STATUS', 'A_STATUS', $labels) . '</td>
													<td>' . V::get('A_STATUS_INFO', 'A_STATUS_INFO', $labels) . '</td>
													<td>' . V::get('L_APPOITMENT_USER', 'L_APPOITMENT_USER', $labels) . '</td>
													<td>' . V::get('Adresy', 'Adresy', $labels) . '</td>
											 </tr>
											 <tr>
												<td style="padding:0" width=1><button style="padding:5px" id="filtersFieldRemoveBtn-PRACOWNICY" onClick="return removeFiltersPracownicy(event, this)" title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button></td>
												<td style="padding:0"><input style="padding:2px 8px; width:80px" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_ID" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_imiona" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_nazwisko" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_nip" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_pesel" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_regon" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_source" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_jednostka_organizacyjna" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_A_STATUS" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_A_STATUS_INFO" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_L_APPOITMENT_USER" value="" placeholder="%"></td>
												<td style="padding:0"><input style="padding:2px 8px; width:100%" onChange="return onChangeFiltersPracownicy(event, this)" onKeypress="return onKeypressFiltersPracownicy(event, this)" type="text" name="f_Adresy" value="" placeholder="%"></td>
											 </tr>
										 </thead>
										 <tbody id="body-pracownicy">
										 </tbody></table>
										 </form>';
						return $view;

	}


	// tworzenie grupy pracowników
	public function createPracownicyGroupAjaxAction() {
		Response::sendTryCatchJson(array($this, 'createPracownicyGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function createPracownicyGroupAjax($args) {
		$nazwa = V::get('NAZWA', '', $args);

		// validate
		if (!$nazwa) throw new Exception("Nie wybrano grupa");

		$idGroup = DB::getPDO()->insert('BI_audit_ENERGA_PRACOWNICY_group', [
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
			'NAZWA' => $nazwa,
			'ID_USER' => User::getID()
		]);

		return [
			'msg' => "Utworzona grupę {$nazwa}",
			'type' => "success",
			'body' => [
				'id' => $idGroup,
				'nazwa' => $nazwa
			]
		];
	}

	// Dodanie do grupy filtra pracowników
	public function addPracownicyToGroupAjaxAction() {
		 Response::sendTryCatchJson(array($this, 'addPracownicyToGroupAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
	}
	public function addPracownicyToGroupAjax($args) {
		$idGroup = V::get('idGroup', '', $args);
		$type = V::get('type', 'ids', $args);
		$pracownicyIds = V::get('pracownicyIds', '', $args);
		$filter = V::get('filter', '', $args);

		// validate
		if (!$idGroup) throw new Exception("Nie wybrano grupa");
		switch ($type) {
			case 'ids': {
				if (!$pracownicyIds || count($pracownicyIds) == 0) throw new Exception("Proszę wybrać pracowników");
			} break;
			case 'filter': {
				if (empty($filter)) throw new Exception("Proszę wybrać pracowników");
			} break;
			default: throw new Exception("Missing type");
		}

		// TODO: SPRWADZENIE  CZY NIE DODANOU JUZ PRACOWNIKAS
		// default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group
		// default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY

		$group = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'ID_USER',
				'NAZWA',
			],
			// 'f_ID_USER' => User::getID()
		])->getItem($idGroup);
		if (!$group) throw new Exception("Grupa nie istnieje");
		if (User::getID() != $group['ID_USER']) throw new Exception("Brak uprawnień do grupy");

		if ('filter' === $type) {
			$args__idGroup = V::get('filterIdGroup', 0, $filter, 'int'); // dla filtrów "Wysokiego ryzyka" - przekazywany ID rekodu
			if ($args__idGroup < 0) $args__idGroup = 0;
			$search = V::get('search', '', $filter);
			$searchParams = [];
			if (!empty($search)) {
				$ogcSearch = "*{$search}*"; // wildCard="*" -> mysql '%'
				$searchParams['ogc:Filter'] = '
					<ogc:Filter>
				    <ogc:Or>
				      <ogc:PropertyIsLike wildCard="" singleChar="%23" escapeChar="!">
				        <ogc:PropertyName>nip</ogc:PropertyName>
				        <ogc:Literal>' . $ogcSearch . '</ogc:Literal>
				      </ogc:PropertyIsLike>
				      <ogc:PropertyIsLike wildCard="*" singleChar="%23" escapeChar="!">
				        <ogc:PropertyName>nazwisko</ogc:PropertyName>
								<ogc:Literal>' . $ogcSearch . '</ogc:Literal>
				      </ogc:PropertyIsLike>
				    </ogc:Or>
				  </ogc:Filter>
				';
			}

			$backRefFilter = [];
			if ($args__idGroup > 0) {
				$backRefFilter['__backRef'] = [
					'namespace' => 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
					'primaryKey' => $args__idGroup,
					'fieldName' => 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
				];
			}

			$filtersParams = [];
			$fieldFilterKeys = array_filter(array_keys($filter), function ($key) {
				return ('f_' === substr($key, 0, 2));
			});
			foreach ($fieldFilterKeys as $key) {
				$filtersParams[ $key ] = '%' . $filter[ $key ] . '%';
			}

			$acl = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY');
			$query = $acl->buildQuery(array_merge([
				'cols' => ['ID'],
			], $searchParams, $filtersParams, $backRefFilter, [
				'limit' => 0
			]));
			$items = $query->getItems();

			$pracownicyIds = array_map(function ($row) {
				return $row['ID'];
			}, $items);
		}

		ACL::addListRef(
			$rootObjectNamespace = 'default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group',
			$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
			$refPrimaryKey = $idGroup,
			$refListRemotePrimaryKey = $pracownicyIds
		);

		return [
			'msg' => "Powiązano pracowników z grupą {$idGroup}",
			'type' => "success",
		];
	}


	public function fetchGroupPracownicyAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchGroupPracownicyAjax'));
	}
	public function fetchGroupPracownicyAjax() {
		$query = ACL::getAclByNamespace('default_db/BI_audit_ENERGA_PRACOWNICY_group/BI_audit_ENERGA_PRACOWNICY_group')->buildQuery([
			'cols' => [ // TODO:? propertyName = []
				'ID',
				'ID_USER',
				'NAZWA',
			],
			'f_ID_USER' => "=" . User::getID(), // szukamy dokładnie tej wartości - mysql: where ID_USER = "1"
			'f_A_STATUS' => "!DELETED", // `A_STATUS` != 'DELETED'
		]);
		$items = $query->getItems();
		DBG::log($items,'array',"grupy");
		if (empty($items)) throw new AlertWarningException("Grupy nie istnieją");

		$arrayGroupPracownicy = array();
		foreach ($items as $item) {
			// if (User::getID() != $item['ID_USER']) throw new Exception("Brak uprawnień do grupy"); // or skip - continue;
			$arrayGroupPracownicy[] = [
				'ID' => $item['ID'],
				'NAZWA' => $item['NAZWA'],
			];
 		}

		return [
			'type' => 'success',
			'msg' => 'fetchGroupPracownicyAjax',
			'__req_args' => $_REQUEST,
			'__args' => $args,
			'body' => [
				'itmesGroupPracownicy' => $arrayGroupPracownicy
			]
		];
	}


	// link do ackji w php: $saveFormUrl = $this->getLink('saveRaportAjax');
	// przekazać link do JavaScript i tam:
	// window.fetch('{$saveFormUrl}', { ... }).then(...) - dokumentacja: https://github.com/github/fetch
	public function generateBiAuditRaportAjaxAction() {
		 //Response::sendTryCatchJson(array($this, 'saveRaportAjax'), $args = 'JSON_FROM_REQUEST_BODY'); // użyj tej wersji jeśli chcesz wysyłać z przelgądarki JSON-a post-em
		Response::sendTryCatchJson(array($this, 'generateBiAuditRaportAjax'), $args = 'JSON_FROM_REQUEST_BODY');
		//Response::sendTryCatchJson(array($this, 'generateBiAuditRaportAjax'));
	}


	public function generateBiAuditRaportAjax($args) {

		// głebokość powiazan
		$depthValue = V::get('depthValue', '', $args);
		if (!$depthValue) {
			throw new Exception("Nie podano wartości dla głębokości powiązań");
		}

		// tytuł raportu
		$smadReaportTitle = V::get('smadReaportTitle', '', $args);
		if (!$smadReaportTitle) {
			throw new Exception("Nie podano tytułu raportu");
		}

		// Bi_analiza_onlyTarger
		$analizaOnlyTargets = V::get('analizaOnlyTargets', '', $args);
		if (!$analizaOnlyTargets) {
			throw new Exception("Nie podano wartości czy zwracać wyniki tylko z obiektami docelowymi");
		}

		$pracownicyIds = V::get('pracownicyIds', [], $args, 'uint_array'); // array of int > 0
		$kontrahenciIds = V::get('kontrahenciIds', [], $args, 'uint_array'); // array of int > 0

		// walidacja listy kontrahentów i pracowników
		if ( empty($kontrahenciIds) && empty($pracownicyIds) ) {
			throw new Exception("Nie wybrano pozycji do analizy. Wybierz pracowników/kontrahentów.");
		}

		// Tworzenie rekrodu w bazie - Raport -
		$idRaport = DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA', [
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
			'L_APPOITMENT_INFO' => $smadReaportTitle,
			'FILE_STATUS' => "TO_GENERATE",
			'A_STATUS' => "NORMAL",
			'BI_analiza_minDepth' => 1,
			'BI_analiza_maxDepth' => $depthValue,
			'BI_analiza_onlyTargets' => $analizaOnlyTargets
		]);
		if ($idRaport <= 0) throw new Exception("Nie udało się dodać nowego raportu");

		DB::getPDO()->insert('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_HIST', [
			'ID_USERS2' => $idRaport,
			'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
			'A_RECORD_CREATE_DATE' => 'NOW()',
			'L_APPOITMENT_INFO' => $smadReaportTitle,
			'FILE_STATUS' => "TO_GENERATE",
			'A_STATUS' => "NORMAL",
			'BI_analiza_minDepth' => 1,
			'BI_analiza_maxDepth' => $depthValue,
			'BI_analiza_onlyTargets' => $analizaOnlyTargets
		]);

		if (!empty($pracownicyIds)) {
			ACL::addListRef(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY',
				$refPrimaryKey = $idRaport,
				$refListRemotePrimaryKey = $pracownicyIds
			);
		} else {
			$refRaportToPracownicyConfig = ACL::getRefConfig(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_PRACOWNICY:BI_audit_ENERGA_PRACOWNICY'
			);
			DB::getPDO()->execSql("
				insert into `{$refRaportToPracownicyConfig->tableName}` (`PRIMARY_KEY`,`REMOTE_PRIMARY_KEY`)
				select {$idRaport} as PRIMARY_KEY, ID as REMOTE_PRIMARY_KEY
				from `BI_audit_ENERGA_PRACOWNICY`
				where `A_STATUS` != 'DELETED'
			");
		}

		if (!empty($kontrahenciIds)) {
			ACL::addListRef(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI',
				$refPrimaryKey = $idRaport,
				$refListRemotePrimaryKey = $kontrahenciIds
			);
		} else {
			$refRaportToKontrahenciConfig = ACL::getRefConfig(
				$rootObjectNamespace = 'default_db/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA/BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA',
				$fieldTypeName = 'default_db__x3A__BI_audit_ENERGA_RUM_KONTRAHENCI:BI_audit_ENERGA_RUM_KONTRAHENCI'
			);
			DB::getPDO()->execSql("
				insert into `{$refRaportToKontrahenciConfig->tableName}` (`PRIMARY_KEY`,`REMOTE_PRIMARY_KEY`)
				select '{$idRaport}' as PRIMARY_KEY, ID as REMOTE_PRIMARY_KEY
				from `BI_audit_ENERGA_RUM_KONTRAHENCI`
				where `A_STATUS` != 'DELETED'
			");
		}

		return [
			'msg' => "Zadanie do wygnerowania raportu zostało zapisane.",
			'type' => "success",
			'body' => [
				'id' => $idRaport,
			]
		];
	}


	/**
	* Widok formularza dodawania pracowników i kontrahentów
	*/
	public function defaultViewFormBiAudit($items, $type) {
		$activeFormSteps = '';
		$fieldLabels = [];
		$currentDate = date("j.n.Y");
		switch($type) {
				case 'KONTRAHENCI':

					$activeFormStepsKontrahent = 'complete';

					$titleHeader = 'KONTRAHENCI/PODMIOTY';

					$groupFilterList = '
					<div class="menu-item">
							<ul class="padding-0">
									<li><a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupKontrahenci(event)" data-color-noactive="">+ STWÓRZ GRUPĘ</a></li>
							</ul>
					</div>
					<div id="group-kontrahenci" class="btn-group">
							<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
					</div>';

					$formSmadDepth = '<input type="text" class="form-control smad-depth-kontrahenci" placeholder="1-16" value="" />';

					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target-kontrahenci"><option value="y">tak</option><option value="n">nie</option></select>';

					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-kontrahenci">Wszyscy</h2>';
					$formFilterHeadDesc = '<p>Liczba pozycji na liście: <span id="smad-filter-desc-kontrahenci">0</span></p>';
					$countSelectedItem = '<div>Wybrano: <span id="count-selected-item-kontrahenci">0</span> <span><a title="wyczyść zapamietanych kontrahentów"  class="link-primary" onClick="clearListLocalStorageByType(\'kontrahenci\')"><small>(wyczyść)</small></a></span></div>';

					$graphView = '<div class="smad-kontrahenci-graph-view" style="display: none;"></div>';

					$csvExampleKontrahenci = Request::getPathUri() . 'projects/bocian/theme/assets/file_example/kontrahenci_example.zip';
					$formAddNewData ='
					<li><a title="IMPORT KONTRAHENCI" onClick="showViewUploadFile(event, \'Import podmiotów/kontrahentów\', \'kontrahenci\', \'no\', \''.$csvExampleKontrahenci.'\' )" class="btn btn-info">IMPORT KONTRAHENCI</a></li>
					<li><a title="DODAJ KONTRAHENCI" onClick="createKontrahentAjax(event)" class="btn btn-info">+ DODAJ PODMIOT</a></li>'; //todo: dodać obsługe doddawania kontrahentow

					$buttonMoveToGroup = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addKontrahenciToGroup(event)" class="btn btn-info">DODAJ WYBRANE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addKontrahenciAllToGroup(event)" class="btn btn-info" style="margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="USUN WYBRANE Z GRUPY" onClick="removeKontrahenciFromGroup(event)" class="btn btn-info" style="margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';

					$formSmadReaportTitleInput = '<input type="text" class="form-control smad-reaport-title-kontrahenci" placeholder="Raport bez tytułu z dnia ' .$currentDate .'" value="" />';

					$showButtonNextStep = '';

					$pagination_form = '<div id="pagination-kontrahenci"></div>';

					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI");
					$fieldList = $acl->getRealFieldList();
					$fieldLabels = array_combine(
						$fieldList,
						array_map(function ($fieldName) use ($acl) {
							return $acl->getFieldLabel($fieldName);
						}, $fieldList)
					);
					DBG::log($fieldLabels, 'array', "fieldLabels (KONTRAHENCI)");
				break;

				case 'OPERACYJNA_BAZA_ZGLOSZEN':

					$activeFormStepsKontrahent = 'complete';

					$titleHeader = 'KONTRAHENCI/PODMIOTY';

					$groupFilterList = '
					<div class="menu-item">
							<ul class="padding-0">
									<li><a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupKontrahenci(event)" data-color-noactive="">+ STWÓRZ GRUPĘ</a></li>
							</ul>
					</div>
					<div id="group-kontrahenci" class="btn-group">
							<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
					</div>';

					$formSmadDepth = '<input type="text" class="form-control smad-depth-kontrahenci" placeholder="1-16" value="" />';

					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target-kontrahenci"><option value="y">tak</option><option value="n">nie</option></select>';

					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-kontrahenci">Wszyscy</h2>';
					$formFilterHeadDesc = '<p>Liczba pozycji na liście: <span id="smad-filter-desc-kontrahenci">0</span></p>';
					$countSelectedItem = '<div>Wybrano: <span id="count-selected-item-kontrahenci">0</span> <span><a title="wyczyść zapamietanych kontrahentów"  class="link-primary" onClick="clearListLocalStorageByType(\'kontrahenci\')"><small>(wyczyść)</small></a></span></div>';

					$graphView = '<div class="smad-kontrahenci-graph-view" style="display: none;"></div>';

					$csvExampleKontrahenci = Request::getPathUri() . 'projects/bocian/theme/assets/file_example/kontrahenci_example.zip';
					$formAddNewData ='
					<li><a title="IMPORT KONTRAHENCI" onClick="showViewUploadFile(event, \'Import podmiotów/kontrahentów\', \'kontrahenci\', \'no\', \''.$csvExampleKontrahenci.'\' )" class="btn btn-info">IMPORT KONTRAHENCI</a></li>
					<li><a title="DODAJ KONTRAHENCI" onClick="createKontrahentAjax(event)" class="btn btn-info">+ DODAJ PODMIOT</a></li>'; //todo: dodać obsługe doddawania kontrahentow

					$buttonMoveToGroup = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addKontrahenciToGroup(event)" class="btn btn-info">DODAJ WYBRANE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addKontrahenciAllToGroup(event)" class="btn btn-info" style="margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="USUN WYBRANE Z GRUPY" onClick="removeKontrahenciFromGroup(event)" class="btn btn-info" style="margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';

					$formSmadReaportTitleInput = '<input type="text" class="form-control smad-reaport-title-kontrahenci" placeholder="Raport bez tytułu z dnia ' .$currentDate .'" value="" />';

					$showButtonNextStep = '';

					$pagination_form = '<div id="pagination-kontrahenci"></div>';

					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_RUM_KONTRAHENCI/BI_audit_ENERGA_RUM_KONTRAHENCI");
					$fieldList = $acl->getRealFieldList();
					$fieldLabels = array_combine(
						$fieldList,
						array_map(function ($fieldName) use ($acl) {
							return $acl->getFieldLabel($fieldName);
						}, $fieldList)
					);
					DBG::log($fieldLabels, 'array', "fieldLabels (KONTRAHENCI)");
				break;

				case 'PRACOWNICY':
					$titleHeader = 'OSOBY';

					$groupFilterList = '
					<div class="menu-item">
							<ul class="padding-0">
									<li><a href="#" title="STWÓRZ GRUPĘ" class="btn btn-default" onClick="createGroupPracownicy(event)" >+ STWÓRZ GRUPĘ</a></li>
							</ul>
					</div>
					<div id="group-pracownicy" class="btn-group">
							<button class="btn btn-default active" title="Wszyscy" data-group-filter="0">Wszyscy</button>
					</div>';

					$formSmadDepth = '<input type="text" class="form-control smad-depth" placeholder="1-16" value="" />';

					$formSmadSelectTarget = '<select class="form-control" id="smad-select-target"><option value="y">tak</option><option value="n">nie</option></select>';

					$formFilterHeadTitle = '<h2 class="title" id="smad-filter-head-title-pracownicy">Wszyscy</h2>';
					$formFilterHeadDesc = '<p>Liczba pozycji na liście: <span id="smad-filter-desc-pracownicy">0</span></p>';
					$countSelectedItem = '<div>Wybrano: <span id="count-selected-item-pracownicy">0</span> <span><a title="wyczyść zapamietanych pracowników" class="link-primary" onClick="clearListLocalStorageByType(\'pracownicy\')"><small>(wyczyść)</small></a></span></div>';

					$graphView = '<div class="smad-pracownicy-graph-view" style="display: none;"></div>';

					$csvExamplePracownicy = Request::getPathUri() . 'projects/bocian/theme/assets/file_example/pracownicy_example.zip';
					$formAddNewData ='
					<li><a title="IMPORT PRACOWNIKÓW" onClick="showViewUploadFile(event, \'Import osób\', \'pracownicy\', \'yes\', \''.$csvExamplePracownicy.'\'  )" class="btn btn-info">IMPORT PRACOWNIKÓW</a></li>
					<li><a title="DODAJ PRACOWNIKÓW" onClick="createPracownikAjax(event)" class="btn btn-info" >+ DODAJ OSOBĘ</a></li>'; //todo: dodać obsługe doddawania pracownikow

					$buttonMoveToGroup = '<a title="DODAJ WYBRANE DO GRUPY" onClick="addPracownikToGroup(event)" class="btn btn-info">DODAJ WYBRANE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="DODAJ WSZYSTKIE DO GRUPY" onClick="addPracownikAllToGroup(event)" class="btn btn-info" style="margin-left:12px">DODAJ WSZYSTKIE DO GRUPY</a>';
					$buttonMoveToGroup .= '<a title="USUN WYBRANE Z GRUPY" onClick="removePracownikFromGroup(event)" class="btn btn-info" style="margin-left:12px">USUŃ WYBRANE Z GRUPY</a>';

					$showButtonNextStep = '<a href="'.Request::getPathUri().'index.php?_route=UrlAction_Bocian#KONTRAHENCI"  title="DODAJ DO ANALIZY" class="btn btn-primary">DODAJ DO ANALIZY</a>';

					$formSmadReaportTitleInput = '<input type="text" class="form-control smad-reaport-title-pracownicy" placeholder="Raport bez tytułu z dnia ' .$currentDate .'" value="" />';

					$pagination_form = '<div id="pagination-pracownicy"></div>';

					$acl = ACL::getAclByNamespace("default_db/BI_audit_ENERGA_PRACOWNICY/BI_audit_ENERGA_PRACOWNICY");
					$fieldList = $acl->getRealFieldList();
					$fieldLabels = array_combine(
						$fieldList,
						array_map(function ($fieldName) use ($acl) {
							return $acl->getFieldLabel($fieldName);
						}, $fieldList)
					);
					DBG::log($fieldLabels, 'array', "fieldLabels (PRACOWNICY)");
				break;
		}


			$view = '
			<!-- start:employees-section-->
			<div id="smad-employees-section" class="smad-form-' . $type . '" >
				<div class="container-fluid">
					<div>
							<div class="padding-lr-0">
									<div id="smad-menu-section">
											<div class="col-sm-12 col-md-6 padding-lr-0">
													<div class="menu-items">
															<div class="smad-heder-title menu-item"><span class="smad-line-red">|</span> ' . $titleHeader . ' </div>
													</div>
											</div>
											<div class="col-sm-12 col-md-6 padding-lr-0">
													<div class="form-steps">
															<!-- start:form steps wizard -->
															<div class="row smad-wizard" style="border-bottom:0;">
																	<div class="col-xs-4 col-md-4 smad-wizard-step complete"><!-- complited line -->
																			<div class="text-center smad-wizard-stepnum">&nbsp;</div>
																			<div class="progress"><div class="progress-bar"></div></div>
																			<a href="'.Request::getPathUri().'index.php?_route=UrlAction_Bocian#PRACOWNICY" class="smad-wizard-dot"></a>
																			<div class="smad-wizard-info complete text-center">
																					<div class="step-item"><a href="'.Request::getPathUri().'index.php?_route=UrlAction_Bocian#PRACOWNICY">Krok 1</a></div>
																					<div class="step-title">OSOBY <span class="top--count-selected-item-pracownicy"></span></div>
																			</div>
																	</div>

																	<div class="col-xs-4 col-md-4 smad-wizard-step ' . $activeFormStepsKontrahent . ' ">
																			<div class="text-center smad-wizard-stepnum">&nbsp;</div>
																			<div class="progress"><div class="progress-bar"></div></div>
																			<a href="'.Request::getPathUri().'index.php?_route=UrlAction_Bocian#KONTRAHENCI" class="smad-wizard-dot"></a>
																			<div class="smad-wizard-info  text-center">
																					<div class="step-item"><a href="'.Request::getPathUri().'index.php?_route=UrlAction_Bocian#KONTRAHENCI">Krok 2</a></div>
																					<div class="step-title">PODMIOTY/<BR />KONTRAHENCI <span class="top--count-selected-item-kontrahenci"></span></div>
																			</div>
																	</div>

																	<div class="col-xs-4 col-md-4 smad-wizard-step ">
																			<div class="text-center smad-wizard-stepnum">&nbsp;</div>
																			<div class="progress"><div class="progress-bar"></div></div>
																			<a href="#" class="smad-wizard-dot"></a>
																			<div class="smad-wizard-info  text-center">
																					<div class="step-item">Krok 3</div>
																					<div class="step-title">SZUKANIE POWIĄZAŃ</div>
																			</div>
																	</div>
															</div>
															<!-- end:form steps wizard -->
													</div>
											</div>
									</div>
							</div>
					</div>
			</div>

			<div class="container-fluid">
					<div class=" padding-lr-0">
							<div class="smad-divider"></div>
					</div>
			</div>
			<!-- start:filters -->
			<div class="container-fluid">
					<div class="row">
							<div>
									<div class="smad-employees-form-section" class="border-top-grey">
											<div class="col-md-9 smad-border-col">
													<div class="menu-items">
														'.$groupFilterList.'
														</div>
											</div>
											<div class="col-md-3">
													<div class="form-input">
															<div class="form-item col-md-7  col-lg-9 smad-heder-title">głębokość powiązań:</div>
															<div class="form-item col-md-5  col-lg-3">
																	'.$formSmadDepth.'
															</div>
													</div>
													<div class="form-input">
															<div class="form-item col-md-7  col-lg-9 smad-heder-title">Czy zwracać wyniki tylko ze znalezionymi obiektami docelowymi(z tabeli kontrahentów)?</div>
															<div class="form-item col-md-5  col-lg-3">
																	'.$formSmadSelectTarget.'
															</div>
													</div>
											</div>
									</div>
							</div>
					</div>
			</div>
			<!-- end:filters -->

			<!-- start:list employees -->
			<div class="container-fluid">

							<div class="padding-0 smad-employees-list-head">
									<div class="col-md-6">
											<header>
											'.$formFilterHeadTitle.'
											</header>
											<div class="desc">
													'.$formFilterHeadDesc.'
											</div>
											<div class="countSelectedItem">
													'.$countSelectedItem.'
											</div>
									</div>
									<div class="col-md-6">
											<div class="menu-items">
													<div class="menu-item">
															<ul class="padding-0">
																	'.$formAddNewData.'
															</ul>
													</div>
											</div>
									</div>
							</div>
			</div>

			<!-- Start: graph-view -->
			<div class="smad-graph-section">
				<div class="container-fluid">
				'.$graphView.'
				</div>
			</div>
			<!-- End: graph-view -->

			<div class="container-fluid">
					<div class="table-responsive padding-0" id="smad-table-' . $type . '">
							' . $this->showListDataByType($items, $type, $fieldLabels) . '
					</div>
			</div>
			<!-- end:list employees -->
			<!-- start:list paginations employees -->
			<div class="container-fluid ">
				<div>
					'. $pagination_form .'
				</div>
			</div>
			<!-- end:list paginations employees -->

			<!-- start:bottom buttons -->
			<div class="container-fluid smad-employees-bottom-navigation">
					<div class="padding-0">
							<div class="col-lg-6 ">
									'.$buttonMoveToGroup.'
							</div>
							<div class="col-lg-6 text-right">
									' . $showButtonNextStep . '
							</div>
					</div>
			</div>
			<!-- end:bottom buttons -->
	</div>
	<!-- start:employees-section -->

	<div class="container-fluid ">
			<div class="row">
					<div class="container text-center">
								<div class="col-md-7  col-lg-5 "  style="margin: 0 auto; float: none;">
									'.$formSmadReaportTitleInput.'
								</div>
					</div>
			</div>
 </div>
	<!-- START:bottom generate reaport-->
<div class="container-fluid smad-generate-reaport">
    <div class="row">
        <div class="container text-center">
            <button type="button" class="btn btn-default smad-generate-reaport-button" onclick="generateBiAuditRaport(event)" id="button-generate-reaport" >GENERUJ RAPORT POWIĄZAŃ</button>
        </div>
        <div class="container smad-generate-reaport-info text-center">
            <div class="step-title"><span class="bottom--count-selected-item-kontrahenci"></span></div>
            <div class="step-title"><span class="bottom--count-selected-item-pracownicy"></span></div>
						<div><strong><span class="bottom--message-warning-critical-search"></span></strong></div>
        </div>
    </div>
</div>
<!-- end:bottom generate reaport -->

			';
			return $view;
		}


	public function showListDataByType($items, $type='PRACOWNICY', $labels) {

			switch ($type) {
				case 'PRACOWNICY':
					return $this->showTablePracownicy($labels);
					break;
				case 'KONTRAHENCI':
					return $this->showTableKontrahenci($labels);
					break;
			}
	}

	function fetchProgressAjaxAction() {
		Response::sendTryCatchJson(array($this, 'fetchProgressAjax'), $args = 'JSON_FROM_REQUEST_BODY');
	}
	function fetchProgressAjax($args) {
		$DBG_FAKE_ANIM = false;
		if (empty($args['ids'])) return [ 'msg' => "empty ids", 'type' => "success" ];
		$ids = $args['ids'];

		// private static function getDirectory($table, $id) {
		$firstId = reset($ids);
		{
			Lib::loadClass('FoldersConfig');
			$folderConf = FoldersConfig::getAll('BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA_COLUMN');
			if (!isset($folderConf['mount_point'])) throw new HttpException("Błąd danych konfiguracyjnych<br>\n{$errMsg}", 404);
			$rootPath = $folderConf['mount_point'];
		}

		$statuses = array_map(function ($id) {
			return DB::getPDO()->fetchValue(" select FILE_STATUS from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = :id ", [ ':id' => $id ]);
		}, $ids);
		$statusesInfo = array_map(function ($id) {
			return DB::getPDO()->fetchValue(" select FILE_STATUS_info from BI_audit_ENERGA_RUM_KONTRAHENCI_POWIAZANIA where ID = :id ", [ ':id' => $id ]);
		}, $ids);
		$progress = array_map(function ($id, $idx) use ($rootPath, $statuses, $DBG_FAKE_ANIM) {
			DBG::log("Loop id({$id}) is-eq-82(".(82 == $id).") is-eq-'82'(".("82"==$id).")");
			DBG::log("Loop id({$id}) is-eq-80(".(80 == $id).") is-eq-'80'(".("80"==$id).")");
			$status = $statuses[$idx];
			if ($DBG_FAKE_ANIM && 82 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
			if ($DBG_FAKE_ANIM && 80 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
			if ($DBG_FAKE_ANIM && 77 == $id) $status = 'IN_PROGRESS'; // TODO: DBG
			DBG::log("Loop id({$id}) status({$status})...");

			if ('GENERATED' === $status) return 1;
			if ('IN_PROGRESS' !== $status) return 0;

			if (!file_exists("{$rootPath}/.tasks/generatePowiazania-{$id}.progress")) return 0;
			DBG::log("Loop id({$id}) status({$status}) progress file exists");
			try {
				$cnt = file_get_contents("{$rootPath}/.tasks/generatePowiazania-{$id}.progress");
				$json = @json_decode($cnt, $assoc = true);
				if (null === $json && 0 !== json_last_error()) {
					throw new Exception("Parse json error for restrictions: " . json_last_error());
				}
				// $json['summary']['step']: 'initialize', 'relations', 'reports'
				// $json['summary']['step'] = 'initialize' - recache - skip
				// $json['summary']['step'] = 'relations' - szuka powiązań (@see AVG(details.progress / summary.count))
				// $json['summary']['step'] = 'reports' - generuje pliki (@see summary.created)
				/*
				if ($DBG_FAKE_ANIM && 82 == $id) { // TODO: DBG
					$json = [
						'summary' => [
							'count' => 4,
							'step' => 'relations',
						],
						'details' => [
							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'22' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'25' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
					] ];
				}
				*/
				if ($DBG_FAKE_ANIM && 80 == $id) { // TODO: DBG
					$json = [
						'summary' => [
							'count' => 4,
							'created' => 2,
							'step' => 'reports',
						],
						'details' => [
							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'22' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'25' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
					] ];
				}
				if ($DBG_FAKE_ANIM && 77 == $id) { // TODO: DBG
					$json = [
						'summary' => [
							'count' => 4,
							'created' => 2,
							'step' => 'relations',
						],
						'details' => [
							'9'  => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'19' => [ 'progress' => 1, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'22' => [ 'progress' => 0.25, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
							'25' => [ 'progress' => 0, 'results' => 123, 'elapsed' => 45.286203145981, 'estimated' => 0 ],
					] ];
				}
				DBG::log($json, 'array', "Loop id({$id}) status({$status}) progress json");

				if (empty($json['summary'])) return 0;
				if (empty($json['summary']['count'])) return 0;
				if (empty($json['summary']['step'])) return 0;
				if (empty($json['details'])) return 0;

				$listDetailsProgress = array_map(function ($detail) {
					return floatval($detail['progress']);
				}, $json['details']);

				$relationsProgress = $json['summary']['count'] > 0 ? round(floatval(array_sum($listDetailsProgress)) / floatval($json['summary']['count']), 3) : 0;
				$reportsCount = V::get('reportsCount', 0, $json['summary'], 'float');
				$reportsProgress = $reportsCount > 0 ? round(V::get('reportsCreated', 0, $json['summary'], 'float') / $reportsCount, 3) : 0;
				return round(0.5 * $relationsProgress + 0.5 * $reportsProgress, 3);
			} catch (Exception $e) {
				DBG::log($e);
			}
			return 0;
		}, $ids, array_keys($ids));
		return [ 'msg' => "DBG ids set", 'type' => "success", 'body' => [
			'ids' => $ids,
			'progress' => $progress,
			'statuses' => $statuses,
			'statusesInfo' => $statusesInfo,
		] ];
	}

}