<?php namespace AloVoice; date_default_timezone_set('Asia/Tashkent');

use AloVoice\AloVoiceConnector as ALVC;
use PAMI\Message\Event\EventMessage;
use PAMI\Message\Event\NewextenEvent;
use PAMI\Message\Event\HangupEvent;

class AloVoiceRest
{
    private $options;
    private $config;
	private $smsparts;
	private $billzconf;
	
	public function __construct($config) {
		$this->config = $config;
	}
	
	public function lasttimefile() {
		return __DIR__.'/billzlasttime';
	}
	
	public function consoleMethod($r) {
		if(!empty($_SERVER['argv'][1])){
			$runMethod = strtolower($_SERVER['argv'][1]);
			if(method_exists($this,strtolower($runMethod))){
				$rq=[];
				if(count($_SERVER['argv'])>2){
					foreach($_SERVER['argv'] as $i=>$arg){
						if($i>1){
							$v = explode("=",$arg);
							if(!empty($v[1])){ $rq[$v[0]] = $v[1]; } else { $rq[] = $v[0]; }
						}
					}
				}
				return $this->$runMethod($rq);
			}
			
		}
		
		return false;
	}
	
	public function doMethod($r) {
		if($cnslRes = $this->consoleMethod($r)){
			return $cnslRes;
		}
		if(empty($r["restmethod"])){ return false; }
		$runMethod = strtolower($r["restmethod"]);
		if(method_exists($this,strtolower($runMethod))){
			ALVC::eLog("------ AloVoiceRest :: Methos [".$runMethod."] ----------");
			return $this->$runMethod($r);
		} else {
			return array( 'error' => 'Rest Method not Found' );
		}
	}

	// private function deletePeerNumber($r){
		// $ccmd = 'delnum';
		// $params = ['PEERNUMBERS'=>['490','3030']];
		// include(dirname(dirname(dirname(__DIR__)))."/command.php");
	// }
	
	private function agentsCheckDeletedUsersNumber($r){
		return ALVC::agentsCheckDeletedUsersNumber($r);
	}
		
	private function payForDeal($r){
		$dname = 'OZONE FITNESS MCHJ';
		$searchResult = BxRest::call("crm.deal.list",[
			'ID' => 952,
		]);

		// var_dump($searchResult);
	}
	
	private function getRespNumByCallerNumber($r){
		if(empty($r[0])){ return '';}
		return $this->getInfoByNumber($r[0]);
	}
	
	public function getInfoByNumber($number){
		$crmEntitySearchResult = BxRest::call("crm.duplicate.findbycomm",array(
			'type' => "PHONE",
			'values' => [$number],
		));
		
		if(!empty($crmEntitySearchResult["result"])){
			$arEnt = json_decode($crmEntitySearchResult["result"],true);
			if(!empty($arEnt)){
				foreach($arEnt as $ent->$ids){
					$entity_type = strtolower($ent);
					$arEntity = BxRest::call("crm.".$entity_type.".get",array( 'id' => $ids[0] ));
				}
			}
			
		}
		return $crmEntitySearchResult;
	}
	
	
	private function create_conf($r) {
		$confResult = BxRest::call( 'im.conference.create', []);
		
		// $confResult = BxRest::call(
			// 'im.conference.create',
			// [
				// 'aliasData' => [
					// 'ALIAS' => "maytest2020", 
					// "LINK" => "https://4uz.bitrix24.ru/video/maytest2020"
				// ],
				// 'fields' => [
					// 'broadcast_mode' => false, 
					// 'id' => 0, 
					// 'invitation' => "#CREATOR# приглашает вас в видеоконференцию:\n#TITLE#\nПрисоединяйтесь по ссылке: #LINK#", 
					// 'password' => "", 
					// 'password_needed' => false, 
					// 'presenters' => [6], 
					// 'title' => "Maytest2021", 
					// 'users' => [6, 1], 
				// ]
			// ]
		// );
		
		ALVC::eLog($confResult,"------ AloVoiceRest :: CONFfffff Bx confResult RES: ");
		
		return $confResult;
	}
	
	private function pdu_decode($r) {
		// $pduStr = AloPdu::decode("0791999827960010040C919998777096900008125082414534021E04230440043000210020042D0442043E0020044E043D0438043A043E0434");
		$pduStr = AloPdu::decode("0791999819931020040C91999849148206000012703141701002A0D0F79CAE03C9722D65D5D992C55A3E194C06C3C16030190C668BC16E34180C16E3B544D4E210E97C569D496AEB287D56A122507388548250D0707EFC6EA75A371C880683B96030100A06B3CD68D376584EB7A6E7F430A805B2E6E5F5317A1D0689A8C521D2F9AC3A93D4D651FAAC4245A0E610A904DD702C1A0CC6023DE7741D48068ADD62A0988CE6CADD76");
		return $pduStr;
	}
	
	private function incom_sms_pdu($r) {
		$smspartsfile = dirname(dirname(dirname(__DIR__))).'/files/smsparts.json';
		ALVC::eLog($r,"------ AloVoiceRest :: incom_sms_message REQUEST:");
		$data = base64_decode($r["data"]);
		ALVC::eLog($data,"------ AloVoiceRest :: incom_sms_message DATA:");
		
		$arCmrg = explode("\n",$data);
			
		ALVC::eLog($arCmrg,"--== SMS CMGR ARR:",true);
		
		$smsPduLine = end($arCmrg);
		
		if(!empty($smsPduLine)){
			$smsparts = (file_exists($smspartsfile)) ? file_get_contents($smspartsfile) : [];
			if(empty($smsparts)){ $smsparts = []; } else { $smsparts = json_decode($smsparts,true);}
			$pduStr = AloPdu::decode($smsPduLine);
			
			ALVC::eLog($pduStr,"--== SMS pduStr ARRAYs:",true);
			
			$message = $pduStr["message"];
			$number = $pduStr["number"];
			$userDataHeader = $pduStr["userDataHeader"];
			
			if(!empty($userDataHeader)){
				//"05 00 03 A4 03 01 "
				$dHeader = str_replace(" ", '', $userDataHeader);
				$smscount = (int)substr($dHeader,-4,2);
				$smscurrent = (int)substr($dHeader,-2,2);

				ALVC::eLog($smsparts,"--== SMS PARTSSSSS[".$number."]:",true);
				
				if(!empty($smsparts[$number])) {
					$smsparts[$number] = $smsparts[$number].$message;
				}
				else {
					$smsparts[$number] = $message;
				}
				
				ALVC::eLog($smscount,"--== SMS Count:",true);
				ALVC::eLog($smscurrent,"--== SMS Current:",true);
				ALVC::eLog($smsparts[$number],"--== SMS PART NOW:",true);
				
				if($smscount == $smscurrent){
					ALVC::eLog($smsparts[$number],"--== SMS LAST PART:",true);
					ALVC::processIncomSMS($number, $smsparts[$number]);
					$smsparts[$number] = null;
					unset($smsparts[$number]);
				}
				
			}
			else{
				ALVC::processIncomSMS($number, $message);
			}
			
			file_put_contents($smspartsfile, json_encode($smsparts)); 
		}
			
		ALVC::eLog("----------------------------------============================== SMS PROCESS END:\n\n\n\n","--",true);
		return ["123"=>"123"]; // ALVC::processIncomSMS($r["number"], $r["message"]);
	}
	
	public function alovoice_incom_message($r) {
		/*
			connector
			line
			chat_id
			message_id
			message
			name
			phone //opt
			photo //opt
			files //opt
			
		*/
		// ALVC::eLog($r,"------ AloVoiceRest :: PredProcessArray OBJECT: ----------");
		
		if( empty($r["chat_id"]) || (empty($r["message"]) && empty($r["filepath"])) || empty($r["connector"]) || empty($r["line"]) ){ return false; }
		
		if(!empty($r["message_id"])){
			$arUpdMessage = [
				'im',
				'message' => [ 'id' =>  ['456'.$r['message_id'].'123'] ],
				'chat' => [
					'id' => [$r["chat_id"]],
				],
			];
			$updResult = BxRest::call(
				// 'imconnector.send.status.delivery',
				'imconnector.send.status.reading',
				[
					'CONNECTOR' => $r["connector"],
					'LINE' => $r["line"],
					'MESSAGES' => [$arUpdMessage],
				]
			);
			
			// ALVC::eLog($updResult,"------ AloVoiceRest :: IncomTGMsg Bx updResult RES: ");
		}
		
		$arMessage = [
			'user' => [
				'id' => $r["chat_id"],
				'name' => (!empty($r["name"])) ? htmlspecialchars($r['name']) : $r["chat_id"],
			],
			'message' => [
				'id' => (!empty($r["message_id"])) ? $r['message_id'] : rand(1111111111,9999999999),
				'date' => time(),
				'text' => (!empty($r['message'])) ? htmlspecialchars($r['message']) : false,
			],
			'chat' => [
				'id' => $r["chat_id"],
				//'url' => htmlspecialchars($_SERVER['HTTP_REFERER']),
			],
		];
		
		if(!empty($p["chat_title"])){
			$arMessage['chat']['name'] = $p["chat_title"];
		}
		
		if(!empty($r["phone"])){
			$arMessage["user"]["phone"] = $r["phone"];
		}
		
		if(!empty($r["photo"])){
			$arMessage["user"]["picture"] = [ 'url' => $r["phone"] ];
		}
		
		if(!empty($r["files"])){
			foreach($r["files"] as $fl ){
				$arMessage["message"]["files"][] = [ 'url' => $fl ];
			}
		}
		elseif(!empty($r["filepath"])){
			$arMessage["message"]["files"] = [];
			$fPath = str_replace($this->config["basedir"].'/',$this->config["alovoice_host"],$r["filepath"]);
			
			$arMessage["message"]["files"][] = [ 'url' => $fPath ];
		}
		
		// ALVC::eLog($arMessage,"------ AloVoiceRest :: IncomMsg OBJECT: ----------");
		
		$result = BxRest::call(
			'imconnector.send.messages',
			[
				'CONNECTOR' => $r["connector"],
				'LINE' => $r["line"],
				'MESSAGES' => [$arMessage],
			]
		);
		
		// BX24.callMethod( 'imconnector.send.messages', {
			// "LINE": 1,
			// "CONNECTOR": "tgclient998944412860",
			// "MESSAGES": [
				// {
					// 'user' : {
						// 'id' : "124987160",
						// 'name' : "Kulya_124987160",
						// 'phone' : "998994412860",
					// },
					// 'message' : {
						// 'id' : 2547263547265,
						// 'date' : 1642485811,
						// 'text' : "Пробнобное сообщение",
					// },
					// 'chat' : {
						// 'id' : "124987160",
						// 'name' : "Kulya_124987160",
						// //'url' => htmlspecialchars($_SERVER['HTTP_REFERER']),
					// },
				// }
			// ]
		// },function(result){
			// console.log(result);
		// });
		
		// BX24.callMethod( 'imconnector.send.messages', {
			// "LINE": 1,
			// "CONNECTOR": "tgclient998944412860",
			// "MESSAGES": [
				// {
					// 'user' : {
						// 'id' : "124987168",
						// 'name' : "DANIIL NAGAY KAMILEVICH",
					// },
					// 'message' : {
						// 'id' : 2547263547265,
						// 'date' : 1642485911,
						// 'text' : "Пробнобное сообщение",
					// },
					// 'chat' : {
						// 'id' : "124987168",
						// 'name' : "DANIIL NAGAY KAMILEVICH",
						// //'url' => htmlspecialchars($_SERVER['HTTP_REFERER']),
					// },
				// }
			// ]
		// },function(result){
			// console.log(result);
		// });



		// ALVC::eLog($result,"------ AloVoiceRest :: IncomMsg Bx RES  ----------");
		// ALVC::eLog($this->config["basedir"],"------ AloVoiceRest :: IncomMsg BaseDIR  ----------");

		return array(
			'chat' => $r["chat_id"],
			'req' => $r,
			'result' => $result
			
		);
	}

	private function savealovoicesettings($r=false) {
		$r["restmethod"] = null;
		unset($r["restmethod"]);
		
		foreach($r as $sk=>$sv){
			$this->config[$sk] = $sv;
		}
		
		if($nvals = ALVC::setConfigValues($this->config)){
			return ["result"=>"ok","data"=>$nvals];
		}
		else{
			return ["result"=>"error"];
		}
	}
	
	private function bx_process_product($data=[],$full=false) {
		
		$datasss = json_decode('{
				"ID": 1261574,
				"name": "*Tahorat va namoz",
				"sku": "Q001",
				"barCode": "9789943542556",
				"price": 23000,
				"priceUSD": 23000,
				"discountAmount": 0,
				"qty": 15,
				"properties": {
					"BRAND": "",
					"CATEGORY": "Kitob",
					"COLLECTION": "",
					"COLOR": "",
					"DESCRIPTION": "Tahorat lug`atda poklikdir. Poklik – inson tabiatan rag`bat qiladigan go`zal sifatlarning biridir. Islom dini insonlarni poklikka targ`ib qiladi va o`zlarini pok tutuvchilarni maqtaydi. \"Albatta Alloh tavba qilguvchilarni va o`zlarini mudom pok tutguvchilarni sevadi\" (Baqara - 222). Hadisi sharifda Rasululloh sollallohu alayhi vasallam: \"poklik iymonning yarmidir\", deb aytganlar. (Buxoriy rivoyati).",
					"GENDER": "",
					"SEASON": "",
					"SIZE": "14*21",
					"SUB_CATEGORY": "Foydali kitoblar",
					"АВТОР": "",
					"ВЕС": "220gr",
					"ЖАНР": "",
					"ИЗДАТЕЛЬСТВО": "G`afur G`ulom nashryot-matbaa ijodiy uyi",
					"КОЛИЧЕСТВО_СТРАНИЦ": "185",
					"НАПРАВЛЕНИЕ": "Kitoblar",
					"ПОДКАТЕГОРИЯ2": "Din ahkomlari (namoz, zakot..)",
					"ПОСТАВЩИК": "Islomaka",
					"ТИП_ОБЛОЖКИ": "Yumshoq"
				},
				"offices": [
					{
						"officeID": 1347,
						"officeName": "Qamar Kitoblar A.Navoiy",
						"price": 23000,
						"priceUSD": 23000,
						"discountAmount": 0,
						"qty": 15
					}
				],
				"imageUrls": [
					{
						"url": "https://app.billz.uz/fileupload/products/2021/02/25/901F535D975D24B3334CC40D4DC62922_022521120712_square.jpeg"
					}
				],
				"totalRows": 990
			}',1);
		
		
		if(empty($data)){
			return false;
		}
		
		BillzRest::setLog($data, "Processing Product:");
		
		$conf = self::get_billzconf();
		
		$priceType = 2;
		$currency = 'UZS';
		$result = false;
		
		if(!empty($conf["bx_catalog_id"])){
			$arProduct = [];
			
			$xmlId = $data["ID"];
				
			$select = ($full) ? [ 'id', 'iblockId', '*' ] : ['id', 'iblockId'];
			
			$result = BxRest::call('catalog.product.list',[
				"filter" => [
					"xmlId" => $xmlId,
					"iblockId" => $conf["bx_catalog_id"],
				],
				"select" => $select
			]);
			
			if(!empty($result["result"]["products"])){
				$arProduct = $result["result"]["products"][0];
			}

			
				$arNewProductParams = [
					"iblockId" => $conf["bx_catalog_id"],
					"name" => $data["name"],
					"code" => $this->translit($data["name"]),
					"xmlId" => $xmlId,
					"iblockSectionId" => (!empty($data["sid"])) ? $data["sid"] : 0,
					"quantity" => (!empty($data["qty"])) ? $data["qty"] : 0,
					"quantityTrace" => 'N',
				];
				
				// if(!empty($data["price"])){
					// $arNewProductParams["priceType"] = $priceType;
					// $arNewProductParams["purchasingCurrency"] = $currency;
					// $arNewProductParams["purchasingPrice"] = $data["price"];
				// }
					
				if(!empty($conf["bxbillzfields"])){
					foreach($conf["bxbillzfields"] as $bxf=>$blzf){
						$bxFld = substr($bxf,9);
						if(substr($bxFld,0,2)=="F_"){
							if(substr($blzf,0,10)=="_imageUrls" && !empty($data["imageUrls"][0]["url"])){
								$purl = str_replace("_square","",$data["imageUrls"][0]["url"]);

								$arImage = $this->get_image_by_url($purl);
								$bxFld = substr($bxFld,2);
								$blzVal = [ "value" => [ "fileData" => [
									$arImage["name"],
									$arImage["base64"]
								]]];
							}
							else {
								continue; //todo process other files
							}
						}
						elseif(substr($blzf,0,11)=="properties_"){
							$blzSubFldCode = substr($blzf,11);
							$blzVal = (!empty($data["properties"][$blzSubFldCode])) ? $data["properties"][$blzSubFldCode] : false;
						}
						else {
							$blzVal = $data[$blzf];
						}
						
						if( $bxFld != "ID" && $bxFld != "xmlId" && $bxFld != "quantity" && !empty($blzVal) ){
							$arNewProductParams[$bxFld] = $blzVal;
						}
					}
				}
				
				$section_id = (!empty($data["properties"]["CATEGORY"])) ? $this->process_product_section($data["properties"]["CATEGORY"]) : false;
				
				if(!empty($data["properties"]["SUB_CATEGORY"])){
					$section_id = $this->process_product_section($data["properties"]["SUB_CATEGORY"],$section_id);
				}
				if(!empty($data["properties"]["ПОДКАТЕГОРИЯ2"])){
					$section_id = $this->process_product_section($data["properties"]["ПОДКАТЕГОРИЯ2"],$section_id);
				}
				
				$arNewProductParams["iblockSectionId"] = (!empty($section_id)) ? $section_id : 0;
				
				BillzRest::setLog($arNewProductParams);
				
				if(empty($arProduct)){
					$arAddRes = BxRest::call('catalog.product.add',["fields"=>$arNewProductParams]);
					if(!empty($arAddRes["result"]["element"])){
						$arProduct = $arAddRes["result"]["element"];
					}
				}
				else {
					$arUpdRes = BxRest::call('catalog.product.update',["id"=>$arProduct["id"] ,"fields"=>$arNewProductParams]);
					if(!empty($arUpdRes["result"]["element"])){
						$arProduct = $arUpdRes["result"]["element"];
					}
				}
								
				if(!empty($arProduct["id"]) && !empty($data["price"])){
					$arProdPrice = [
						"product" => [
							"id" => $arProduct["id"],
							"prices" => [
								[
									"catalogGroupId" => $priceType,
									"currency" => $currency,
									"price" => (!empty($data["price"])) ? $data["price"] : $data["retailPriceUzs"],
								]
							]
						]
					];
					
					$priceRes = BxRest::call('catalog.price.modify',["fields"=>$arProdPrice]);

				}
			
		}
		
		return $arProduct;
	}
	
	private function get_image_by_url($url=false) {
		// $url = "https://app.billz.uz/fileupload/products/2021/02/25/901F535D975D24B3334CC40D4DC62922_022521120712_square.jpeg";
		if(empty($url)){
			return false;
		}
		$arInfo = pathinfo($url);
		$data = base64_encode(file_get_contents($url));

		$return = [
			'name' => $arInfo["basename"],
			'base64' => $data,
			'extension' => $arInfo["extension"],
		];
		
		return $return;
	}
	
	// private function billz_products_all_synch($r=false) {
		// $tms["0_begin"] = time();
		// $return = ["result"=>false];
		// $date = "2017-01-01T00:00:00Z";
		// echo "\nBegin loading billz products [date_from:".$date."]...";
		
		// $allProds = BillzRest::getProducts($date);
		// echo "\n Billz products loaded done!";
		// if(!empty($allProds["answer"]["result"])){
			// echo "\n Billz begin product saving...";
			// $tms["1_saving"] = time();
			// $jsProducts = json_encode($allProds);
			// $return["count"] = count($allProds["answer"]["result"]);
			// $return["result"] = file_put_contents(__DIR__."/billz_allproducts.json",$jsProducts);
			// $tms["2_saved"] = time();
			// echo "\n Billz products saved!";
		// }
		
		// $tms["3_end"] = time();
		// $tms["9_ALL"] = $tms["3_end"]-$tms["0_begin"];
		
		// echo "\n DONE!!";
		// $return["times"] = $tms;
		// return $return;
	// }
	
	private function get_byinn($r=false) {
		return ALVC::requesTaxInn($r["inn"]);
	}
	
	private function billz_catalog_infos_synch($r=false) {

		$tms["0_begin"] = time();
		
		$newProductsCnt = 0;
		$arOffices = [];
		
		$arAllProperties = [
			"ID" => 'ID', //123123123,
			"name" => 'Наименование', //"*Tahorat va namoz",
			"sku" => 'Артикуль', //"Q001",
			"barCode" => 'Баркод', //"9789943542556",
			"price" => 'Цена', //23000,
			"priceUSD" => 'ЦенаUSD', //23000,
			"discountAmount" => 'Скидка', //0,
			"qty" => 'Количество', //15,
			".imageUrls" => 'Изображение', //15,  [url]
			".offices" => 'В складах', //15, [officeID,officeName,qty]
			/*{
				"officeID": 1347,
				"officeName" => "Qamar Kitoblar A.Navoiy",
				"price": 23000,
				"priceUSD": 23000,
				"discountAmount": 0,
				"qty": 15
			}*/

		];
		
		$sdata = self::get_products_last_update(); //"2017-01-01T00:00:00Z";
		
		echo "Загрузка изменения из Billz c: ".$sdata.":...";
		
		$first = BillzRest::getProducts($sdata);
		

		if(!empty($first["answer"]["result"])){
			if(!empty($first["answer"]["result"][0]["properties"])){
				foreach( $first["answer"]["result"][0]["properties"] as $prk=>$prp){
					$arAllProperties["properties_".$prk] = $prk;
				}
			}
			
			$prdAllCnd = count($first["answer"]["result"]);
			echo "Загружено ".$prdAllCnd." товаров!";
			
			echo "Импортирования в Тарговый каталог...";
			
			foreach($first["answer"]["result"] as $prd){
				$this->bx_process_product($prd);
				
				$newProductsCnt++;

				$percStp = round(($newProductsCnt/$prdAllCnd)*100);
				$nowt = time();
				$raznt = $nowt-$tms["0_begin"];
				$remainTime = 0;
				
				if($raznt!=0 && $percStp!=0) { $remainTime = round(($raznt/$percStp)*100); }

				echo "\r Импортировано: \033[32m".$percStp."% \033[0m [\033[36m".$newProductsCnt."\033[0m/".$prdAllCnd."] [Прошло: ".$raznt." сек.]...";
			}
			self::set_products_last_update();
			
			// foreach($first["answer"]["result"] as $prd){
				// $prid = false;
				// $sid = false;
				// if(!empty($prd["properties"]["CATEGORY"])){
					// $rpid = $this->process_product_section($prd["properties"]["CATEGORY"]);
					// // if(!in_array($prd["properties"]["CATEGORY"],$arSections)){
						// // $arSections[] = $prd["properties"]["CATEGORY"];
					// // }
				// }
				
				// if(!empty($prd["properties"]["SUB_CATEGORY"])){
					// $sid = $this->process_product_section($prd["properties"]["SUB_CATEGORY"],$rpid);
					// // if(!in_array($prd["properties"]["SUB_CATEGORY"],$arSubSections)){
						// // $arSubSections[] = $prd["properties"]["SUB_CATEGORY"];
					// // }
				// }
				
				// if(!empty($prd["properties"]["ПОДКАТЕГОРИЯ2"])){
					// $this->process_product_section($prd["properties"]["SUB_CATEGORY"],$sid);
					// // if(!in_array($prd["properties"]["ПОДКАТЕГОРИЯ2"],$arTrdSections)){
						// // $arTrdSections[] = $prd["properties"]["ПОДКАТЕГОРИЯ2"];
					// // }
				// }
				
				// // process offices
				// if(!empty($prd["offices"])){
					// foreach($prd["offices"] as $ofc){
						// if(!empty($ofc["officeID"]) && !empty($ofc["officeName"]) && empty($arOffices[$ofc["officeID"]])){
							// $arOffices[$ofc["officeID"]] = $ofc["officeName"];
						// }
					// }
				// }
				
			// }
		}
		
		$arConf = self::get_billzconf();
		$arConf["billz_productfields"] = $arAllProperties;
		self::save_billzconf(["conf"=>$arConf]);
		
		$now = time();
		$alltime = $now-$tms["0_begin"];
				
		$return = ["newproducts"=>$newProductsCnt,"billzprops"=>count($arAllProperties), "time"=>$alltime."sec."]; //"categories"=>$arSections, "subcats"=>$arSubSections, "trdcats"=>$arTrdSections, "offices"=>$arOffices, 
		ALVC::eLog($return,"------ AloVoiceRest :: billz_catalog_infos_synch CRON Done!");
		
		return $return;
	}
	
	private function process_orders_synch($p=false) {
		$officeId = 1347;
		$sFilter = [ "payed" => "Y" ];
		
		if(!empty($p["order_id"])){
			$sFilter["id"] = $p["order_id"];
		}
		else {
			$orders_last_update = self::get_orders_last_update(); //"2021-12-10T18:46:50+05:00";
			$sFilter[">dateUpdate"] = $orders_last_update; //"2021-12-10T18:46:50+05:00";
		}

		$orderSearchParams = [
			"select"=>["id"], //,"price","accountNumber","dateUpdate"],
			"filter"=>$sFilter
		];
		ALVC::eLog($orderSearchParams,"------ AloVoiceRest :: Order Search PARAMS:");
		
		$res = BxRest::call("sale.order.list",$orderSearchParams);
		
		$arResOrders = [];
		if(!empty($res["result"]["orders"])){
			foreach($res["result"]["orders"] as $order){
				$arProducts = self::get_bx_order_products($order["id"]);
				if(empty($arProducts)){
					continue;
				}
				
				$arOrderProducts = [];
				foreach($arProducts as $oprd){
					$arPrdRes = BxRest::call('catalog.product.get',["id"=>$oprd["productId"]]);
					if(!empty($arPrdRes["result"]["product"])){
						$xmlId = $arPrdRes["result"]["product"]["xmlId"];
					}
					$arOrderProducts[] = [
						"office_id" => $officeId,
						"id" => (int)$oprd["productId"],
						"billz_id" => (int)$xmlId,
						"quantity" => (int)$oprd["quantity"],
						"price" => (int)$oprd["price"],
						"discount" =>(int)$oprd["discountPrice"]
					];
				}
				
				$arOrderParams = [
					"order_id" => $order["id"],
					"paytype" => "payme",
					// "datePaid" => "2018-03-27T09:19:25.667Z",
					"products" => $arOrderProducts
					
				];
				
				$arResOrders[] = BillzRest::createOrder($arOrderParams);

				$arOrder = self::process_order_client($order["id"]);
			}
			
			self::set_orders_last_update();
		} 
		
		$ordCount = count($arResOrders);
		
		ALVC::eLog(["orders"=>$ordCount],"------ AloVoiceRest :: process_orders_synch From:[".$orders_last_update."] CRON Done!");
		
		return $arResOrders	;
		
		// if(!empty($res["result"]["sections"])){
			// $result = $res["result"]["sections"][0]["id"];
		// }
		
	}
	
	private function process_order_client($id=false) {
		if(empty($id)){ $id = 56; }
		$res = BxRest::call("sale.order.get",[ "id" => $id ]);
		
		ALVC::eLog($res["result"],"------ Billz :: Order RES:");
		
		if(empty($res["result"]["order"]['clients'])){ return false; }
		$client = $res["result"]["order"]['clients'][0];
		$clientId = $client["entityId"];
		$clientTypeId = $client["entityTypeId"];
		if($clientTypeId==3){
			$resCont = BxRest::call("crm.contact.get",[ "id" => $clientId ]);
			ALVC::eLog($resCont["result"],"------ Billz :: Client(contact) RES:");
			
			if(empty($resCont["result"])){
				return false;
			}
			$contact = $resCont["result"];
			
			if(empty($contact["UF_CRM_1644411792448"]) && !empty($contact["PHONE"][0]["VALUE"])){
				$arClientParams = [ "phone" => $contact["PHONE"][0]["VALUE"] ];
				if(!empty( $contact["NAME"] )){
					$arClientParams['firstName'] = $contact["NAME"];
				}
				if(!empty( $contact["SECOND_NAME"] )){
					$arClientParams['lastName'] = $contact["SECOND_NAME"];
				}
				if(!empty( $contact["BIRTHDATE"] )){
					$arClientParams['birthDate'] = $contact["BIRTHDATE"];
				}
				
				ALVC::eLog($arClientParams,"------ Billz :: Client Add PARAMS:");
				
				$clientAddRes = BillzRest::createClient($arClientParams);
				ALVC::eLog($clientAddRes,"------ Billz :: Client Add RES:");
			}
		}
		
	}
	
	private function get_bx_order_products($id=false) {
		// if(empty($id)){ return false; }
		$res = BxRest::call("sale.basketItem.list",[
			// "select"=>["productId","quantity","price","name","productXmlId"],
			"filter"=>[ "orderId" => $id ]
		]);
		return (!empty($res["result"]["basketItems"])) ? $res["result"]["basketItems"] : [];
	}
	
	private function set_orders_last_update() {
		$ordTimeFile = __DIR__."/orderlasttime";
		$ldatetime = date("c");
		$resSet = file_put_contents($ordTimeFile,$ldatetime);
		ALVC::eLog($resSet,"------ Billz :: Set last UPD time:[".$ordTimeFile.' -->> '.$ldatetime."]");
	}
	private function get_orders_last_update() {
		$ordTimeFile = __DIR__."/orderlasttime";
		$lastDateTime = "2021-12-10T10:10:10+05:00";
		if(file_exists($ordTimeFile)){
			$strTime = file_get_contents($ordTimeFile);
			if(!empty($strTime)){
				$lastDateTime = $strTime;
			}
		}
		return $lastDateTime;
	}
	
	private function get_products_last_update() {
		$timeFile = self::lasttimefile();
		$lastDateTime = "2018-01-01T00:00:00Z";
		if(file_exists($timeFile)){
			$strTime = file_get_contents($timeFile);
			if(!empty($strTime)){
				$lastDateTime = $strTime;
			}
		}
		return $lastDateTime;
	}
	private function set_products_last_update() {
		$ldatetime = date("Y-m-d")."T".date("H:i:s")."Z";
		$timeFile = self::lasttimefile();
		file_put_contents($timeFile,$ldatetime);
	}
	
	private function process_product_section($name='',$parent_id=false) {
		$sid = false;
		if(!$sid = $this->bx_get_product_section($name)){
			$sid = $this->bx_add_product_section($name,$parent_id);
		}
		
		return $sid;
	}
	
	private function bx_get_product_section($name='') {
		$conf = self::get_billzconf();
		$result = false;
		if(!empty($name) && !empty($conf["bx_catalog_id"])){
			$res = BxRest::call("catalog.section.list",[
				// "select"=>[],
				"filter"=>[
					"iblockId" => $conf["bx_catalog_id"],
					"name" => $name
				]
			]);
			
			if(!empty($res["result"]["sections"])){
				$result = $res["result"]["sections"][0]["id"];
			}
		}
		
		return $result;
	}
	
	private function bx_add_product_section($name,$parent_id=false) {
		if(empty($name)){ return false; }
		$conf = self::get_billzconf();
		$result = false;
		if(!empty($conf["bx_catalog_id"])){
			$addParams = [
				"iblockId" => $conf["bx_catalog_id"],
				"name" => $name,
				"code" => self::translit($name)
			];
			if(!empty($parent_id) && is_numeric($parent_id)){
				$addParams["iblockSectionId"] = $parent_id;
			}
			$res = BxRest::call("catalog.section.add",["fields"=>$addParams]);
			if(!empty($res["result"]["section"]["id"])){
				$result = $res["result"]["section"]["id"];
			}
		}
		
		return $result;
	}
	

				
	private function create_billz_order($r=false) {
		$officeId = 1347;
		$arOrderProducts = [
			[
				"office_id" => $officeId,
				"id" => 6154,
				"billz_id" => 2641209,
				"quantity" => 2,
				"price" => 1200,
				"discount" =>180
			]
		];
		
		$arOrderParams = [
			"order_id" => "123123123",
			"paytype" => "payme",
			// "datePaid" => "2018-03-27T09:19:25.667Z",
			"products" => $arOrderProducts
			
		];
		
		$createRes = BillzRest::createOrder($arOrderParams);
		// answer {
			// "settings": {
				// "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJxYW0uYml0cml4MjQucnUiLCJpYXQiOjE2MzkxMzU5NTQsImV4cCI6MTYzOTI4NTk1NCwic3ViIjoicWFtYXIuYml0cml4MjQifQ.N1I8rP3admsR_dGIHvYyAPcgu64wPoDTAaI9XHIfCyc",
				// "url": "https://api.billz.uz/v4/"
			// },
			// "params": "{\"jsonrpc\":\"2.0\",\"method\":\"orders.create\",\"params\":{\"subTotalPrice\":0,\"orderID\":\"123123123\",\"dateCreated\":\"2021-12-10T16:32:34Z\",\"products\":[{\"billzOfficeID\":1347,\"billzProductID\":2641209,\"productID\":6154,\"name\":\"Ilm olish sirlari\",\"barCode\":\"9789943510470\",\"sku\":\"VIP756\",\"qty\":2,\"subTotalPrice\":1200,\"discountAmount\":180,\"totalPrice\":1020}],\"paymentMethod\":\"payme\",\"totalPrice\":0}}",
			// "answer": {
				// "jsonrpc": "2.0",
				// "error": {
					// "code": -32601,
					// "message": "Method not found"
				// }
			// }
		// }
		
		return $createRes;
	}
	
	private function test($r=false) {
		$conf = self::get_billzconf();
		return BxRest::call("catalog.product.getFieldsByFilter",[
			"filter" => [
				"iblockId" => $conf["bx_catalog_id"],
				"productType" => 1
			]
		]);
			
		return $this->bx_add_product_section($r[0]);
	}
	
	private function translit($t=false) {
		 $cyr  = array('а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п','р','с','т','у', 
            'ф','х','ц','ч','ш','щ','ъ', 'ы','ь', 'э', 'ю','я',
            'А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У',
            'Ф','Х','Ц','Ч','Ш','Щ','Ъ', 'Ы','Ь', 'Э', 'Ю','Я' );
		$lat = array( 'a','b','v','g','d','e','e','zh','z','i','y','k','l','m','n','o','p','r','s','t','u',
            'f' ,'h' ,'ts' ,'ch','sh' ,'sht' ,'i', 'y', 'y', 'e' ,'yu' ,'ya','A','B','V','G','D','E','E','Zh',
            'Z','I','Y','K','L','M','N','O','P','R','S','T','U',
            'F' ,'H' ,'Ts' ,'Ch','Sh' ,'Sht' ,'I' ,'Y' ,'Y', 'E', 'Yu' ,'Ya' );

		$textlat = str_replace($cyr, $lat, $t);
		// $textlat = str_replace($lat, $cyr, $textlat);
		$textlat = str_replace(" ", "_", $textlat);
		
		return $textlat;
	}
	
	private function billz_catalog_infos_synch_OLD($r=false) {
		$p=1;
		$ps=10;
		$loadedCnt = 0;
		$bxlang = 'Ru';
		$tms["0_begin"] = time();
		// $arAllBrands = [];
		$arAllCategories = [];
		
		$arAllProperties = [
			'barCode' => 'Баркод',
			'counts_active' => 'Количество',
			'id' => 'ID',
			'name' => 'Наименование',
			'officeId' => 'Номер магазина',
			'officeName' => 'Магазин',
			'prices_retailPriceUzs' => 'Цена',
			'vendorCode' => 'Артикуль',
		];
		
		$first = BillzRest::getCatalog();
		if(!empty($first["answer"]["result"]["data"]["total"])){
			$totalCnt = $first["answer"]["result"]["data"]["total"];
			$pageCnt = round($totalCnt/$ps);
		}
		
		while($loadedCnt<$totalCnt){
			$loads = BillzRest::getCatalog($p,10);
			
			if(!empty($loads["answer"]["result"]["data"]["results"])){
				foreach($loads["answer"]["result"]["data"]["results"] as $prd){
					
					// if(!empty($prd["properties"]["brand"])){
						// if(!in_array($prd["properties"]["brand"]["value"],$arAllBrands)){
							// $arAllBrands[] = $prd["properties"]["brand"]["value"];
						// }
					// }
					if(!empty($prd["properties"]["category"])){
						if(!in_array($prd["properties"]["category"]["value"],$arAllCategories)){
							$arAllCategories[] = $prd["properties"]["category"]["value"];
						}
					}
					
					if(!empty($prd["properties"])){
						foreach( $prd["properties"] as $prk=>$prp){
							$arAllProperties["properties_".$prk] = $prp["caption".$bxlang];
						}
					}
					$loadedCnt++;
					
					$percStp = round(($loadedCnt/$totalCnt)*100);
					$prpCnt = count($arAllProperties);
					$catCnt = count($arAllCategories);
					
					$nowt = time();
					$raznt = $nowt-$tms["0_begin"];
					$remainTime = 0;
					if($raznt!=0 && $percStp!=0) { $remainTime = round(($raznt/$percStp)*100); }
					//".$prd["name"]."
					echo "\r Updating: \033[32m".$percStp."% \033[0m [\033[36m".$loadedCnt."\033[0m/".$totalCnt."] [PropsCnt:".$prpCnt."] [NowPrd: \033[33m".$prd["id"]."\033[0m ] [Times:".$raznt."/".$remainTime."] [Cats:".$catCnt."] completed...";
				}
			}
			$p++;
		}
		// {
			// "count": 3122,
			// "billzprops": {
				// "barCode": "Баркод",
				// "counts.active": "Количество",
				// "id": "ID",
				// "name": "Наименование",
				// "officeId": "Номер магазина",
				// "officeName": "Магазин",
				// "prices.retailPriceUzs": "Цена",
				// "vendorCode": "Код производителя",
				// "properties.subCategory": "Подкатегория",
				// "properties.category": "Категория",
				// "properties.brand": "Бренд",
				// "properties.description": "Описание",
				// "properties.size": "Размер",
				// "properties.collection": "Коллекция",
				// "properties.season": "Сезон"
			// },
			// "alltime": 336
		// }
		// $prCount = count($first["answer"]["result"]["data"]["results"]);
		// var_dump($first["answer"]["result"]["data"]["results"]);
		$alltime = time()-$tms["0_begin"];
		
		$arConf = self::get_billzconf();
		$arConf["billz_productfields"] = $arAllProperties;
		self::save_billzconf(["conf"=>$arConf]);
		
		$return = ["count" => $totalCnt, "billzprops"=>count($arAllProperties), "alltime"=>$alltime];
		ALVC::eLog($return,"------ AloVoiceRest :: billz_catalog_infos_synch CRON Done!");
	}
	
	private function billz_load_product($r=false) {
		$products = BillzRest::getProducts();
		
		return $products;
	}
	
	private function billz_catalog_synch($r=false) {
		$p=1;
		$stp = (!empty($r["step"])) ? $r["step"] : 1;
		
		$loadedCnt = 0;
		$first = BillzRest::getCatalog($stp,2);
		if(!empty($first["answer"]["result"]["data"]["total"])){
			$totalCnt = $first["answer"]["result"]["data"]["total"];
		}
		
		return $first["answer"]["result"];
		// while($loadedCnt < $totalCnt){
			// $res = BillzRest::getCatalog();
		// }
		// if(!empty($res["answer"]["result"]["data"]["results"])){
			// foreach( $res["answer"]["result"]["data"]["results"] as $pr ){
				
			// }
		// }
	}
	
	private function bx_catalog_products_fields($r=false) {
		
		$conf = self::get_billzconf();

		// $billz_productfields = (!empty($conf["billz_productfields"])) ? $conf["billz_productfields"] : [];
		// if(!empty($bpfs)) {
			// foreach($bpfs as $bzfld=>$bxfld){
				// $bxbillzflds[$bxfld] = $bzfld;
			// }
		// }
		
		$result = [];
		if(!empty($conf["bx_catalog_id"])){
			$result["bx_catalog_id"] = $conf["bx_catalog_id"];
			$res = BxRest::call("catalog.product.getFieldsByFilter",[
				"filter" => [
					"iblockId" => $conf["bx_catalog_id"],
					"productType" => 1
				]
			]);
			
			$arFileds = [];
			if(!empty($res["result"]["product"])){
				foreach($res["result"]["product"] as $pfk=>$prf){
					
					$type = (!empty($prf["propertyType"])) ? $prf["propertyType"] : $prf["type"];
					if( ($type=="S" || $type=="F" || $type=="string") && ($pfk != "code") && ($pfk != "purchasingCurrency") && ($pfk != "purchasingPrice") && ($pfk != "previewTextType") && ($pfk != "detailTextType")){
						
						if($type=="F"){
							$pfk = "F_".$pfk;
						}
						
						$arFileds[$pfk] = [
							'code' => $pfk,
							'title' => $prf["name"],
						];
						
						if(!empty($conf["bxbillzfields"]["bz_field_".$pfk])){
							$arFileds[$pfk]["billz_field"] = $conf["bxbillzfields"]["bz_field_".$pfk];
						}
					}
				}
				
				return $arFileds;
			}
		}
		
		return [];
	}
	
	private function bx_catalogs_list($r=false) {
		$res = BxRest::call("catalog.catalog.list",[]);
		$conf = self::get_billzconf();
		$arCatalogs = [];
		if(!empty($res["result"]["catalogs"])){
			foreach( $res["result"]["catalogs"] as $cat){
				$arCatalogs[$cat['id']] = $cat['name'];
			}
		}
		
		return ["conf"=>$conf, "list"=>$arCatalogs];
	}
	
	private function save_billzconf($r=false) {
		$arConf = (!empty($r["conf"])) ? $r["conf"] : [];
		if(!empty($arConf)){
			$jsConf = json_encode($arConf);
			return file_put_contents(__DIR__."/billz.conf",$jsConf);
		}
		return false;
	}
	
	private function get_billzconf() {

		$arConf = [];

		if(!empty($this->billzconf)){
			$arConf = $this->billzconf;
		}
		elseif(file_exists(__DIR__."/billz.conf")){
			$jsConf = file_get_contents(__DIR__."/billz.conf");
			$arConf = $this->billzconf = json_decode($jsConf,1);
		}

		return $arConf;
	}
	
	private function get_synchstatus($all,$cnt) {
		$jsInfo = file_get_contents(__DIR__."/updstatus");
		return json_decode($jsInfo,1);
	}
	
	private function upd_synchstatus($all,$cnt) {
		$arInfo = ["all"=>$all,"cnt"=>$cnt];
		$jsInfo = json_encode($arInfo);
		file_put_contents(__DIR__."/updstatus" , $jsInfo);
	}
	
	private function alovoice_billzsettings($r=false) {
		$r["restmethod"] = null;
		unset($r["restmethod"]);
		// $res = BillzRest::getProducts();
		$res = BillzRest::getCatalog();
		
		return $res;
	}
	
	private function savealovoice_crmsettings($r=false) {
		// foreach($r as $sk=>$sv){
			// $this->config[$sk] = $sv;
		// }
		$r["restmethod"] = null;
		unset($r["restmethod"]);
		
		// $arrCrmFileds = ALVC::getCrmFileds();
		
		// if(!empty($arrCrmFileds)){
			// foreach($arrCrmFileds as $crmkey=>$crmconfs){
				// if(!empty($r[$crmkey])){
					// $arrCrmFileds[$crmkey] = $r[$crmkey];
				// }
			// }
		// }
		
		// $arrCrmFileds["company_requesits_template"] = $r["company_requesits_template"];
		// $arrCrmFileds["contact_requesits_template"] = $r["contact_requesits_template"];
		
		ALVC::saveCrmFileds($r);
		return ["result"=>"ok","data"=>$r];
	}
	
	private function alovoice_crmsettings($r=false) {
		$arTaxFileds = ALVC::innTaxFields();
		$arFileds = []; //ALVC::innFields();
		$arFizFileds = ALVC::innFields(true);
		
		
		$arrCrmEntities = ALVC::crm_entites();
		$arrCrmFileds = ALVC::getCrmFileds();
		
		// $arrCrmFileds["innfields"] = array_merge($arFileds,$arTaxFileds);
		$arrCrmFileds["innfields"] = $arTaxFileds;
		$arrCrmFileds["innfizfields"] = $arFizFileds;
		
		$arrCrmFileds["crmupdfileds"] = [];
	
		$arrCrmFileds["crmentitytypes"] = $arrCrmEntities;
		foreach($arrCrmEntities as $entity=>$title){
			$arrCrmFileds["crmupdfileds"][$entity] = $arrCrmFileds[$entity.'_fields'];
		}
		return $arrCrmFileds;
	}
	
	private function alovoice_settings($r=false) {
		return $this->config; 
		// array(
			// 'host' => $this->config["asterisk_host"],
			// 'port' => $this->config["asterisk_port"],
			// 'username' => $this->config["asterisk_username"],
			// 'secret' => $this->config["asterisk_secret"]
		// );
	}
	
	private function alovoice_tasktest($data) {
		$arResults = BxRest::call('tasks.task.add', array(
			"fields" => array(
				"TITLE" => "Test123",
				"RESPONSIBLE_ID" => 6,
				"DESCRIPTION" => "Post: 18.05.21->20208000200610740001<-'Mondelux Kitchen'MCH-1 400 000.00 (00668 Za programmnoe obespechenie soglasno dogovora NSOFT 2021/01-, Ost: 6 264 962.66;",
				'GROUP_ID' => 40,
			)
		));
		return $arResults;
		$ttt = "Post: 18.05.21->20208000200610740001<-'Mondelux Kitchen'MCH-1 400 000.00 (00668 Za programmnoe obespechenie soglasno dogovora NSOFT 2021/01-, Ost: 6 264 962.66;";
		preg_match("/Ost:([0-9\s\.]{2,})/",$ttt,$ostMtchs);
		return $ostMtchs;
	}
	
	public function alovoice_taskadd($data) {
		$configs = AloVoiceConnector::getConfigs();
		$respID = 8;
		$grpID = 40;
		if(substr($data,0,5) == 'Rasx:'){
			$taskTitle = 'Расход '.date("d.m.Y");
		} 
		elseif(substr($data,0,5) == 'Post:'){
			$taskTitle = 'Поступление оплаты '.date("d.m.Y");
		}else{
			$taskTitle = 'Обработка смс '.date("d.m.Y");
		}
		
		$ostSumm = '';
		preg_match("/Ost:([0-9\s\.]{2,})/",$data,$ostMtchs);
		if(!empty($ostMtchs[1])){ $ostSumm = "Ost: ".$ostMtchs[1]; }
		
		$arResults = BxRest::call('tasks.task.add', array(
			"fields" => array(
				"TITLE" => $taskTitle.$ostSumm,
				"RESPONSIBLE_ID" => $respID,
				"DESCRIPTION" => $data, //"Post: 18.05.21->20208000200610740001<-'Mondelux Kitchen'MCH-1 400 000.00 (00668 Za programmnoe obespechenie soglasno dogovora NSOFT 2021/01-, Ost: 6 264 962.66;",
				'GROUP_ID' => $grpID,
			)
		));
		
		$tskLink = '';
		
		if(!empty($arResults["result"]["task"]["id"])){
			$tskLink = 'https://'.$configs['bitrix_domain'].'/workgroups/group/'.$arResults["result"]["task"]["groupId"].'/tasks/task/view/'.$arResults["result"]["task"]["id"].'/';
		}
		return $tskLink;
	}
	
	private function alovoice_tests($r=false) {
		$arResults = BxRest::call('im.message.add', array(
			// "DIALOG_ID" => 'imol|alotg|2|$01000000182773071d3a41e62f1c9b0b|178',
			"DIALOG_ID" => 'chat3138',
			// "USER_ID" => 6,
			"MESSAGE" => "TestFrom Console msg_456",
			'SYSTEM' => 'N',
			'ATTACH' => '',
			'URL_PREVIEW' => 'Y',
			'KEYBOARD' => '',
			'MENU' => ''
		));
		
		// $arResults = BxRest::call('im.chat.get', array(
			// "ENTITY_TYPE" => 'LINES',
			// "ENTITY_ID" => 'imol|alotg|2|$01000000182773071d3a41e62f1c9b0b|178',
		// ));
		//Request URL: https://4uz.bitrix24.ru/bitrix/components/bitrix/im.messenger/im.ajax.php?MESSAGE_SEND&V=130&logTag=im.message.add&timType=lines&timLinesType=alotg&timDevice=web

		// $arResults = BxRest::call('im.dialog.get', array(
			// "DIALOG_ID" => 518 //, //"chat_id|$01000000182773071d3a41e62f1c9b0b"
		// ));
	/*
		MESSAGE_SEND: 
V: 130
logTag: im.message.add
timType: lines
timLinesType: alotg
timDevice: web
IM_SEND_MESSAGE: Y
CHAT: Y
ID: temp12
RECIPIENT_ID: chat3138
MESSAGE: 123123123
OL_SILENT: N
TAB: chat3138
USER_TZ_OFFSET: 7200
IM_AJAX_CALL: Y
FOCUS: N
sessid: 40512ed0288d707e78dc4f7ef25214ef
		
		*/
		return $arResults;
	}
	
	private function alovoice_getfreenumber($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceFreeNumber();
	}
	
	private function alovoice_findcontactinfo($r=false) {
		ALVC::eLog($r,"------ AloVoiceRest :: Begin alovoice_findcontactinfo ----------");
		$tgl = new \TGA\ATelegram(); 
		ALVC::eLog(!empty($tgl),"------ AloVoiceRest :: Begin alovoice_findcontactinfo isTGM----------");
		return $tgl->get_contact_info($r["number"]);
		//return ALVC::requestGoogle($r["number"]);
	}
	
	/* STATS methods ........................ */
	private function alovoice_get_agents($r=false) {
		$deps = [488];
		$resDepsAll = BxRest::call("department.get",array('PARENT'=>$deps));
		if( !empty($resDepsAll['result']) ){
			foreach($resDepsAll['result'] as $dpt){ $deps[] = $dpt['ID']; }
		}
		
		$resUserInfo = BxRest::call("user.get",array(
			'FILTER' => [
				'ACTIVE' => true,
				'UF_DEPARTMENT' => $deps,
			]
		));
		
		// echo '<PRE>'; var_dump($resUserInfo['result']); echo '</PRE>';
		$arAgents = [];
		$arAgentIds = [];
		if(!empty($resUserInfo['result'])){
			foreach($resUserInfo['result'] as $usr){
				$arAgents[$usr['ID']] = $usr;
				$arAgentIds[] = $usr['ID'];
				// [
					// 'ID' => $usr['ID'], 
					// 'NAME' => $usr['NAME'], 
					// 'LAST_NAME' => $usr['LAST_NAME'], 
					// 'UF_DEPARTMENT' => $usr['UF_DEPARTMENT'], 
					// 'PERSONAL_PHOTO' => $usr['PERSONAL_PHOTO'],
					// 'UF_PHONE_INNER' => $usr['UF_PHONE_INNER'], 
					// 'WORK_POSITION' => $usr['WORK_POSITION'], 
				// ];
			}
		}
		
		$resCalls = BxRest::call("voximplant.statistic.get",array(
			'FILTER' => [
				'PORTAL_USER_ID' => $arAgentIds,
				">CALL_DURATION" => 29
			]
		));
		
		return ["agents"=> $arAgents, "deps"=>$deps, "calls"=>$resCalls['result']];
	}
	
/* Calls Methods......................*/
	private function alovoice_dnd_toggle($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->doDndToggle($r);
	}
	
	private function alovoice_get_operators($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceOperators();
	}
	
	private function alovoice_peers_list($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoicePeers();
	}

	private function alv_autocall_finished($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->autocallFinished($r);
	}
	
	private function upload_file($r=false) {
		if(!empty($_FILES["file"])){
			if(substr($_FILES["file"]["type"],0,5) == "audio"){
				$alvActions = new AloVoiceActions($this->config);
				return $alvActions->uploadAlovoiceSound($_FILES["file"]);
			}
		}
		return ["error"=>$_FILES];
	}
	
	private function deletealovoiceonesound($r=false) {
		// $r["restmethod"] = null;
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->deleteAlovoiceOneSound($r);
	}
	
	private function savealovoiceonesound($r=false) {
		// $r["restmethod"] = null;
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceSaveSound($r);
	}
	
	private function alovoice_sounds_list($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceSounds();
	}
	
	private function alovoice_trunks_list($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceTrunks();
	}
	
	private function alovoice_get_callscript($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		$res = $alvActions->getOneAlovoiceCallScript($r);
		// $this->integration_on(["code"=>"callscriptscardone","name"=>$r['scriptname']]);
		return $res;
	}
	
	private function alovoice_save_new_callscript($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		$res = $alvActions->addNewAlovoiceCallScript($r);
		if(!empty($res['integ']) && $res['integ']=="yes"){
			$this->integration_on(["code"=>"callscriptscardone","name"=>$r['scriptname']]);
		}
		return $res['res'];
	}
	
	private function alovoice_callscripts_delete($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		$res = $alvActions->deleteAlovoiceCallScripts($r);
		$this->integration_off(["code"=>"callscriptscardone","name"=>$r['filename']]);
		return $res;
	}
	
	private function alovoice_callscripts_list($r=false) {
		$alvActions = new AloVoiceActions($this->config);
		return $alvActions->getAlovoiceCallScripts();
	}
	
	private function crmMenusList() {
		return [
			'CRM_LEAD_DETAIL_TOOLBAR',
			'CRM_DEAL_DETAIL_TOOLBAR',
			'CRM_CONTACT_DETAIL_TOOLBAR',
			'CRM_COMPANY_DETAIL_TOOLBAR'
		];	
		// return [
			// 'CRM_LEAD_LIST_MENU',
			// 'CRM_LEAD_DETAIL_ACTIVITY',
			// 'CRM_LEAD_DETAIL_TOOLBAR'
		// ];
	}
	
	private function status_integration($r=false) {
		$result = shell_exec("ps -aux | grep listener | grep php | grep -v grep | grep bx24 | awk {'print $2'}");
		$integrations = [];
		
		if(!empty($result)){
			$integrations[] = array(
				'code'=>'inboundcalls',
				'title'=>'Входящие звонки',
				'status'=>'on',
			);
		}
		
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'inboundcalls',
			'title'=>'Входящие звонки',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_outbound';
		$res['rescheck'] = $result;
		
		return $res;
	}
	
	private function status_outbound($r=false) {
		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( $itg["event"] == "ONEXTERNALCALLSTART" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'outboundcalls',
							'title'=>'Исходящие звонки',
							'status'=>'on',
						);
					}
				}
			}
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'outboundcalls',
			'title'=>'Исходящие звонки',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_usermenu';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	private function status_usermenu($r=false) {
		//$arResults = BxRest::call('placement.list');
		$arResults = BxRest::call('placement.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $plc){
				if( $plc["placement"] == "USER_PROFILE_MENU" ){
					if( $plc["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'bxusermenu',
							'title'=>'Меню SIP клиент у сотрудника',
							'status'=>'on',
						);
					}
				}
			}
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'bxusermenu',
			'title'=>'Меню SIP клиент у сотрудника',
			'status'=>'off',
			)];
		$res['nextintegration'] = 'status_callcard';
		$res['rescheck'] = $arResults;
		
		return $res;
	}

	private function status_callcard($r=false) {
		//$arResults = BxRest::call('placement.list');
		$arResults = BxRest::call('placement.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $plc){
				if( $plc["placement"] == "CALL_CARD" ){
					if( $plc["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'callcard',
							'title'=>'Карточка звонка',
							'status'=>'on',
						);
					}
				}
			}
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'callcard',
			'title'=>'Карточка звонка',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_useradd';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	/*
	
BX24.callMethod(
   'bizproc.robot.add',
   {
   'CODE': 'alvcallbot',
   'HANDLER': 'https://tug.alovoice.uz/bx24/',
   'AUTH_USER_ID': 1,
   'NAME': 'Позванить',
   'USE_PLACEMENT': 'N', 
   'PLACEMENT_HANDLER': 'https://tug.alovoice.uz/bx24/',
   'PROPERTIES': {
		'callname': {
			'Name': 'Кому звонить?',
			'Type': 'text'
		},
		'callsound': {
			'Name': 'Что воспроизвести?',
			'Type': 'select',
			'Options': {
				'soundone': 'Первый звук',
				'soundtwo': 'Второй звук'
			}
		},
	}
},
function(result){
	if(result.error()){
        console.log("Ошибка: ", result.error());
	}
	else {
		console.log("Ошибка: ", result);
	}
});
	*/
	private function status_autocallrobot($r=false) {
		$restAns = BxRest::call('bizproc.robot.list');
		$arResult = array(
			'lines' => [array(
				'code'=>'autocallrobot',
				'title'=>'Аудио звонок',
				'status'=>'off',
			)],
			'nextintegration' => 'status_useradd',
			'rescheck' => $restAns,
		);
		

		if(!empty($restAns["result"]) && in_array('alvautocall',$restAns["result"])){
			$arResult['lines']['status'] ='on';
		}
	
		return $arResult;
	}
	
	private function status_useradd($r=false) {

		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( $itg["event"] == "ONUSERADD" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'useraddevent',
							'title'=>'Автоназначение внут.номера',
							'status'=>'on',
						);
					}
				}
			}
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'useraddevent',
			'title'=>'Автоназначение внут.номера',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_activityadd';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	// private function status_leadupdate($r=false) {

		// $arResults = BxRest::call('event.get');
		// $integrations = [];
	
		// if(!empty($arResults["result"])){
			// foreach($arResults["result"] as $itg){
				// if( $itg["event"] == "ONCRMLEADUPDATE" ){
					// if( $itg["handler"] == $this->config["alovoice_host"] ){
						// $integrations[] = array(
							// 'code'=>'leadupdateevent',
							// 'title'=>'Лидообработка',
							// 'status'=>'on',
						// );
					// }
				// }
			// }
		// }
		// $res['lines'] = (!empty($integrations)) ? $integrations : [array(
			// 'code'=>'leadupdateevent',
			// 'title'=>'Лидообработка',
			// 'status'=>'off',
		// )];
		// $res['nextintegration'] = 'status_activityadd';
		// $res['rescheck'] = $arResults;
		
		// return $res;
	// }
	
	private function status_activityadd($r=false) {
		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( $itg["event"] == "ONCRMACTIVITYADD" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'activityadd',
							'title'=>'Событие дел',
							'status'=>'on',
						);
					}
				}
			}
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'activityadd',
			'title'=>'Событие дел',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_alosms';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	// private function status_callback($r=false) { //todo

		// $arResults = BxRest::call('event.get');
		// $integrations = [];
	
		// if(!empty($arResults["result"])){
			// foreach($arResults["result"] as $itg){
				// if( $itg["event"] == "ONEXTERNALCALLBACKSTART" ){
					// if( $itg["handler"] == $this->config["alovoice_host"] ){
						// $integrations[] = array(
							// 'code'=>'callbackcalls',
							// 'title'=>'Обратный звонок',
							// 'status'=>'on',
						// );
					// }
				// }
			// }
		// }
		// $res['lines'] = (!empty($integrations)) ? $integrations : [array(
			// 'code'=>'callbackcalls',
			// 'title'=>'Обратный звонок',
			// 'status'=>'off',
		// )];
		// $res['nextintegration'] = 'status_alotg';
		// $res['rescheck'] = $arResults;
		
		// return $res;
	// }
	
		
	private function status_alosms($r=false) {
		$integrations = [];
		$arResults = BxRest::call('messageservice.sender.list');
		if(!empty($arResults["result"]) && in_array("alosms",$arResults["result"])){
			$integrations[] = array(
				'code'=>'smsservice',
				'title'=>'SMS сервис (alosms)',
				'status'=>'on',
			);
		}
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'smsservice',
			'title'=>'SMS сервис',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_alotg';
		$res['rescheck'] = $arResults;
		
		return $res;
	}	
	// private function status_aloetc($r=false) {
		// $integrations = [];
		// $arResults = BxRest::call('messageservice.sender.list');
		// if(!empty($arResults["result"]) && in_array("smsetc",$arResults["result"])){
			// $integrations[] = array(
				// 'code'=>'smsetcgateway',
				// 'title'=>'SMS шлюз (smsetc)',
				// 'status'=>'on',
			// );
		// }
		// $res['lines'] = (!empty($integrations)) ? $integrations : [array(
			// 'code'=>'smsetcgateway',
			// 'title'=>'SMS шлюз Etc',
			// 'status'=>'off',
		// )];
		// $res['nextintegration'] = 'status_alotg';
		// $res['rescheck'] = $arResults;
		
		// return $res;
	// }
	
	private function status_alotg($r=false) {
		//OnImConnectorMessageAdd
		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( $itg["event"] == "ONIMCONNECTORMESSAGEADD" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$tgl = new \TGA\ATelegram(); 
						$olId = $tgl->getLine();
						if(!empty($olId)){
							$integrations[] = array(
								'code'=>'tgservice',
								'title'=>'Telegram сервис ('.$olId.')',
								'status'=>'on',
							);
						} else {
							$integrations[] = array(
								'code'=>'tgservice',
								'title'=>'Telegram сервис не запущен',
								'status'=>'on',
							);
						}
					}
				}
			}
		}
		/*
		$tgl = new \TGA\ATelegram(); 
		$olId = $tgl->getLine();
		if(!empty($olId)){
			$integrations[] = array(
				'code'=>'tgservice',
				'title'=>'Telegram сервис ('.$olId.')',
				'status'=>'on',
			);
		}
		*/
		/*
		$arResults = BxRest::call('imbot.bot.list');
		$listenTgAgent = false;
		$listenTgAgentId = false;
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $bxBot){
				if( $bxBot["CODE"] == 'alotg' ){
					//$listenTgAgent = true;
					//$listenTgAgentId = $bxBot["ID"];
					$integrations[] = array(
						'code'=>'tgservice',
						'title'=>'Telegram сервис ('.$listenTgAgentId.')',
						'status'=>'on',
					);
				}
			}
		}*/

		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'tgservice',
			'title'=>'Telegram сервис',
			'status'=>'off',
		)];
		
		$res['nextintegration'] = 'status_contactupdate';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	private function status_contactupdate($r=false) {
		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( $itg["event"] == "ONCRMCONTACTUPDATE" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'contactupdate',
							'title'=>'Обновления контактов',
							'status'=>'on',
						);
					}
				}
			}
		}

		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'contactupdate',
			'title'=>'Обновления контактов',
			'status'=>'off',
		)];
		
		$res['nextintegration'] = 'status_alvcrmmenus';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	private function status_alvcrmmenus($r=false) {
		$arPls = self::crmMenusList();
		
		$arResults = BxRest::call('placement.get');
		$integrations = [];
		$arCntPls = 0;
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $plc){
				if( in_array($plc["placement"], $arPls) && $plc["handler"] == $this->config["alovoice_host"].'?inncheck' ){
					$arCntPls++;
				}
			}
		}
		
		$allCnt = count($arPls);
		$res['lines'] = [];
		
		if( $arCntPls < $allCnt ){
			$res['lines'][] = array(
				'code'=>'alvcrmmenus',
				'title'=>'Инструменты в СРМ сущностях ('.$allCnt.'/'.$arCntPls.')',
				'status'=>'off',
			);
		}
		else {
			$res['lines'][] = array(
				'code'=>'alvcrmmenus',
				'title'=>'Инструменты в СРМ сущностях ('.$allCnt.'/'.$arCntPls.')',
				'status'=>'on',
			);
		}	
		

		
		
		$res['nextintegration'] = 'status_alvcrmmenustg';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	private function status_alvcrmmenustg($r=false) {
		$arPls = self::crmMenusList();
		
		$arResults = BxRest::call('placement.get');
		$integrations = [];
		$arCntPls = 0;
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $plc){
				if( in_array($plc["placement"], $arPls) && $plc["handler"] == $this->config["alovoice_host"].'?tgupd' ){
					$arCntPls++;
				}
			}
		}
		
		$allCnt = count($arPls);
		$res['lines'] = [];
		
		if( $arCntPls < $allCnt ){
			$res['lines'][] = array(
				'code'=>'alvcrmmenustg',
				'title'=>'Telegram Upd в СРМ сущностях ('.$allCnt.'/'.$arCntPls.')',
				'status'=>'off',
			);
		}
		else {
			$res['lines'][] = array(
				'code'=>'alvcrmmenustg',
				'title'=>'Telegram Upd в СРМ сущностях ('.$allCnt.'/'.$arCntPls.')',
				'status'=>'on',
			);
		}	
		

		
		
		$res['nextintegration'] = 'status_callscriptscard';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	private function status_callscriptscard($r=false) {
		$arCallScriptFiles = [];
		if ($handle = opendir('/var/www/html/bx24/callscripts')) {
			while (false !== ($entry = readdir($handle))) {
				if (substr($entry,-5)==".html") {
					$arCallScriptFiles[] = $entry;
				}
			}
			closedir($handle);
		}
		
		$arResults = [];
		$integrations = [];
		$allClScrCnt = count($arCallScriptFiles);
		
		if(!empty($arCallScriptFiles)){
			$arCsCardCnt = 0;
			$arResults = BxRest::call('placement.get');
			if(!empty($arResults["result"])){
				foreach($arResults["result"] as $plc){
					$pos = strpos($plc["handler"], "callscripts");
					if ($plc["placement"] == "CALL_CARD" && $pos != false) {
						$arCsCardCnt++;
					}
				}
				
				if(!empty($arCsCardCnt)){
					$integrations[] = array(
						'code'=>'callscriptscard',
						'title'=>'Вкладки скриптов ('.$arCsCardCnt.'/'.$allClScrCnt.')',
						'status'=>'on',
					);
				}
				
			}
			
			
			// $arResults = BxRest::call('placement.get');
			// if(!empty($arResults["result"])){
				// $arCsCardCnt = 0;
				// $prefcnt = strlen("Скрипт: ");
				// foreach($arResults["result"] as $plc){
					// $curPlcTitle = substr($plc["title"],$prefcnt);
					
					// if( $plc["placement"] == "CALL_CARD" && in_array($curPlcTitle,$arCallScriptFiles) ){
						// $arCsCardCnt++;
					// }
				// }
				
				// if(!empty($arCsCardCnt)){
					// $integrations[] = array(
						// 'code'=>'callscriptscard',
						// 'title'=>'Вкладки скриптов ('.$arCsCardCnt.'/'.$allClScrCnt.')',
						// 'status'=>'on',
					// );
				// }
			// }
			
		}
		
		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'callscriptscard',
			'title'=>'Вкладки скриптов',
			'status'=>'off',
		)];
		$res['nextintegration'] = 'status_salepaymentsave';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	
	private function status_salepaymentsave($r=false) {
		//OnPaymentEntitySaved salepaymentsave
		$arResults = BxRest::call('event.get');
		$integrations = [];
	
		if(!empty($arResults["result"])){
			foreach($arResults["result"] as $itg){
				if( strtoupper($itg["event"]) == "ONPAYMENTENTITYSAVED" ){
					if( $itg["handler"] == $this->config["alovoice_host"] ){
						$integrations[] = array(
							'code'=>'salepaymentsave',
							'title'=>'Отслеживания оплат',
							'status'=>'on',
						);
					}
				}
			}
		}

		$res['lines'] = (!empty($integrations)) ? $integrations : [array(
			'code'=>'salepaymentsave',
			'title'=>'Отслеживания оплат',
			'status'=>'off',
		)];
		
		// $res['nextintegration'] = 'status_alvcrmmenus';
		$res['rescheck'] = $arResults;
		
		return $res;
	}
	

	private function integration_on($r=false) {
		//outboundcalls
		if($r["code"]=='outboundcalls'){
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONEXTERNALCALLSTART',
				'handler'=>$this->config["alovoice_host"],
			]);
			//$arResults = BxRest::call('event.get');
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='alvcrmmenus'){
			$doResult = false;
			$arPls = self::crmMenusList();
			$addingMenusList = [];
			foreach($arPls as $mnu){
				$addingMenusList[] = 'placement.bind?'.http_build_query(
					array(
						'PLACEMENT'=>$mnu,
						'HANDLER'=>$this->config["alovoice_host"].'?inncheck',
						'TITLE'=>"Реквизиты(УЗБ)",
						'DESCRIPTION'=>'Обновить Реквизиты по ИНН (УЗБ)',
					)
				);
			}
			
			if(!empty($addingMenusList)){
				$doResult = BxRest::call('batch',[
					'halt' => 0,
					'cmd' => $addingMenusList
				]);
				
			}
			
			return array( 'do' => $doResult, 'result' => 'success'); 
			
		}
		
		if($r["code"]=='alvcrmmenustg'){
			$doResult = false;
			$arPls = self::crmMenusList();
			$addingMenusList = [];
			foreach($arPls as $mnu){
				$addingMenusList[] = 'placement.bind?'.http_build_query(
					array(
						'PLACEMENT'=>$mnu,
						'HANDLER'=>$this->config["alovoice_host"].'?tgupd',
						'TITLE'=>"Найти в TG",
						'DESCRIPTION'=>'Обновить по Telegram',
					)
				);
			}
			
			if(!empty($addingMenusList)){
				$doResult = BxRest::call('batch',[
					'halt' => 0,
					'cmd' => $addingMenusList
				]);
				
			}
			
			return array( 'do' => $doResult, 'result' => 'success'); 
			
		}
		
		if($r["code"]=='callscriptscardone'){
			$doResult = BxRest::call('placement.bind',[
				'PLACEMENT'=>'CALL_CARD',
				'HANDLER'=>$this->config["alovoice_host"].'callscripts/'.$r["name"].'.html',
				'TITLE'=>$r["name"],
				'DESCRIPTION'=>'Скрипт звонка: '.$r["name"],
			]);
		}
		
		if($r["code"]=='callscriptscard'){
			$arCallScriptFiles = [];
			$aloCallScrpBindPlcResult = [];
			
			if ($handle = opendir('/var/www/html/bx24/callscripts')) {
				while (false !== ($entry = readdir($handle))) {
					if (substr($entry,-5)==".html") {
						$arCallScriptFiles[] = substr($entry,0,-5);
					}
				}
				closedir($handle);
			}
			
			$arResults = [];
			$integrations = [];
			$allClScrCnt = count($arCallScriptFiles);
			if(!empty($arCallScriptFiles)){
				$arResults = BxRest::call('placement.get');
				if(!empty($arResults["result"])){
					$arCallsAddedCards = [];
					foreach($arResults["result"] as $plc){
						if( $plc["placement"] == "CALL_CARD" && in_array($plc["title"],$arCallScriptFiles) ){
							$arCallsAddedCards[] = $plc["title"];
						}
					}
					
					$addingScriptFiles = [];
					foreach($arCallScriptFiles as $scrFile){
						if(!in_array($scrFile,$arCallsAddedCards)){
							$addingScriptFiles[] = 'placement.bind?'.http_build_query(
								array(
									'PLACEMENT'=>'CALL_CARD',
									'HANDLER'=>$this->config["alovoice_host"].'callscripts/'.$scrFile.'.html',
									'TITLE'=>$scrFile,
									'DESCRIPTION'=>'Скрипт звонка: '.$scrFile,
								)
							);
						}
					}
				}
				
				if(!empty($addingScriptFiles)){
					$aloCallScrpBindPlcResult = BxRest::call('batch',[
						'halt' => 0,
						'cmd' => $addingScriptFiles
					]);
				}
			}
			
			return array( 'do' => $aloCallScrpBindPlcResult, 'result' => 'success');
		}
		
		if($r["code"]=='callcard'){
			$doResult = BxRest::call('placement.bind',[
				'PLACEMENT'=>'CALL_CARD',
				'HANDLER'=>$this->config["alovoice_host"],
				'TITLE'=>'Информация',
				'DESCRIPTION'=>'Генерировано AloVoice',
			]);
			//"Unable to set placement handler: Handler already binded"
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='bxusermenu'){
			$doResult = BxRest::call('placement.bind',[
				'PLACEMENT'=>'USER_PROFILE_MENU',
				'HANDLER'=>$this->config["alovoice_host"],
				'TITLE'=>'Мои телефоны',
				'DESCRIPTION'=>'Скачать SIP клиент для звонков в компьютере ',
			]);
			//"Unable to set placement handler: Handler already binded"
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='autocallrobot'){
			return array( 'do' => "soon", 'result' => 'success');
		}
		if($r["code"]=='inboundcalls'){
			return array( 'do' => "soon", 'result' => 'success');
		}
		
		if($r["code"]=='useraddevent'){
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONUSERADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='activityadd'){ //oncrmactivityadd
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONCRMACTIVITYADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='leadupdateevent'){
			$doResult = BxRest::call('event.bind',[
				'event'=>'onCrmLeadUpdate',
				'handler'=>$this->config["alovoice_host"],
			]);
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONCRMDEALADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONCRMLEADADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			
			$resActivity = BxRest::call('crm.activity.type.add',[
				'fields'=>array(
					"TYPE_ID" => "inninfo",
					"NAME" => "Информация",
					//"ICON_FILE" => "", //document.getElementById('type-icon') // file input node
				),
			]);
			
			$resAddUserFiled = BxRest::call('crm.lead.userfield.add',[
				'fields'=>array(
					"FIELD_NAME" => "ALV_TG_CHECKER",
					"EDIT_FORM_LABEL" => "Проверка номера ТГ",
					"LIST_COLUMN_LABEL" => "Проверка номера ТГ",
					"USER_TYPE_ID" => "string",
					"XML_ID" => "ALV_TG_CHECKER",
					"SETTINGS" => [ "DEFAULT_VALUE"=>""]
				),
			]);
			
			return array( 'do' => $doResult, 'result' => 'success', 'activity' => $resActivity, 'resAddUserFiled' => $resAddUserFiled);
		}
		
		if($r["code"]=='callbackcalls'){
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONEXTERNALCALLBACKSTART',
				'handler'=>$this->config["alovoice_host"],
			]);
			//$arResults = BxRest::call('event.get');
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='smsservice'){
			$doResult = BxRest::call('messageservice.sender.add',array(
				'CODE' => 'alosms',
				'TYPE' => 'SMS',
				'HANDLER' => $this->config["alovoice_host"],
				'NAME' => 'AloSms',
				'DESCRIPTION' => 'Sms provider for sending sms by AloVoice'
			));
			$moreResult = BxRest::call('crm.activity.type.add',[
				'TYPE_ID' => 'alosms',
				'NAME' => 'AloSms',
				'ICON_FILE' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAAAAAAbPrZOAAAVE0lEQVQYGeXAC2DNdeM/8PfZZht28SCwAIGIBKkewJMCAyj9qCAQgCWRSg/EskKI9O8RIQS6oYCUKICIpAZGgG02287e/13O93wvn8/3fM8u7Bx7gfkMmM+A+QyYz4D5DJjPgPkMmM+A+QyYz4B3SezhDbNfHfjs042qly1ZNDjQxycwuGjJsjUea/3swHEffHUkjncJeIfFHVo/a1SXesVgoXj9LqNnbzgUzzsMvHNu/zK3d00fZInvQ33n/5rEOwe8I1KP/W9IwwBkU2CjoZ8eT+UdAea+YzNahiDHQltFnWTuA3PX7c3DKyPXVB21JYm5C8xFMR93DkYuC+n2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J/K/E8YM6dezW7fnXnxp8IixU+Yt+3b379d5t4CKN5FdwYOP02uADslhyJ6ac27Si4AOq5AdBXtuo3cBHVog6xrMu05vA2b6DVlVduwReiEwUz9kSZF+21LplcAMMQFwX7E+X9+mtwIzTIC7Sg36LpleDEwXXxRuKTt8h53eDUw3G26oM253Kr0emCalEiwEd1p4lvcEMM1KuFRj9PdJvFeAaRrCVGj7D07zXgKSGyFX6MmpP6fwHgOS/4bIv/Eb22/zHgRyCwwKNhm3KZ73KJDNoVGma9TPSbyHgTvh4Pvw4KWnea8DWwGwPdBj5o445gf4tfbzUVuvMd8A8xkwnwHzGTCfAfMZMJ8B8xkwnwHzGTCf+f+lxugxz/9YKwAAAABJRU5ErkJggg=='
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='ecpavtivity'){
			$moreResult = BxRest::call('crm.activity.type.add',[
				'TYPE_ID' => 'ecpsign',
				'NAME' => 'Подпись',
				'ICON_FILE' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAADAFBMVEX///+AgIB/f39+fn6Gh4aEhIR8fHyIiIiGhoaKioqCgoJsbGxycnKHhoZoZ2glJSUXFxdISEiJiYmDg4NoaGgHBgcbGhttbG0MCwwAAABnZmd9fX04NzgaGRs9PT4FAwYDAQUCAAIHBgh4eHgSERI7OjsiISMDAQQCAAMAAAEUExWFhYVWVlcHBwhHR0cEBAUBAAIBAQFxcHEsKy0lJCY5OToEAQUbGhyBgYFwcHAIBwlDQkMXFxgDAgRJSUmAgIGFhYRJSEkODg8CAQNwb3BfXl4vLy8dHB0rKyxeXl8gHyAAAQAuLS4tLC4GBAcEAgUpKCl/f4A6OjtRUVGDhINjY2MCAgNKSUokIyRUVFQ5OTkJCQorKysJCAkGBQZubm4EBAQTExRbW1sxMDEKCgoLCwx3d3eBgIFdXV0WFRZra2tXV1cEAwSHh4Zvbm9UU1SNjYx0c3QgHyFramuGhYYjIiMdHR6Hh4d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gly832CCvuQBsIDGIaSUgJTIJCUNDGqOAZmaJ5xPYonU03PPzAUqOgtyI+60eMFZ8iLQsMt4stwVBgbbqwTy7HWScjgAesRHnSiyCqwAAAAASUVORK5CYII='
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='smsetcgateway'){
			$doResult = BxRest::call('messageservice.sender.add',array(
				'CODE' => 'smsetc',
				'TYPE' => 'SMS',
				'HANDLER' => $this->config["alovoice_host"],
				'NAME' => 'SmsEtc',
				'DESCRIPTION' => 'Sms gateway from Etc by AloVoice'
			));
			
			$moreResult = BxRest::call('crm.activity.type.add',[
				'TYPE_ID' => 'smsetc',
				'NAME' => 'EtcSMS',
				'ICON_FILE' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAAAAAAbPrZOAAAVE0lEQVQYGeXAC2DNdeM/8PfZZht28SCwAIGIBKkewJMCAyj9qCAQgCWRSg/EskKI9O8RIQS6oYCUKICIpAZGgG02287e/13O93wvn8/3fM8u7Bx7gfkMmM+A+QyYz4D5DJjPgPkMmM+A+QyYz4B3SezhDbNfHfjs042qly1ZNDjQxycwuGjJsjUea/3swHEffHUkjncJeIfFHVo/a1SXesVgoXj9LqNnbzgUzzsMvHNu/zK3d00fZInvQ33n/5rEOwe8I1KP/W9IwwBkU2CjoZ8eT+UdAea+YzNahiDHQltFnWTuA3PX7c3DKyPXVB21JYm5C8xFMR93DkYuC+n2ySXmIjC3nJnc0IY7wqfROxeYW8BckbS6jQ/uIL/wdcnMFWAuOB5RAndc6VdPMBeAORX/yb9xlzRZfIs5BebMsQEhuItCB51kzoA5cfgZH9xlvj1/Y06A2be/sw15wKf7QWYfmF172iOv2Dr+wuwCs2fX08hTrX9k9oDZcaAl8tyTR5gdYNZdH+YLD+A36iazDsyyT0vBQ5T+jFkGZtHhJvAgzY4wi8AsuTnSD9kUWrv9kMhFy9Z/9+PBk+euJyVdP3fy4I/frV+2KHJI+9qhyCa/UTeZJWBWfFYaWV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4KWnea8DWwGwPdBj5o445gf4tfbzUVuvMd8A8xkwnwHzGTCfAfMZMJ8B8xkwnwHzGTCf+f+lxugxz/9YKwAAAABJRU5ErkJggg=='
			]);
			
			return array( 'do' => $doResult,'more' => $moreResult, 'result' => 'success');
		}
		
		if($r["code"]=='salepaymentsave'){
			//OnPaymentEntitySaved salepaymentsave
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONPAYMENTENTITYSAVED',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='contactupdate'){
			$doResult = BxRest::call('event.bind',[
				'event'=>'ONCRMCONTACTUPDATE',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}

		if($r["code"]=='tgservice'){
			$arResults = BxRest::call('imconnector.unregister',[ 'ID' => 'alotg' ]);
			$regAloTgConnector = BxRest::call("imconnector.register",array(
				'ID' => 'alotg',
				'NAME' => 'AloTG',
				'ICON' => [
					'DATA_IMAGE' => 'data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%20240%20240%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22a%22%20x1%3D%22.667%22%20x2%3D%22.417%22%20y1%3D%22.167%22%20y2%3D%22.75%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%2337aee2%22/%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%231e96c8%22/%3E%3C/linearGradient%3E%3ClinearGradient%20id%3D%22b%22%20x1%3D%22.66%22%20x2%3D%22.851%22%20y1%3D%22.437%22%20y2%3D%22.802%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%23eff7fc%22/%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23fff%22/%3E%3C/linearGradient%3E%3C/defs%3E%3Ccircle%20cx%3D%22120%22%20cy%3D%22120%22%20r%3D%22120%22%20fill%3D%22url%28%23a%29%22/%3E%3Cpath%20fill%3D%22%23c8daea%22%20d%3D%22M98%20175c-3.888%200-3.227-1.468-4.568-5.17L82%20132.207%20170%2080%22/%3E%3Cpath%20fill%3D%22%23a9c9dd%22%20d%3D%22M98%20175c3%200%204.325-1.372%206-3l16-15.558-19.958-12.035%22/%3E%3Cpath%20fill%3D%22url%28%23b%29%22%20d%3D%22M100.04%20144.41l48.36%2035.729c5.519%203.045%209.501%201.468%2010.876-5.123l19.685-92.763c2.015-8.08-3.08-11.746-8.36-9.349l-115.59%2044.571c-7.89%203.165-7.843%207.567-1.438%209.528l29.663%209.259%2068.673-43.325c3.242-1.966%206.218-.91%203.776%201.258%22/%3E%3C/svg%3E',
					'COLOR' => '#a6ffa3',
					'SIZE' => '100%',
					'POSITION' => 'center',
				],
				'ICON_DISABLED' => [
					'DATA_IMAGE' => 'data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%20240%20240%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22a%22%20x1%3D%22.667%22%20x2%3D%22.417%22%20y1%3D%22.167%22%20y2%3D%22.75%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%23ccc%22/%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23888%22/%3E%3C/linearGradient%3E%3ClinearGradient%20id%3D%22b%22%20x1%3D%22.66%22%20x2%3D%22.851%22%20y1%3D%22.437%22%20y2%3D%22.802%22%3E%3Cstop%20offset%3D%220%22%20stop-color%3D%22%23eff7fc%22/%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23fff%22/%3E%3C/linearGradient%3E%3C/defs%3E%3Ccircle%20cx%3D%22120%22%20cy%3D%22120%22%20r%3D%22120%22%20fill%3D%22url%28%23a%29%22/%3E%3Cpath%20fill%3D%22%23c8daea%22%20d%3D%22M98%20175c-3.888%200-3.227-1.468-4.568-5.17L82%20132.207%20170%2080%22/%3E%3Cpath%20fill%3D%22%23a9c9dd%22%20d%3D%22M98%20175c3%200%204.325-1.372%206-3l16-15.558-19.958-12.035%22/%3E%3Cpath%20fill%3D%22url%28%23b%29%22%20d%3D%22M100.04%20144.41l48.36%2035.729c5.519%203.045%209.501%201.468%2010.876-5.123l19.685-92.763c2.015-8.08-3.08-11.746-8.36-9.349l-115.59%2044.571c-7.89%203.165-7.843%207.567-1.438%209.528l29.663%209.259%2068.673-43.325c3.242-1.966%206.218-.91%203.776%201.258%22/%3E%3C/svg%3E',
					'SIZE' => '100%',
					'POSITION' => 'center',
					'COLOR' => '#ffb3a3',
				],
				'PLACEMENT_HANDLER' => $this->config["alovoice_host"],
			));
			ALVC::eLog($regAloTgConnector,"-------------------== regAloTgConnector RES: ----------------");
			$listenTgAgentId = $regAloTgConnector["result"];
			
			//OnImConnectorMessageUpdate
			$aloTgConnEventResult = BxRest::call('batch',[
				'halt' => 0,
				'cmd' => [
					'bind_msg_add' => 'event.bind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageAdd',
							'handler' => $this->config["alovoice_host"],
						)
					),
					'bind_msg_upd' => 'event.bind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageUpdate',
							'handler' => $this->config["alovoice_host"],
						)
					),
					'bind_msg_del' => 'event.bind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageDelete',
							'handler' => $this->config["alovoice_host"],
						)
					),
					
				]
			]);
			/*
			$aloTgConnEventResult = BxRest::call('event.bind',[
				'event'=>'OnImConnectorMessageAdd',
				'handler'=>$this->config["alovoice_host"],
			]);
			*/
			return array( 'res' => ['tgevent'=>$aloTgConnEventResult,'tgplace'=>$regAloTgConnector], 'result' => 'success');
			
			
			
			/*
			$regTgAgentBot = BxRest::call("imbot.register",array(
				'CODE' => 'alotg',
				'TYPE' => 'S',
				'EVENT_HANDLER' => config["alovoice_host"],
				'OPENLINE' => 'Y',
				'PROPERTIES' => Array(
					'NAME' => 'TG24',
					'LAST_NAME' => '',
					'COLOR' => 'DARK_BLUE',
					'PERSONAL_GENDER' => ''
				)
			));
			ALVC::eLog($regTgAgentBot,"-------------------== regTgAgentBot RES: ----------------");
			$listenTgAgentId = $regTgAgentBot["result"];*/
		}
		
		return 'code not found';
	}
	
	private function crm_updater_menus_on($r=false) {
		$arrCrmEntities = ALVC::crm_entites();
		$addingMenusList = [];
		$doResult = ["error"];
		foreach($arrCrmEntities as $entity=>$entTitle){
			$upEnt = strtoupper($entity);
			// $addingMenusList[] = 'placement.bind?'.http_build_query(
				// array(
					// 'PLACEMENT'=>'CRM_'.$upEnt.'_LIST_MENU',
					// 'HANDLER'=>$this->config["alovoice_host"].'?inncheck',
					// 'TITLE'=>"Обновить по ИНН",
					// 'DESCRIPTION'=>'Обновить по ИНН',
				// )
			// );
			$addingMenusList[] = 'placement.bind?'.http_build_query(
				array(
					'PLACEMENT'=>'CRM_'.$upEnt.'_DETAIL_TOOLBAR',
					'HANDLER'=>$this->config["alovoice_host"].'?inncheck',
					'TITLE'=>"Реквизиты(УЗБ)",
					'DESCRIPTION'=>'Обновить реквизиты по ИНН открытых данных',
				)
			);
		}
		
		if(!empty($addingMenusList)){
			$doResult = BxRest::call('batch',[
				'halt' => 0,
				'cmd' => $addingMenusList
			]);
			
		}
		
		return $doResult;
	}
	
	private function crm_updater_menus_off($r=false) {
		$arrCrmEntities = ALVC::crm_entites();
		$addingMenusList = [];
		foreach($arrCrmEntities as $entity){
			$upEnt = strtoupper($entity);
			// $addingMenusList[] = 'placement.unbind?'.http_build_query(
				// array(
					// 'PLACEMENT'=>'CRM_'.$upEnt.'_LIST_MENU',
					// 'HANDLER'=>$this->config["alovoice_host"].'?inncheck'
				// )
			// );
			$addingMenusList[] = 'placement.unbind?'.http_build_query(
				array(
					'PLACEMENT'=>'CRM_'.$upEnt.'_DETAIL_TOOLBAR',
					'HANDLER'=>$this->config["alovoice_host"].'?inncheck'
				)
			);
		}
		
		if(!empty($addingMenusList)){
			$doResult = BxRest::call('batch',[
				'halt' => 0,
				'cmd' => $addingMenusList
			]);
			
		}
	}
	
	private function checkmethod($r=false) {
		
		$doResult = BxRest::call('sale.paysystem.handler.list',[]);
		return ["result"=>$doResult];
	}
	private function load_all_events($r=false) {
		
		// $doResult = BxRest::call('event.bind',['event'=>'ONPAYMENTENTITYSAVED','handler'=>'https://pay.4u.uz/']);
		// return ["result"=>$doResult];	
		// $doResult = BxRest::call('events',[]);
		// ;
		$doResult = BxRest::call("user.get");
		return ["result"=>$doResult];
	}
	
	private function integration_off($r=false) {
		
		if($r["code"]=='outboundcalls'){
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONEXTERNALCALLSTART',
				'handler'=>$this->config["alovoice_host"],
			]);
			
			//$arResults = BxRest::call('event.get');
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='alvcrmmenus'){
			$doResult = false;
			$arPls = self::crmMenusList();
			$addingMenusList = [];
			foreach($arPls as $mnu){
				$addingMenusList[] = 'placement.unbind?'.http_build_query(
					array(
						'PLACEMENT'=>$mnu,
						'HANDLER'=>$this->config["alovoice_host"].'?inncheck',
					)
				);
			}
			
			if(!empty($addingMenusList)){
				$doResult = BxRest::call('batch',[
					'halt' => 0,
					'cmd' => $addingMenusList
				]);
				
			}
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='alvcrmmenustg'){
			$doResult = false;
			$arPls = self::crmMenusList();
			$addingMenusList = [];
			foreach($arPls as $mnu){
				$addingMenusList[] = 'placement.unbind?'.http_build_query(
					array(
						'PLACEMENT'=>$mnu,
						'HANDLER'=>$this->config["alovoice_host"].'?tgupd',
					)
				);
			}
			
			if(!empty($addingMenusList)){
				$doResult = BxRest::call('batch',[
					'halt' => 0,
					'cmd' => $addingMenusList
				]);
				
			}
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='inboundcalls'){
			//todo
		}
		if($r["code"]=='callbackcalls'){
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONEXTERNALCALLBACKSTART',
				'handler'=>$this->config["alovoice_host"],
			]);
			
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='useraddevent'){
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONUSERADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		
		if($r["code"]=='activityadd'){ //oncrmactivityadd
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONCRMACTIVITYADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='leadupdateevent'){
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONCRMLEADUPDATE',
				'handler'=>$this->config["alovoice_host"],
			]);
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONCRMDEALADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONCRMLEADADD',
				'handler'=>$this->config["alovoice_host"],
			]);
			$resActivity = BxRest::call('crm.activity.type.delete',[
				'fields'=>array(
					"TYPE_ID" => "inninfo"
				)
			]);
			return array( 'do' => $doResult, 'result' => 'success');
		}
		
		if($r["code"]=='callscriptscardone'){
			$doResult = BxRest::call('placement.unbind',[
				'PLACEMENT'=>'CALL_CARD',
				'HANDLER'=>$this->config["alovoice_host"].'callscripts/'.$r["name"],
			]);
		}
		
		if($r["code"]=='callscriptscard'){
			$arCallScripts = [];
			
			$arResults = BxRest::call('placement.get');
			if(!empty($arResults["result"])){
				foreach($arResults["result"] as $plc){
					$pos = strpos($plc["handler"], "callscripts");
					if ($plc["placement"] == "CALL_CARD" && $pos != false) {
						$arCallScripts[] = 'placement.unbind?'.http_build_query( array(
							'PLACEMENT'=>'CALL_CARD',
							'HANDLER'=>$plc["handler"],
						));
					}
				}
			}

			if(!empty($arCallScripts)){
				$aloCallScrpUnBindPlcResult = BxRest::call('batch',[
					'halt' => 0,
					'cmd' => $arCallScripts
				]);
				
			}
			
			return array( 'do' => $aloCallScrpUnBindPlcResult, 'result' => 'success');
		}
		
		if($r["code"]=='salepaymentsave'){
			//OnPaymentEntitySaved salepaymentsave
			$doResult = BxRest::call('event.unbind',[
				'event'=>'ONPAYMENTENTITYSAVED',
				'handler'=>$this->config["alovoice_host"],
			]);
			return array( 'do' => $doResult, 'result' => 'success'); 
		} 
		
		if($r["code"]=='callcard'){
			
			$doResult = BxRest::call('placement.unbind',[
				'PLACEMENT'=>'CALL_CARD',
				'HANDLER'=>$this->config["alovoice_host"],
			]);
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		if($r["code"]=='bxusermenu'){
			
			$doResult = BxRest::call('placement.unbind',[
				'PLACEMENT'=>'USER_PROFILE_MENU',
				'HANDLER'=>$this->config["alovoice_host"],
			]);
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='tgservice'){
			$arResults = BxRest::call('imconnector.unregister',[ 'ID' => 'alotg' ]);
			$aloTgConnEventResult = BxRest::call('batch',[
				'halt' => 0,
				'cmd' => [
					'bind_msg_add' => 'event.unbind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageAdd',
							'handler' => $this->config["alovoice_host"],
						)
					),
					'bind_msg_upd' => 'event.unbind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageUpdate',
							'handler' => $this->config["alovoice_host"],
						)
					),
					'bind_msg_del' => 'event.unbind?'.http_build_query(
						array(
							'event' => 'OnImConnectorMessageDelete',
							'handler' => $this->config["alovoice_host"],
						)
					),
					
				]
			]);
			/*
			$doResult = BxRest::call('event.unbind',[
				'event'=>'OnImConnectorMessageAdd',
				'handler'=>$this->config["alovoice_host"],
			]);
			*/
			return array('result' => 'success');
		}
		
		if($r["code"]=='smsservice'){
			$doResult = BxRest::call('messageservice.sender.delete',[
				'CODE' => 'alosms'
			]);
			// $doResult = BxRest::call('crm.activity.type.add',[
				// 'TYPE_ID' => 'alosms',
				// 'NAME' => 'AloSMS',
				// 'ICON_FILE' => 'data:image/png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Lq2EtCYg11zk6ribxVePx1ZhOoswsSheKourqwhQ/ylv/gC8w2UCcCEs9Rce1/7Qogj4VNusAcALVSy0HiK2a49FHrAshrTT9PZo6AWlsgcV8yyVPvNvZBXis84DBzCtR6ERJDUn4YWxN5r+p715lzoEZ8ECQaFkPeK/HS5lTmBlDjU3imCiN32JlLQI0n4YFqvr6PuQhUnfVBjgU8FYbc49PonRPMXaDqHeRY51Pk2S/GNgtGjvk9GvHldeY6UFUdOdRgKx3shxf1f9gf2VW+8+RNsbwjQKctyJl6G6iX8sdXMwc0K4WsCG3Ya+rGy7xzQKeuyIlG62jixp5PJw3u8sQDQXAhqFrLF8Yv2B7DOw1UnPNDttnCd9Ja3KldX3w0J/K/E8YM6dezW7fnXnxp8IixU+Yt+3b379d5t4CKN5FdwYOP02uADslhyJ6ac27Si4AOq5AdBXtuo3cBHVog6xrMu05vA2b6DVlVduwReiEwUz9kSZF+21LplcAMMQFwX7E+X9+mtwIzTIC7Sg36LpleDEwXXxRuKTt8h53eDUw3G26oM253Kr0emCalEiwEd1p4lvcEMM1KuFRj9PdJvFeAaRrCVGj7D07zXgKSGyFX6MmpP6fwHgOS/4bIv/Eb22/zHgRyCwwKNhm3KZ73KJDNoVGma9TPSbyHgTvh4Pvw4KWnea8DWwGwPdBj5o445gf4tfbzUVuvMd8A8xkwnwHzGTCfAfMZMJ8B8xkwnwHzGTCf+f+lxugxz/9YKwAAAABJRU5ErkJggg=='
			// ]);
			
			
			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		if($r["code"]=='smsetcgateway'){
			$doResult = BxRest::call('messageservice.sender.delete',[
				'CODE' => 'smsetc'
			]);

			return array( 'do' => $doResult, 'result' => 'success'); 
		}
		
		return 'code not found';
	}
	
	
	private function alovoice_update_dongles_accounts($r=[]) {
		return ALVC::ralv("alovoice_update_dongles_accounts",$r);
		// $alvActions = new AloVoiceActions($this->config);
		// if(!empty($params["device"])){
			// $resUpdateDongles = $alvActions->updateOneDongleAccount($params);
		// } else {
			// $resUpdateDongles = $alvActions->updateDonglesAccount();
		// }
		
		// return $resUpdateDongles;
	}
	
	private function alovoice_dongle_channels($r=false) {
		$res = ALVC::ralv("alovoice_dongle_channels");
		// $alvActions = new AloVoiceActions($this->config);
		return $res; //['gsmlines' => $alvActions->getDongles() ];
	}
	
	private function ctest($r=false) {
		$doResult = BxRest::call('im.chat.get',[
			'ENTITY_ID' => (!empty($r['e'])) ? $r['e'] : 'CONTACT|19284',
			//'ENTITY_TYPE' => 'LIVECHAT'
		]);
		// $doResult = BxRest::call('catalog.product.getFieldsByFilter');
		
		return ['cres' => $doResult ];
	}
	
	private function testmtd($r=false) {
		$method = $r["method"];
		$r["method"] = null;
		unset($r["method"]);
		
		if(!empty($r)){
			$arResults = BxRest::call($method,$r);
		}
		else {
			$arResults = BxRest::call($method);
		}
		
		
		//return $this->configv["alovoice_host"];
		//return $r;
		/*
		$arResults = BxRest::call('crm.activity.type.add',[
			'fields' =>[
				'TYPE_ID' => 'alosms',
				'NAME' => 'Входящий SMS - AloSMS',
				'ICON_FILE' => 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAAAAAAbPrZOAAAVE0lEQVQYGeXAC2DNdeM/8PfZZht28SCwAIGIBKkewJMCAyj9qCAQgCWRSg/EskKI9O8RIQS6oYCUKICIpAZGgG02287e/13O93wvn8/3fM8u7Bx7gfkMmM+A+QyYz4D5DJjPgPkMmM+A+QyYz4B3SezhDbNfHfjs042qly1ZNDjQxycwuGjJsjUea/3swHEffHUkjncJeIfFHVo/a1SXesVgoXj9LqNnbzgUzzsMvHNu/zK3d00fZInvQ33n/5rEOwe8I1KP/W9IwwBkU2CjoZ8eT+UdAea+YzNahiDHQltFnWTuA3PX7c3DKyPXVB21JYm5C8xFMR93DkYuC+n2ySXmIjC3nJnc0IY7wqfROxeYW8BckbS6jQ/uIL/wdcnMFWAuOB5RAndc6VdPMBeAORX/yb9xlzRZfIs5BebMsQEhuItCB51kzoA5cfgZH9xlvj1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F+21LplcAMMQFwX7E+X9+mtwIzTIC7Sg36LpleDEwXXxRuKTt8h53eDUw3G26oM253Kr0emCalEiwEd1p4lvcEMM1KuFRj9PdJvFeAaRrCVGj7D07zXgKSGyFX6MmpP6fwHgOS/4bIv/Eb22/zHgRyCwwKNhm3KZ73KJDNoVGma9TPSbyHgTvh4Pvw4KWnea8DWwGwPdBj5o445gf4tfbzUVuvMd8A8xkwnwHzGTCfAfMZMJ8B8xkwnwHzGTCf+f+lxugxz/9YKwAAAABJRU5ErkJggg=='
			]
		]);
		*/
		//$arResults = BxRest::call('crm.activity.type.delete',['TYPE_ID'=>'alosms']);
		//$arResults = BxRest::call('crm.enum.activitydirection');
		//$arResults = BxRest::call('crm.enum.contenttype');
		//$arResults = BxRest::call('crm.enum.activitypriority');
		//$arResults = BxRest::call('crm.enum.activitytype');
		//$arResults = BxRest::call('user.current',['PHONE_NUMBER'=>'+998994412860']);
		//$arResults = BxRest::call('telephony.externalCall.searchCrmEntities',['PHONE_NUMBER'=>'+998994412860']);
		return $arResults;
	}
}