<?php
namespace Models;

// модель для чеков
class Egais {
	public $db, $f3, $web, $url_egais, $sets, $api_data;
	public $state=array(
		0=>'Новый',
		2=>'Отправлено'
	);

	public $types=array(
		'replypartner'=>array('title'=>'Справочник организации', 'schema'=>'ReplyPartner.xsd'),
		'form2reginfo'=>array('title'=>'Квитанция о регистрации справок 2 для Товарно-Транспортной Накладной', 'schema'=>'TTNInformF2Reg.xsd'),
		'replynattn'=>array('title'=>'Список неподтвержденных накладных', 'schema'=>'ReplyNoAnswerTTN.xsd'),
		'WayBillTicket'=>array('title'=>'Подтверждение акта разногласий для Товарно-Транспортной Накладной', 'schema'=>'ConfirmTicket.xsd'),
		"ActChargeOn_v2"=>array("title"=>"Акт постановки на баланс", "schema"=>"ActChargeOn_v2.xsd"),
		"ActInventoryInformF2Reg"=>array("title"=>"Информация по справке 2 акта постановки на баланс", "schema"=>"ActInventoryInformF2Reg.xsd"),
		"ActWriteOff_v2"=>array("title"=>"Акт списания", "schema"=>"ActWriteOff_v2.xsd"),
		"QueryAP_v2"=>array("title"=>"Запрос справочника АП", "schema"=>"QueryParameters.xsd"),
		"QueryClients_v2"=>array("title"=>"Запрос справочника организаций", "schema"=>"QueryParameters.xsd"),
		"QueryClientVersion"=>array("title"=>"Запрос информации по клиенту на дату", "schema"=>"QueryParameters.xsd"),
		"QueryForm2History"=>array("title"=>"Запрос истории по справке 2", "schema"=>"QueryParameters.xsd"),
		"QueryFormF1"=>array("title"=>"Запрос справки 1", "schema"=>"QueryFormF1F2.xsd"),
		"QueryFormF2"=>array("title"=>"Запрос справки 2", "schema"=>"QueryFormF1F2.xsd"),
		"QueryRejectRepImported"=>array("title"=>"Запрос на отмену проводки отчета о импорте продукции", "schema"=>"QueryRejectRepImported.xsd"),
		"QueryRejectRepProduced"=>array("title"=>"Запрос на отмену проводки отчета о производстве", "schema"=>"QueryRejectRepProduced.xsd"),
		"QueryRests_v2"=>array("title"=>"Запрос остатков", "schema"=>"QueryParameters.xsd"),
		"QuerySP_v2"=>array("title"=>"Запрос справочника спирта", "schema"=>"QueryParameters.xsd"),
		"QuerySSP_v2"=>array("title"=>"Запрос справочника ССП", "schema"=>"QueryParameters.xsd"),
		"QuRepImportedProducterySSP_v2"=>array("title"=>"Отчет об импорте продукции", "schema"=>"RepImportedProduct.xsd"),
		"ReplyAP_v2"=>array("title"=>"Ответ на запрос справочника продукции", "schema"=>"ReplyAP_v2.xsd"),
		"ReplyClient_v2"=>array("title"=>"Ответ на запрос справочника организаций", "schema"=>"ReplyClient_v2.xsd"),
		"ReplyClientVersion"=>array("title"=>"Ответ на запрос информации по клиенту на дату", "schema"=>"ReplyClientVersion.xsd"),
		"ReplyForm1"=>array("title"=>"Ответ на запрос справки 1", "schema"=>"ReplyForm1.xsd"),
		"ReplyForm2"=>array("title"=>"Ответ на запрос справки 2", "schema"=>"ReplyForm2.xsd"),
		"ReplyHistForm2"=>array("title"=>"Ответ на запрос истории по справке 2", "schema"=>"ReplyHistForm2.xsd"),
		"ReplyRests_v2"=>array("title"=>"Ответ на запрос остатков", "schema"=>"ReplyRests_v2.xsd"),
		"ReplySpirit_v2"=>array("title"=>"Ответ на запрос справочника спирта", "schema"=>"ReplySpirit_v2.xsd"),
		"ReplySSP_v2"=>array("title"=>"Ответ на запрос справочника ССП", "schema"=>"ReplySSP_v2.xsd"),
		"RepProducedProduct"=>array("title"=>"Отчет о производстве", "schema"=>"RepProducedProduct.xsd"),
		"TransferFromShop"=>array("title"=>"Возврат продукции из торгового зала на склад", "schema"=>"TransferFromShop.xsd"),
		"TransferToShop"=>array("title"=>"Передача продукции в торговый зал", "schema"=>"TransferToShop.xsd"),
		"TTNInformF2Reg"=>array("title"=>"Информация по справке 2", "schema"=>"TTNInformF2Reg.xsd"),
		"WayBill_v2"=>array("title"=>"Накладная", "schema"=>"TTNSingle_v2.xsd"),
		"WayBillAct_v2"=>array("title"=>"Акт разногласий по накладной", "schema"=>"TNActSingle_v2.xsd"),
		"RepInformF1Reg"=>array("title"=>"Информация по справке 1", "schema"=>"RepInformF1Reg.xsd"),
		"QueryNATTN"=>array("title"=>"Запрос необработанных ТТН", "schema"=>"QueryParameters.xsd"),
		"ReplyNoAnswerTTN"=>array("title"=>"Ответ на запрос необработанных ТТН", "schema"=>"ReplyNoAnswerTTN.xsd"),
		"QueryRestsShop_v2"=>array("title"=>"Запрос остатков в торговом зале", "schema"=>"QueryParameters.xsd"),
		"ReplyRestsShop_v2"=>array("title"=>"Ответ на запрос остатков в торговом зале", "schema"=>"ReplyRestsShop_v2.xsd"),
		"Asiiu"=>array("title"=>"Загрузка данных от автоматических средств измерения (за период)", "schema"=>"Asiiu.xsd"),
		"ActChargeOnShop_v2"=>array("title"=>"Акт постановки на баланс в торговом зале", "schema"=>"ActChargeOnShop_v2.xsd"),
		"ActWriteOffShop_v2"=>array("title"=>"Акт списания из торгового зала", "schema"=>"ActWriteOffShop_v2.xsd"),
		"AsiiuTime"=>array("title"=>"Загрузка данных от автоматических средств измерения (состояние на момент времени)", "schema"=>"AsiiuTime.xsd"),
		"InfoVersionTTN"=>array("title"=>"Информация о используемой версии формата ТТН", "schema"=>"InfoVersionTTN.xsd"),
		"QueryBarcode"=>array("title"=>"Запрос на получение штрихкода по серии и номеру марки", "schema"=>"QueryBarcode.xsd"),
		"ReplyBarcode"=>array("title"=>"Ответ на запрос штрихкода по серии и номеру марки", "schema"=>"ReplyBarcode.xsd"),
		"RequestRepealWB"=>array("title"=>"Запрос на отмену проведения ТТН от грузополучателя", "schema"=>"RequestRepealWB.xsd"),
		"ConfirmRepealWB"=>array("title"=>"Подтверждение запроса на отмену проведения ТТН (оформляет грузоотправитель)", "schema"=>"ConfirmRepealWB.xsd"),
		"RequestRepealACO"=>array("title"=>"Запрос на отмену проведения акта постановки на баланс", "schema"=>"RequestRepealACO.xsd"),
		"RequestRepealAWO"=>array("title"=>"Запрос на отмену проведения акта списания с баланса", "schema"=>"RequestRepealAWO.xsd"),
		"QueryRestsShop_Mini"=>array("title"=>"Запрос остатков (без справочников) в торговом зале", "schema"=>"QueryRestsShop_Mini.xsd"),
		"ReplyRestsShop_Mini"=>array("title"=>"Ответ на запрос остатков (без справочников) в торговом зале", "schema"=>"ReplyRestsShop_Mini.xsd"),
		"QueryRests_Mini"=>array("title"=>"Запрос остатков (без справочников) по складу", "schema"=>"QueryParameters.xsd"),
		"ReplyRests_Mini"=>array("title"=>"Ответ на запрос (без справочников) остатков по складу", "schema"=>"ReplyRests_Mini.xsd"),
		"RequestAddFProducer"=>array("title"=>"Запрос на добавление иностранного производителя", "schema"=>"RequestAddForeignProducer.xsd"),
		"RequestAddProducts"=>array("title"=>"Запрос на добавление новой продукции", "schema"=>"RequestAddProducts.xsd"),
		"QueryHistoryRestShop"=>array("title"=>"Запрос истории движения между 1 и 2 регистрами", "schema"=>"QueryParameters.xsd"),
		"ReplyHistoryShop"=>array("title"=>"Ответ на Запрос истории движения между 1 и 2 регистрами", "schema"=>"ReplyHistoryShop.xsd"),
		"QueryWriteOffCheque"=>array("title"=>"Запрос количества обработанных чеков", "schema"=>"QueryParameters.xsd"),
		"ReplyWriteOffCheque"=>array("title"=>"Ответ на запрос количества обработанных чеков", "schema"=>"ReplyWriteOffCheque.xsd"),
		"AsiiuTimeSign"=>array("title"=>"Загрузка данных от автоматических средств измерения (состояние на момент времени)", "schema"=>"AsiiuTime.xsd"),
		"AsiiuSign"=>array("title"=>"Загрузка данных от автоматических средств измерения (за период)", "schema"=>"Asiiu.xsd"),
		"ASCPNavigation"=>array("title"=>"Данные от АСКП", "schema"=>"ASCPNavigation.xsd"),
		"WayBill_v3"=>array("title"=>"Накладная", "schema"=>"TTNSingle_v3.xsd"),
		"ActWriteOff_v3"=>array("title"=>"Акт списания", "schema"=>"ActWriteOff_v3.xsd"),
		"RepProducedProduct_v3"=>array("title"=>"Отчет о производстве", "schema"=>"RepProducedProduct_v3.xsd"),
		"RepImportedProduct_v3"=>array("title"=>"Отчет об импорте продукции", "schema"=>"RepImportedProduct_v3.xsd"),
		"WayBillAct_v3"=>array("title"=>"Акт разногласий по накладной", "schema"=>"TTNActSingle_v3.xsd"),
		"QueryRestBCode"=>array("title"=>"Запрос остатков штрихкодов по идентификатору справки 2", "schema"=>"QueryParameters.xsd"),
		"ReplyRestBCode"=>array("title"=>"Ответ на Запрос остатков штрихкодов по коду продукции", "schema"=>"ReplyRestBCode.xsd"),
		"ActFixBarCode"=>array("title"=>"Акт фиксации штрихкодов на балансе организации", "schema"=>"ActFixBarCode.xsd"),
		"ActUnFixBarCode"=>array("title"=>"Акт отмены фиксации штрихкодов на балансе организации", "schema"=>"ActUnFixBarCode.xsd"),
		"TTNHistoryF2Reg"=>array("title"=>"История движения формы 2 при регистрации ТТН", "schema"=>"TTNHistoryF2Reg.xsd"),
		"CarrierNotice"=>array("title"=>"Уведомление о перевозке", "schema"=>"CarrierNotice.xsd"),
		"QueryParentHistForm2"=>array("title"=>"Запрос на получение истории движения по форме 2", "schema"=>"QueryParameters.xsd"),
		"ReplyParentHistForm2"=>array("title"=>"Ответ на запрос получения истории движения по форме 2", "schema"=>"ReplyParentHistForm2.xsd"),
		"ClaimIssueFSM"=>array("title"=>"Заявление о выдаче ФСМ", "schema"=>"ReplClaimIssueFSMyParentHistForm2.xsd"),
		"InvoiceExportFSM"=>array("title"=>"Квитанция о вывозе ФСМ за пределы РФ", "schema"=>"InvoiceExportFSM.xsd"),
		"InvoicePlannedImport"=>array("title"=>"Квитанция о планируемом ввозе АП", "schema"=>"InvoicePlannedImport.xsd"),
		"NotificationsBeginningTurnover"=>array("title"=>"Уведомление о начале оборота АП", "schema"=>"NotificationsBeginningTurnover.xsd"),
		"RecheckNotificationsFSM"=>array("title"=>"Уведомление о повторной проверке", "schema"=>"RecheckNotificationsFSM.xsd"),
		"RejectionNoticeFSM"=>array("title"=>"Уведомление об отказе в выдаче ФСМ", "schema"=>"RejectionNoticeFSM.xsd"),
		"RepImportedProduct_v4"=>array("title"=>"Отчет об импорте продукции", "schema"=>"RepImportedProduct_v4.xsd"),
		"ReportDestructionAMFSM"=>array("title"=>"Отчет об уничтожении АМ/ФСМ", "schema"=>"ReportDestructionAMFSM.xsd"),
		"RepProducedProduct_v4"=>array("title"=>"Отчет о производстве продукции", "schema"=>"RepProducedProduct_v4.xsd"),
		"RequestRepealEAM"=>array("title"=>"Запрос на отмену квитанции о вывозе АМ за пределы РФ", "schema"=>"RequestRepealEAM.xsd"),
		"RequestRepealIPI"=>array("title"=>"Запрос на отмену квитанции о планируемом ввозе продукции", "schema"=>"RequestRepealIPI.xsd"),
		"ReturnNoticeFSM"=>array("title"=>"Уведомление о возврате ФСМ", "schema"=>"ReturnNoticeFSM.xsd"),
		"TTNIssueFSM"=>array("title"=>"Накладная на выдачу ФСМ заявителю", "schema"=>"TTNIssueFSM.xsd"),
		"TTNIssueReturnFSM"=>array("title"=>"Накладная на возврат ФСМ заявителем", "schema"=>"TTNIssueReturnFSM.xsd"),
		"WayBill_v4"=>array("title"=>"Товарно-Транспортная Накладная", "schema"=>"TTNSingle_v4.xsd"),
		"WayBillAct_v4"=>array("title"=>"Акт разногласий для Товарно-Транспортной Накладной", "schema"=>"TTNActSingle_v4.xsd"),
		"Route"=>array("title"=>"Транспортная Накладная", "schema"=>"Route.xsd"),
		"CancelRoute"=>array("title"=>"Отмена транспортной накладной", "schema"=>"CancelRoute.xsd"),
		"ChequeV3"=>array("title"=>"Чек, чек возврата, розница по безналу", "schema"=>"ChequeV3.xsd"),
		"DebtAbsence"=>array("title"=>"Справка", "schema"=>"DebtAbsence.xsd"),
		"RequestAdjustmentData"=>array("title"=>"Заявление на корректировку данных", "schema"=>"RequestAdjustmentData.xsd"),
		"УПД_True"=>array("title"=>"Универсальный передаточный документ", "schema"=>"УПД_True.xsd"),
		"RequestBalanceTransfer"=>array("title"=>"Заявка на перенос остатков", "schema"=>"RequestBalanceTransfer.xsd"),
	);

	public $q=array(
		1=>3,
		2=>6,
		3=>9,
		4=>0
	);

	public function __construct($db, $f3) {
		$this->db=$db;
		$this->f3=$f3;
		$this->sets=$this->get_settings();
		$this->url_egais=$this->sets['url_egais'];
		$this->web=\Web::instance();
		$this->api_data=$this->f3->get('api_data');
		$this->logs=$this->f3->get('logs_model');
	}

	function GUID() {
        $guid=date('Ymd').'-'.date('Y').'-'.date('md').'-'.date('Hi').'-'.sprintf("%'.012d", time());
        return $guid;
	}

	// данные о страницах
	function page_data($page='api') {
		$pages=array(
			'main'=>array(
				'title'=>'Входящие документы ЕГАИС',
				'inc'=>'egais_main.htm'
			),
			'ticket'=>array(
				'title'=>'Просмотр документа ЕГАИС',
				'inc'=>'egais_ticket.htm'
			),
			'utminfo'=>array(
				'title'=>'Служебная информация',
				'inc'=>'egais_utminfo.htm'
			),
			'ttnact'=>array(
				'title'=>'Принять/Отменить ТТН',
				'inc'=>'egais_ttnact.htm'
			),
			'ttnact_repeal'=>array(
				'title'=>'Отменить проведение накладной',
				'inc'=>'egais_ttnact_repeal.htm'
			),
			'writeoff'=>array(
				'title'=>'Списание',
				'inc'=>'egais_writeoff.htm'
			),
			'writeoff_repeal'=>array(
				'title'=>'Списание',
				'inc'=>'egais_writeoff_repeal.htm'
			),
			'ttn'=>array(
				'title'=>'Товарно-Транспортная Накладная',
				'inc'=>'egais_ttn.htm'
			),
			'organizations'=>array(
				'title'=>'Поиск организации а ЕГАИС',
				'inc'=>'egais_organizations.htm'
			),
			'beer_currentstock'=>array(
				'title'=>'Актуализировать остатки пива',
				'inc'=>'egais_beer_currentstock.htm'
			),
			'waybill_v4'=>array(
				'title'=>'Просмотр ТТН ЕГАИС',
				'inc'=>'egais/waybill_v4.htm'
			),
			'replyrests'=>array(
				'title'=>'Остатки по ЕГАИС',
				'inc'=>'egais/replyrests.htm'
			),
			'replynattn'=>array(
				'title'=>'Список неподтвержденных накладных',
				'inc'=>'egais/replynattn.htm'
			),
			'replyrestbcode'=>array(
				'title'=>'Остатки по идентификатору справки 2',
				'inc'=>'egais/replyrestbcode.htm'
			),
			'related'=>array(
				'title'=>'Связанные документы',
				'inc'=>'egais_related.htm'
			),
			'send_ttn'=>array(
				'title'=>'Принять товар по ТТН',
				'inc'=>'egais_send_ttn.htm'
			),
			'send_replyrests'=>array(
				'title'=>'Создать инвентаризацию по остаткам',
				'inc'=>'egais_send_replyrests.htm'
			),
			'declaration'=>array(
				'title'=>'Алкодекларации',
				'inc'=>'egais_declaration.htm'
			),
			'searchindocs'=>array(
				'title'=>'Поиск продукции по алкокоду в документах',
				'inc'=>'egais_searchindocs.htm'
			),
		);
		$pages[$page]['page']=$page;

		return $pages[$page];
	}

	function get_settings() {
		$settings=new \Models\Settings($this->f3, $this->db);
		return $settings->get_settings(array('egais', 'url_egais', 'fsrar_id', 'egais_alarm'));
	}

	// Верификация марки
	function mark_check($code) {
		$options = array(
			'method'=>'GET'
		);
		$request=$this->web->request($this->url_egais.'/api/mark/check?code='.$code, $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if($body['owner']===true) {
				return array(
					'success'=>true,
					'code'=>$code
				);
			}
			$txt="Акцизная марка ".$code." не найдена на балансе. Попробуйте еще раз. Если ошибка повторяется, возьмите другую бутылку.";
			$this->logs->save_log("ЕГАИС\n\n".$txt);
			return array(
				'success'=>false,
				'txt'=>$txt
			);
		}
		if($body['message']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['message']);
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}

		if($body['error']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['error']);
			return array(
				'success'=>false,
				'txt'=>$body['error']
			);
		}

		if($request['body']!='') {
			$this->logs->save_log("ЕГАИС\n\n".$request['body']);
			return array(
				'success'=>false,
				'txt'=>strip_tags($request['body'])
			);
		}

		$this->logs->save_log("ЕГАИС\n\n".implode(';', $request));
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	// Информация о выданном сертификате RSA
	function get_rsa() {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/rsa/orginfo', $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if($body['cn']) {
				return array(
					'success'=>true,
					'cn'=>$body['cn']
				);
			}
			$txt='Не удалось получить информацию о RSA-сертификате';
			$this->logs->save_log("ЕГАИС\n\n".$txt);
			return array(
				'success'=>false,
				'txt'=>$txt
			);
		}
		if($body['error']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['message']);
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		$this->logs->save_log("ЕГАИС\n\n".implode(';', $request));
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	// Информация об организации
	function orginfo() {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/gost/orginfo', $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if(isset($body['cn'])) {
				return array(
					'success'=>true,
					'data'=>$body
				);
			}
			else {
				$txt='Не удается получить информацию об организации';
				$this->logs->save_log("ЕГАИС\n\n".$txt);
				return array(
					'success'=>false,
					'txt'=>$txt
				);
			}
			$this->logs->save_log("ЕГАИС\n\nОшибка");
			return array(
				'success'=>false,
				'txt'=>'error'
			);
		}
		if($body['message']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['message']);
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		if($body['error']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['error']);
			return array(
				'success'=>false,
				'txt'=>$body['error']
			);
		}
		$this->logs->save_log("ЕГАИС\n\n".implode(';',$request));
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	function receipt_writeoff($receipt_id, $lines, $TypeWriteOff) {
		return array(
			'success'=>true,
			'egais_xml'=>'',
			'writeoff'=>array('receipts'=>array(0=>$this->writeoff_v4($receipt_id, $lines, $TypeWriteOff)))
		);
	}



	// Списание
	function writeoff_v4($receipt_id, $lines, $TypeWriteOff='Приготовление') {

		$writeoff_lines=array();

		foreach($lines as $n=>$line) {
			if(((int)$line['egais']==1 && !$line['mark']) || (int)$line['egais']<1) continue;
			$count=$line['count'];
			if((int)$line['unit_okei']==116) {
				$count*=10000;
				$line['unit_okei']=111;
			}
			elseif((int)$line['unit_okei']==112){
				$count*=1000;
				$line['unit_okei']=111;
			}
			if((int)$line['egais']==1) {
				if(isset($writeoff_lines[$line['mark']])) {
					$writeoff_lines[$line['mark']]['count']+=$line['count'];
				}
				else {
					$writeoff_lines[$line['mark']]=$line;
				}
			}
			elseif((int)$line['egais']==2 && (int)$line['unit_okei']==796) {
				$writeoff_lines['beer_'.$n]=$line;
			}
		}

		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:pref=\"http://fsrar.ru/WEGAIS/ProductRef_v2\" xmlns:awr=\"http://fsrar.ru/WEGAIS/ActWriteOff_v4\" xmlns:ce=\"http://fsrar.ru/WEGAIS/CommonV3\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$this->sets['fsrar_id']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:ActWriteOff_v4>\n";
		$xml.="<awr:Identity>".$receipt_id."</awr:Identity>\n";
		$xml.="<awr:Header>\n";
		$xml.="<awr:ActNumber>".$receipt_id."</awr:ActNumber>\n";
		$xml.="<awr:ActDate>".date('Y-m-d')."</awr:ActDate>\n";
		$xml.="<awr:TypeWriteOff>".$TypeWriteOff."</awr:TypeWriteOff>\n";
		$xml.="</awr:Header>\n";
		$xml.="<awr:Content>\n";
		$Content=false;
		$key=1;
		$beer_formb=array();
		if(!empty($writeoff_lines)) {
			$lines=array();
			foreach($writeoff_lines as $line) {
				if($line['mark']!='' || ((int)$line['egais']==2 && (int)$line['unit_okei']==796)) {
					$line['mark']=json_decode($line['mark'], true)[0];
					$formb=array();
					if(!$line['FormB']) {
						if((int)$line['egais']==1) {
							$formb=$this->db->exec("SELECT * FROM egais_marks WHERE mark=? LIMIT 1", $line['mark']);
						}
						elseif((int)$line['egais']==2) {
							if(!isset($beer_formb[$line['product_id']])) {
								$beer_formb[$line['product_id']]=$this->db->exec("SELECT * FROM egais_formb WHERE product_id=?", $line['product_id']);
							}
							if(isset($beer_formb[$line['product_id']])) {
								foreach($beer_formb[$line['product_id']] as $fn=>$f) {
									if($f['count']>=$line['count']) {
										$beer_formb[$line['product_id']][$fn]['count']-=$line['count'];
										$formb=array(
											array(
												'FormB'=>$f['FormB']
											)
										);
										break;
									}
								}
							}
						}
						if(empty($formb)) $formb[0]['FormB']='PID-'.$line['product_id'];
						$line['FormB']=$formb[0]['FormB'];
					}
					$lines[]=$line;
				}
			}

			if(!empty($lines)) {
				$result_lines=array();
				foreach($lines as $line) {
					if($line['egais']==1) $result_lines[$line['FormB']]=$line;
					else {
						if(isset($result_lines[$line['FormB']])) {
							$result_lines[$line['FormB']]['count']+=$line['count'];
						}
						else {
							$result_lines[$line['FormB']]=$line;
						}
					}
				}

				foreach($result_lines as $line) {
					$xml.="<awr:Position>\n";
					$xml.="<awr:Identity>".$key."</awr:Identity>\n";

					$xml.="<awr:writeoffvolume>\n";
					if((int)$line['unit_okei']==796) {
						$xml.="<awr:Quantity>".number_format($line['count'], 5, '.', '')."</awr:Quantity>\n";
					}
					else{
						$volume=$line['count'];
						if((int)$position['unit_okei']==116) {
							$volume*=10000;
						}
						elseif((int)$line['unit_okei']==112){
							$volume*=1000;
						}
						$xml.="<awr:volume>".round($volume)."</awr:volume>\n";
					}
					$xml.="</awr:writeoffvolume>\n";
					if($TypeWriteOff=='Реализация') {
						$xml.="<awr:SumSale>".number_format($line['sum']*$line['count'], 2, '.', '')."</awr:SumSale>";
					}

					$xml.="<awr:InformF1F2>\n";
					$xml.="<awr:InformF2>\n";
					$xml.="<pref:F2RegId>".$line['FormB']."</pref:F2RegId>\n";
					$xml.="</awr:InformF2>\n";
					$xml.="</awr:InformF1F2>\n";
					if((int)$line['egais']==1) {
						$xml.="<awr:MarkCodeInfo>\n";
						$xml.="<ce:amc>".$line['mark']."</ce:amc>\n";
						$xml.="</awr:MarkCodeInfo>\n";
					}
					$xml.="</awr:Position>\n";
					$Content=true;
					$key++;
				}
			}
		}
		$xml.="</awr:Content>\n";
		$xml.="</ns:ActWriteOff_v4>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";
		if(!empty($beer_formb)) {
			foreach($beer_formb as $forms) {
				foreach($forms as $f) {
					$this->db->exec("UPDATE egais_formb SET count=? WHERE FormB=?", array($f['count'], $f['FormB']));
				}
			}
		}
		return array(
			'success'=>true,
			'writeoff_xml'=>$Content?$xml:'',
			'state'=>0
		);
	}

	// Списание
	function writeoff_v3($receipt_id, $lines, $TypeWriteOff='Приготовление') {
		$writeoff_lines=array();

		foreach($lines as $n=>$line) {
			if(((int)$line['egais']==1 && !$line['mark']) || (int)$line['egais']<1) continue;
			$writeoff_lines[]=$line;
		}

		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:pref=\"http://fsrar.ru/WEGAIS/ProductRef_v2\" xmlns:awr=\"http://fsrar.ru/WEGAIS/ActWriteOff_v3\" xmlns:ce=\"http://fsrar.ru/WEGAIS/CommonV3\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$this->sets['fsrar_id']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:ActWriteOff_v3>\n";
		$xml.="<awr:Identity>".$receipt_id."</awr:Identity>\n";
		$xml.="<awr:Header>\n";
		$xml.="<awr:ActNumber>".$receipt_id."</awr:ActNumber>\n";
		$xml.="<awr:ActDate>".date('Y-m-d')."</awr:ActDate>\n";
		$xml.="<awr:TypeWriteOff>".$TypeWriteOff."</awr:TypeWriteOff>\n";
		$xml.="</awr:Header>\n";
		$xml.="<awr:Content>\n";
		$Content=false;
		$key=1;
		$beer_formb=array();
		if(!empty($writeoff_lines)) {
			$lines=array();
			foreach($writeoff_lines as $ln=>$line) {
				$formb=array();
				if(!$line['FormB']) {
					if((int)$line['egais']==1) {
						$formb=$this->db->exec("SELECT * FROM egais_marks WHERE mark=? LIMIT 1", $line['mark']);
					}
					elseif((int)$line['egais']==2) {
						if(!isset($beer_formb[$line['product_id']])) {
							$beer_formb[$line['product_id']]=$this->db->exec("SELECT * FROM egais_formb WHERE product_id=?", $line['product_id']);
							if($beer_formb[$line['product_id']]['beer_capacity']==0) $line['count']/=10;
							else $line['count']=1;
							$lines[$ln]['count']=$line['count'];
						}
						if(isset($beer_formb[$line['product_id']])) {
							foreach($beer_formb[$line['product_id']] as $fn=>$f) {
								if($f['count']>=$line['count']) {
									$beer_formb[$line['product_id']][$fn]['count']-=$line['count'];
									$formb=array(
										array(
											'FormB'=>$f['FormB']
										)
									);
									break;
								}
							}
						}
					}
					if(empty($formb)) $formb[0]['FormB']='PID-'.$line['product_id'];
					$line['FormB']=$formb[0]['FormB'];
				}
				$lines[]=$line;
			}

			if(!empty($lines)) {
				$result_lines=array();
				foreach($lines as $line) {
					if(!$line['FormB']) continue;
					if($line['egais']==1) $result_lines[$line['FormB']]=$line;
					else {
						if(isset($result_lines[$line['FormB']])) {
							$result_lines[$line['FormB']]['count']+=$line['count'];
						}
						else {
							$result_lines[$line['FormB']]=$line;
						}
					}
				}

				foreach($result_lines as $line) {
					$xml.="<awr:Position>\n";
					$xml.="<awr:Identity>".$key."</awr:Identity>\n";
					$xml.="<awr:Quantity>".number_format($line['count'], 5, '.', '')."</awr:Quantity>\n";
					if($TypeWriteOff=='Реализация') {
						$xml.="<awr:SumSale>".number_format($line['price']*$line['count'], 2, '.', '')."</awr:SumSale>\n";
					}

					$xml.="<awr:InformF1F2>\n";
					$xml.="<awr:InformF2>\n";
					$xml.="<pref:F2RegId>".$line['FormB']."</pref:F2RegId>\n";
					$xml.="</awr:InformF2>\n";
					$xml.="</awr:InformF1F2>\n";
					$xml.="</awr:Position>\n";
					$Content=true;
					$key++;
				}
			}
		}
		$xml.="</awr:Content>\n";
		$xml.="</ns:ActWriteOff_v3>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";
		if(!empty($beer_formb)) {
			foreach($beer_formb as $forms) {
				foreach($forms as $f) {
					$this->db->exec("UPDATE egais_formb SET count=? WHERE FormB=?", array($f['count'], $f['FormB']));
				}
			}
		}

		$res=array(
			'success'=>true,
			'writeoff_xml'=>$Content?$xml:'',
			'state'=>0
		);

		return array(
			'success'=>true,
			'egais_xml'=>'',
			'writeoff'=>array('receipts'=>array(0=>$res))
		);
	}

	// Чек продажи версии 4
	function cheque_v4($change_id, $receipt_id, $lines, $return=false) {
		// Объединяем строки, проданные в розлив
		$writeoff=false;
		$bottle=array();
		$xml='';
		$writeoff_res=array();
		$beer_lines=array();
		$alc_lines=array();
		foreach($lines as $l) {
			if((int)$l['egais']<1) continue;
			$price=$l['price']+($l['price']*($l['vat']/100))*max(0, $l['vat_type']);
			$d_sum=$price*($l['discount']/100);
			$price-=$d_sum;
			$l['price']=round($price, 2);
			$l['sum']=$l['count']*$price;

			if($l['price']==0 && $l['parent_id']>0) {
				$alc_lines[]=$l;
				$writeoff=true;
				continue;
			}
			if((int)$l['egais']==2 && $l['unit_okei']==796) {
				$beer_lines[]=$l;
				$writeoff=true;
				continue;
			}
			if((int)$l['egais']==2) continue;
			$mark=json_decode($l['mark'])[0];
			$l['mark']=$mark;
			if(!isset($bottle[$mark])) {
				$bottle[$mark]=$l;
			}
			else {
				$bottle[$mark]['count']+=$l['count'];
				$bottle[$mark]['sum']+=$l['sum'];
			}
		}

		if($writeoff && !$return) {
			if($alc_lines) {
				$writeoff_res['receipts'][]=$this->writeoff_v4($receipt_id, $alc_lines);
			}
			if($beer_lines) {
				$writeoff_res['receipts'][]=$this->writeoff_v4($receipt_id, $beer_lines, 'Реализация');
			}
		}
		if(!empty($bottle)) {
			/*foreach($bottle as $n=>$b) {
				$b['price']=round($b['sum']/$b['count'], 2);
				$bottle[$n]=$b;
			}*/

			$error='';
			$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
			$xml.="<ns:Documents xmlns:c=\"http://fsrar.ru/WEGAIS/Common\" xmlns:ck=\"http://fsrar.ru/WEGAIS/ChequeV4\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:pref=\"http://fsrar.ru/WEGAIS/ProductRef_v2\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n";
	 		$xml.="<ns:Owner>\n";
	 		$xml.="<ns:FSRAR_ID>".$this->sets['fsrar_id']."</ns:FSRAR_ID>\n";
	 		$xml.="</ns:Owner>\n";
	 		$xml.="<ns:Document>\n";
	 		$xml.="<ns:ChequeV4>\n";
	 		$xml.="<ck:Identity>".$receipt_id."</ck:Identity>\n";
	 		$xml.="<ck:Header>\n";
	 		$xml.="<ck:Date>".date('Y-m-d').'T'.date('H:i:s').".000</ck:Date>\n";
	 		$xml.="<ck:Kassa>".$this->api_data['rm_id']."</ck:Kassa>\n";
	 		$xml.="<ck:Shift>".$change_id."</ck:Shift>\n";
	 		$xml.="<ck:Number>".$receipt_id."</ck:Number>\n";
	 		$xml.="<ck:Type>".($return?'Возврат':'Продажа')."</ck:Type>\n";
	 		$xml.="</ck:Header>\n";
	 		$xml.="<ck:Content>\n";

	 		foreach ($bottle as $l) {
				if((int)$l['unit_okei']!=112 && (int)$l['unit_okei']!=111 && (int)$l['unit_okei']!=796) {
					$error.='<p>У позиции "'.$l['product_title'].'" неверная единица измерения. Допустимы: миллилитр, литр, штука.</p>';
					continue;
				}

				if((int)$l['unit_okei']==796) {
					$item_type="Bottle";
					if($l['barcode']=='') {
						$barcodes=$this->db->exec("SELECT barcode FROM barcodes WHERE product_id=? LIMIT 1", $line['product_id']);
						if($barcodes) {
							$line['barcode']=$barcodes[0]['barcode'];
						}
					}
				}
				else {
					$item_type="Catering";
				}
				$xml.="<ck:".$item_type.">\n";
				$xml.="<ck:Barcode>".$l['mark']."</ck:Barcode>\n";
				if($l['barcode']!='') {
					$xml.="<ck:EAN>".$l['barcode']."</ck:EAN>\n";
				}
				if($item_type=='Catering') {
					$volume=$l['count'];
					if((int)$l['unit_okei']==116) {
						//$l['price']/=10000;
						$volume*=10000;
					}
					elseif((int)$l['unit_okei']==112) {
						//$l['price']/=1000;
						$volume*=1000;
					}
					$l['price']*=$l['count'];
				}

				$xml.="<ck:Price>".number_format(round($l['price'], 2), 2, '.', '')."</ck:Price>\n";

				if($item_type=='Catering') {
					$xml.="<ck:Volume>".(int)$volume."</ck:Volume>\n";
				}

				$xml.="</ck:".$item_type.">\n";
			}
	 		$xml.="</ck:Content>\n";
	 		$xml.="</ns:ChequeV4>\n";
	 		$xml.="</ns:Document>\n";
			$xml.="</ns:Documents>";
		}

		if((int)$this->sets['egais']==0 || $xml=='') {
			return array(
				'success'=>true,
				'egais_xml'=>$xml,
				'writeoff'=>$writeoff_res
			);
		}

		if($error!='') {
			$this->logs->save_log("ЕГАИС\n\n".$error);
			return array(
				'success'=>true,
				'egais_xml'=>$xml,
				'error'=>$error,
				'writeoff'=>$writeoff_res
			);
		}
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/xml?type=ChequeV4', $options);
		$egais_xml=$xml;
		unlink($xml_name);
		if(!is_array($body)) {
			$request['body']=str_replace("&'", "'", $request['body']);
			$xml='';

			libxml_use_internal_errors(true);
			$xml=simplexml_load_string($request['body']);
			libxml_clear_errors();
			if(!$xml) {
				$error=$request['body']?strip_tags($request['body']):'Нет ответа от УТМ';
				$this->logs->save_log("ЕГАИС\n\n".$error);
				return array(
					'success'=>$this->sets['egais_alarm']==0?true:false,
					'egais_xml'=>$egais_xml,
					'error'=>'Ошибка ЕГАИС: '.$error,
					'writeoff'=>$writeoff_res
				);
			}
		}
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if($xml->error!='') {
				$error=(string)$xml->error;
				$this->logs->save_log("ЕГАИС\n\n".$error);
				return array(
					'success'=>$this->sets['egais_alarm']==0?true:false,
					'egais_xml'=>$egais_xml,
					'error'=>'Ошибка ЕГАИС: '.$error,
					'writeoff'=>$writeoff_res
				);
			}
			return array(
				'url'=>(string) $xml->url,
				'egais_xml'=>$egais_xml,
				'writeoff'=>$writeoff_res,
				'sign'=>html_entity_decode((string) $xml->sign)
			);
		}
		if(is_array($body) && $body['error']) {
			$error=(string)$body['error'];
		}
		elseif($xml->error!='') {
			$error=(string)$xml->error;
		}
		else {
			$error=$request['body'];
		}
		$this->logs->save_log("ЕГАИС\n\n".$error);
		return array(
			'success'=>$this->sets['egais_alarm']==0?true:false,
			'egais_xml'=>$egais_xml,
			'error'=>'Ошибка ЕГАИС: '.$error,
			'writeoff'=>$writeoff_res
		);
	}

	// Чек продажи
	function cheque($change_id, $receipt_id, $lines, $return=false) {
		$error='';
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<Cheque inn=\"".$this->sets['inn']."\" datetime=\"".date('dmyHi')."\"";
		if($this->sets['kpp']!='') {
			$xml.=" kpp=\"".$this->sets['kpp']."\"";
		}
		$xml.=" kassa=\"".$this->api_data['rm_id']."\" address=\"".htmlentities($this->sets['org_address'])."\" name=\"".htmlentities($this->sets['org_name'])."\" number=\"".$receipt_id."\" shift=\"".$change_id."\">\n";

		// Объединяем строки, проданные в розлив
		$bottle=array();
		foreach($lines as $l) {
			$mark=json_decode($l['mark'])[0];
			$price=$l['price']+($l['price']*($l['vat']/100))*max(0, $l['vat_type']);
			$d_sum=$price*($l['discount']/100);
			$price-=$d_sum;
			if($return) {
				$price=-$price; // Для возвратных чеков указывается отрицательная цена
			}
			$l['price']=$price;
			$l['sum']=$l['count']*$price;
			$l['mark']=$mark;

			if(!isset($bottle[$mark])) {
				$bottle[$mark]=$l;
			}
			else {
				$bottle[$mark]['count']+=$l['count'];
				$bottle[$mark]['sum']+=$l['sum'];
			}
		}
		foreach($bottle as $n=>$b) {
			$b['price']=round($b['sum']/$b['count'], 2);
			$bottle[$n]=$b;
		}

		foreach ($bottle as $l) {
			if($l['egais']==1) {
				
				if($l['barcode']!='') {
					$ean='ean="'.$l['barcode'].'"';
				}
				else {
					$ean;
				}

				if((int)$l['unit_okei']==796) {
					$xml.="<Bottle barcode=\"".$l['mark']."\" ".$ean." price=\"".number_format(round($l['price'], 2), 2, '.', '')."\" />\n";
				}
				elseif((int)$l['unit_okei']==116 || (int)$l['unit_okei']==112 || (int)$l['unit_okei']==111) {
					$volume=$l['count'];
					if((int)$l['unit_okei']==116) {
						$l['price']/=10;
						$volume*=10;
					}
					elseif((int)$l['unit_okei']==111) {
						$l['price']*=1000;
						$volume/=1000;
					}
					$xml.="<Bottle barcode=\"".$l['mark']."\" ".$ean." price=\"".number_format(round($l['price'], 2), 2, '.', '')."\" volume=\"".number_format($volume, 4, '.', '')."\" />\n";
				}
				else {
					$error.='<p>У позиции "'.$l['product_title'].'" неверная единица измерения. Допустимы: миллилитр, литр, декалитр, штука.</p>';
				}
			}
		}
		$xml.="</Cheque>";
		if($error!='') {
			$this->logs->save_log("ЕГАИС\n\n".$error);
			echo $error;
			exit();
		}
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/xml?type=Cheque', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(!is_array($body)) {
			$request['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
		}
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if($xml->error!='') {
				$this->logs->save_log("ЕГАИС\n\n".$xml->error);
				echo $xml->error;
				exit();
			}
			return array(
				'url'=>(string) $xml->url,
				'sign'=>html_entity_decode((string) $xml->sign)
			);
		}
		if(is_array($body) && $body['error']) {
			$this->logs->save_log("ЕГАИС\n\n".$body['message']);
			echo $body['message'];
		}
		elseif($xml->error!='') {
			$this->logs->save_log("ЕГАИС\n\n".$xml->error);
			echo $xml->error;
		}
		else {
			$this->logs->save_log("ЕГАИС\n\n".$request['body']);
			echo $request['body'];
		}
		exit();
	}

	function tickets_types() {
		foreach($this->types as $key=>$value) {
			$types[mb_strtolower($key)]=$value;
		}
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/schema/list');
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if(is_array($body)) {
				foreach($body as $ticket) {
					$key=str_replace('.xsd', '', mb_strtolower($ticket['name']));
					if(isset($types[$key])) continue;
					$types[$key]=array('title'=>$ticket['description'], 'schema'=>$ticket['name']);
				}
				return array(
					'success'=>true,
					'data'=>$types
				);
			}
			else {
				return array(
					'success'=>false,
					'txt'=>'Не удается получить информацию'
				);
			}
			return array(
				'success'=>false,
				'txt'=>'error'
			);
		}
		if($body['message']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		if($body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['error']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	// Входящие документы
	function out_list($limit, $offset) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/db/out/list?limit='.$limit.'&offset='.$offset, $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if(isset($body['rows'])) {
				$types_data=$this->tickets_types();
				if($types_data['success']) {
					$types=$types_data['data'];
				}
				else {
					$types=array();
				}
				$tickets=array();

				foreach($body['rows'] as $r) {
					$r['docType']=mb_strtolower($r['docType']);
					if(isset($types[$r['docType']])) {
						$r['docTypeName']=$types[$r['docType']]['title'];
					}
					else {
						$r['docTypeName']=$r['docType'];
					}
					if(isset($this->state[(int)$r['state']])) {
						$r['stateName']=$this->state[(int)$r['state']];
					}
					else {
						$r['stateName']=$r['state'];
					}
					$tickets[]=$r;
				}
				return array(
					'success'=>true,
					'total'=>$body['total'],
					'receipts'=>$tickets
				);
			}
			else {
				return array(
					'success'=>false,
					'txt'=>'Не удается получить информацию'
				);
			}
			return array(
				'success'=>false,
				'txt'=>'error'
			);
		}
		if($body['message']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		if($body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['error']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	function schema($schemaName) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: text/xml'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/schema/'.$schemaName);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			return array(
				'success'=>true,
				'schema'=>$request['body']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request['headers'])
		);
	}

	function filtr_type($receipts, $types) {
		$filtr=array();
		$unfiltr=array();
		foreach($receipts as $r) {
			if(in_array(mb_strtolower($r['docType']), $types)) {
				$filtr[]=$r;
			}
			else {
				$unfiltr[]=$r;
			}
		}
		return array(
			'filtr'=>$filtr,
			'unfiltr'=>$unfiltr
		);
	}

	function ticket_xml($folder, $id) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: text/xml'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/db/'.$folder.'/'.$id);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			return array(
				'success'=>true,
				'xml'=>$request['body']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	function ticket($folder='out', $schemaName='Ticket', $id=0) {
		$xml=$this->ticket_xml($folder, $id);
		if(!$xml['success']) {
			return $xml;
		}

		$types=$this->tickets_types();
		if($types['success']) {
			$schemaName=$types['data'][mb_strtolower($schemaName)]['schema'];
		}
		else {
			$schemaName.='.xsd';
		}

		$schema=$this->schema($schemaName);
		if(!$schema['success']) {
			return array(
				'success'=>false,
				'txt'=>$xml['xml']
			);
		}
		$p=xml_parser_create();
		xml_parse_into_struct($p, $xml['xml'], $vals_xml, $index_xml);
		xml_parser_free($p);

		$p=xml_parser_create();
		xml_parse_into_struct($p, $schema['schema'], $vals_xsd, $index_xsd);
		xml_parser_free($p);
		$attr='';
		$params=array();
		foreach($vals_xsd as $val) {
			$tag=mb_strtoupper($val['tag']);
			if($tag=='XS:ELEMENT' && $val['type']=='open') {
				$attr=mb_strtolower($val['attributes']['NAME']);
				continue;
			}
			if($tag=='XS:DOCUMENTATION' && $val['type']=='complete' && $attr!='') {
				$params[$attr]=$val['value'];
				continue;
			}
		}
		$result=array();
		foreach($vals_xml as $val) {
			if($val['type']!='complete') continue;
			if($val['value']=='') continue;
			$tag=explode(':', mb_strtolower($val['tag']));
			if(count($tag)==1) {
				$tag_name=$tag[0];
			}
			else {
				$tag_name=$tag[1];
			}
			if(isset($params[$tag_name])) {
				$result[]=array(
					'title'=>$params[$tag_name],
					'value'=>$val['value']
				);
			}
			else {
				$result[]=array(
					'title'=>$tag_name,
					'value'=>$val['value']
				);
			}
		}
		return array(
			'success'=>true,
			'data'=>$result,
			'schema'=>$schemaName
		);
	}

	function rests() {
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:qp=\"http://fsrar.ru/WEGAIS/QueryParameters\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:QueryRests>\n";
		$xml.="</ns:QueryRests>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>";
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/QueryRests', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	// Остатки марок в форме Б в понятном виде
	function replyrestbcode($id) {
		$ticket=$this->ticket_xml('out', $id);
		if(!$ticket['success']) {
			return $ticket;
		}
		// Разбираем xml
		$rest=array();
		$xml=simplexml_load_string($ticket['xml']);
		$ns=array(
			'rst'=>'http://fsrar.ru/WEGAIS/ReplyRestBCode',
			'ns'=>'http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01',
			'ce'=>'http://fsrar.ru/WEGAIS/CommonV3'
		);
		$docs=$xml->children($ns["ns"]);
		$rst=$docs->Document->ReplyRestBCode->children($ns['rst']);
		$rest['RestsDate']=(string)$rst->RestsDate;
		$rest['Inform2RegId']=(string)$rst->Inform2RegId;
		if(isset($rst->MarkInfo)) {
			$ce=$rst->MarkInfo->children($ns["ce"]);
			$rest['MarkInfo']=(array)$ce->amc;
		}
		else {
			$rest['MarkInfo']=array();
		}
		return array(
			'success'=>true,
			'rest'=>$rest
		);
	}

	// Список не подтвержденных накладных в понятном виде
	function replynattn($id) {
		$ticket=$this->ticket_xml('out', $id);
		if(!$ticket['success']) {
			return $ticket;
		}
		// Разбираем xml
		$nattn=array();
		$xml=simplexml_load_string($ticket['xml']);
		$ns=array(
			'ttn'=>'http://fsrar.ru/WEGAIS/ReplyNoAnswerTTN',
			'ns'=>'http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01'
		);

		$docs=$xml->children($ns["ns"]);
		$ttn=$docs->Document->ReplyNoAnswerTTN->children($ns['ttn']);
		$nattn['ReplyDate']=(string)$ttn->ReplyDate;
		$ttnlist=(array)$ttn->ttnlist;
		if($ttnlist) {
			foreach($ttnlist as $t) {
				$nattn['NoAnswer'][]=(array)$t;
			}
		}
		return array(
			'success'=>true, 
			'nattn'=>$nattn
		);
	}

	function nattn() {
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:qp=\"http://fsrar.ru/WEGAIS/QueryParameters\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:QueryNATTN>\n";
		$xml.="<qp:Parameters>\n";
		$xml.="<qp:Parameter>\n";
		$xml.="<qp:Name>КОД</qp:Name>\n";
		$xml.="<qp:Value>".$utminfo['request']['ownerId']."</qp:Value>\n";
		$xml.="</qp:Parameter>\n";
		$xml.="</qp:Parameters>\n";
		$xml.="</ns:QueryNATTN>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";

		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/QueryNATTN', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function utminfo() {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$request=$this->web->request($this->url_egais.'/api/info/list');
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$res=json_decode($request['body'], true);
			$data=array(
				array('title'=>'Версия УТМ', 'value'=>$res['version']),
				array('title'=>'Контур', 'value'=>$res['contour']),
				array('title'=>'ФСРАР ID', 'value'=>$res['ownerId']),
				array('title'=>'Неотправленные чеки', 'value'=>$res['checkInfo']>0?$res['checkInfo']:'нет'),
				array('title'=>'Период действия ключа доступа к ЕГАИС', 'value'=>'С '.$res['rsa']['startDate'].' по '.$res['rsa']['expireDate']),
				array('title'=>'Период действия ГОСТ сертификата', 'value'=>'С '.$res['gost']['startDate'].' по '.$res['gost']['expireDate']),
			);
			return array(
				'success'=>true,
				'request'=>$res,
				'data'=>$data
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	// Формируем остатки в понятном виде
	function xml_to_rests($xml_str) {
		$xml=simplexml_load_string($xml_str);
		$ns=array(
			'rst'=>'http://fsrar.ru/WEGAIS/ReplyRests',
			'ns'=>'http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01',
			'pref'=>'http://fsrar.ru/WEGAIS/ProductRef',
			'oref'=>'http://fsrar.ru/WEGAIS/ClientRef',
			'xsi'=>'http://www.w3.org/2001/XMLSchema-instance'
		);
		$docs=$xml->children($ns["ns"]);
		$rst=$docs->Document->ReplyRests->children($ns["rst"]);
		$positions=array();
		if(isset($rst->Products->StockPosition)) {
			foreach($rst->Products->StockPosition as $p) {
				$position=(array)$p;
				$pref=$p->Product->children($ns['pref']);
				$position['Product']=(array)$pref;
				$oref=$pref->Producer->children($ns['oref']);
				$position['Product']['Producer']=(array)$oref;
				$positions[]=$position;
			}
		}
		$receipt=array(
			'RestsDate'=>$rst->RestsDate,
			'positions'=>$positions
		);
		return array(
			'success'=>true,
			'receipt'=>$receipt
		);
	}

	function rests_array($id) {
		$ticket=$this->ticket_xml('out', $id);
		if(!$ticket['success']) {
			return $ticket;
		}
		return $this->xml_to_rests($ticket['xml']);
	}

	// Формируем понятную ТТН
	function xml_to_ttn($xml_str) {
		// Разбираем xml
		$ttntypes=array('wbinvoicefromme'=>'расход', 'wbreturntome'=>'возврат мне', 'wbinvoicetome'=>'приход', 'wbreturnfromme'=>'возврат от меня', 'wbinternal'=>'внутренее перемещение');
		$ttn=array();
		$xml=simplexml_load_string($xml_str);
		$ns=array(
			'c'=>'http://fsrar.ru/WEGAIS/Common',
			'ce'=>'http://fsrar.ru/WEGAIS/CommonV3',
			'ns'=>'http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01',
			'oref'=>'http://fsrar.ru/WEGAIS/ClientRef_v2',
			'pref'=>'http://fsrar.ru/WEGAIS/ProductRef_v2',
			'wb'=>'http://fsrar.ru/WEGAIS/TTNSingle_v4',
			'xsi'=>'http://www.w3.org/2001/XMLSchema-instance'
		);
		$docs=$xml->children($ns["ns"]);
		$wb=$docs->Document->WayBill_v4->children($ns["wb"]);
		$ttn['identity']=(string)$wb->Identity;
		$ttn['number']=(int)$wb->Header->NUMBER;
		$ttn['date']=(string)$wb->Header->Date;
		$ttn['type']=$ttntypes[mb_strtolower((string)$wb->Header->Type)];
		$shipper=(array)$wb->Header->Shipper->children($ns["oref"]);
		$shipper=(array)array_shift($shipper);
		$shipper['address_data']=(array)$shipper['address'];
		$shipper['address']=(string)$shipper['address']->description;
		$ttn['shipper']=$shipper;
		$сonsignee=(array)$wb->Header->Consignee->children($ns["oref"]);
		$сonsignee=(array)array_shift($сonsignee);
		$сonsignee['address']=(string)$сonsignee['address']->description;
		$ttn['сonsignee']=$сonsignee;
		$ttn['products']=array();
		foreach($wb->Content->Position as $product) {
			$prod=(array)$product->Product->children($ns["pref"]);
			$prod['Identity']=(string)$product->Identity;
			$prod['Quantity']=(float)$product->Quantity;
			$prod['Price']=(float)$product->Price;
			$prod['FormA']=(string)$product->FARegId;
			$prod['FormB']=(string)$product->Party;
			$ce=(array)$product->InformF2->children($ns["ce"]);
			if(!$prod['FormB']) {
				$prod['FormB']=(string)$ce['F2RegId'];
			}
			$prod['MarkInfo']['amc']=(array)$ce['MarkInfo']->boxpos->amclist->amc;
			$producer=$prod['Producer']->children($ns["oref"]);
			if(isset($producer->UL)) {
				$prod['Producer']=(array)$producer->UL;
			}
			elseif(isset($producer->FL)) {
				$prod['Producer']=(array)$producer->FL;
			}
			elseif(isset($producer->TS)) {
				$prod['Producer']=(array)$producer->TS;
			}
			elseif(isset($producer->FO)) {
				$prod['Producer']=(array)$producer->FO;
			}

			$ttn['products'][$prod['Identity']]=$prod;
		}
		return array(
			'success'=>true, 
			'ttn'=>$ttn
		);
	}

	function ttn($id) {
		$ticket=$this->ticket_xml('out', $id);
		if(!$ticket['success']) {
			return $ticket;
		}
		return $this->xml_to_ttn($ticket['xml']);
	}

	function ttn_regid_from_id($ttn, $id) {
		$last=$this->out_list(1, 0);
		if(!$last['success']) {
			return $last;
		}
		$identity=$ttn['identity'];
		$reg_id='';
		$positions=array();
		$positions_history=array();
		$last_id=(int)$last['receipts'][0]['id'];
		$next_id=$id-50;
		//$types_data['TTNInformF2Reg']=$this->types['TTNInformF2Reg'];
		//$types_data['TTNHistoryF2Reg']=$this->types['TTNHistoryF2Reg'];
		while($next_id<=$last_id) {
			if($next_id==$id) {
				$next_id+=1;
				continue;
			}
			$ticket=$this->ticket_xml('out', $next_id);
			if(!$ticket['success']) {
				$next_id+=1;
				continue;
			}
			$xml=simplexml_load_string($ticket['xml']);
			$ns=$xml->getNamespaces(true);
			$docs=$xml->children($ns["ns"]);
			$type=array_key_first((array)$docs->Document);
			if($type=='TTNInformF2Reg' && $reg_id=='') {
				$wbr=$docs->Document->TTNInformF2Reg->children($ns["wbr"]);
				if(!isset($wbr->Header->Identity)) continue;
				$shipper=(array)$wbr->Header->Shipper->children($ns['oref']);
				$shipper=(array)array_shift($shipper);
				if($wbr->Header->Identity==$ttn['identity'] && $shipper['ClientRegId']==$ttn['shipper']['ClientRegId']) {
					foreach($wbr->Content->Position as $p) {
						$position[(string)$p->Identity]=(array)$p;
					}
					$next_id=$last_id+1;
					return array(
						'success'=>true,
						'regid'=>$wbr->Header->WBRegId,
						'position'=>$position
					);
				}
			}
			
			$next_id+=1;
		}
		return array(
			'success'=>true,
			'receipts'=>array_reverse($receipts)
		);
	}

	function ttn_regid($ttn, $id=false) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);

		if($id>0) {
			return $this->ttn_regid_from_id($ttn, $id);
		}

		//$types=array('formbreginfo', 'form2reginfo', 'replynoanswerttn', 'replynattn');
		$types=array('formbreginfo', 'form2reginfo');

		$stop=false;
		$limit=100;
		$offset=0;
		$end_time=time()-3600*24*30;
		while(!$stop) {
			$request=$this->web->request($this->url_egais.'/api/db/out/list?limit='.$limit.'&offset='.$offset, $options);
			if(mb_strpos($request['headers'][0], '200')===false && mb_strpos($request['headers'][1], '200')===false) {
				return array(
					'success'=>false,
					'txt'=>$request['body']
				);
			}
			$body=json_decode($request['body'], true);
			if(empty($body['rows'])) {
				$stop=true;
				break;
			}
			foreach($body['rows'] as $r) {
				if(strtotime($r['createTimestamp'])<$end_time) {
					$stop=true;
					break;
				}
				$r['docType']=mb_strtolower($r['docType']);
				if(!in_array($r['docType'], $types)) continue;
				$ticket=$this->ticket_xml('out', $r['id']);
				if(!$ticket['success']) continue;
				/*if($r['docType']=='replynoanswerttn' || $r['docType']=='replynattn') {
					$xml=simplexml_load_string($ticket['xml']);
					$ns=$xml->getNamespaces(true);
					$docs=$xml->children($ns["ns"]);
					foreach($docs->Document->ReplyNoAnswerTTN as $consignee) {
						$NAttns=$docs->Document->ReplyNoAnswerTTN ->children($ns["ttn"]);
						if($NAttns->Consignee!=$ttn['сonsignee']['ClientRegId']) continue;
						foreach($NAttns->ttnlist->NoAnswer as $t) {
							if($t->ttnNumber!=$ttn['number'] && $t->ttnDate!=$ttn['date'] && $t->Shipper!=$ttn['shipper']['ClientRegId']) continue;
							$stop=true;
							return array(
								'success'=>true,
								'regid'=>$t->WbRegID
							);
						}
					}
				}*/
				if($r['docType']=='formbreginfo' || $r['docType']=='form2reginfo') {
					$xml=simplexml_load_string($ticket['xml']);
					$ns=$xml->getNamespaces(true);
					$docs=$xml->children($ns["ns"]);
					$wbr=$docs->Document->TTNInformF2Reg->children($ns["wbr"]);
					if(!isset($wbr->Header->Identity)) continue;
					$shipper=(array)$wbr->Header->Shipper->children($ns['oref']);
					$shipper=(array)array_shift($shipper);
					if($wbr->Header->Identity==$ttn['identity'] && $shipper['ClientRegId']==$ttn['shipper']['ClientRegId']) {
						$stop=true;
						$position=array();
						foreach($wbr->Content->Position as $p) {
							$position[(string)$p->Identity]=(array)$p;
						}
						return array(
							'success'=>true,
							'regid'=>$wbr->Header->WBRegId,
							'position'=>$position
						);
					}

				}
			}
			$offset+=$limit;
		}
		return array(
			'success'=>false,
			'txt'=>'ttn_number_not_found'
		);
	}

	function ttnact($data) {
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$number=array_reverse(explode('-', $data['WBRegId']))[0];
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns= \"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" 		xmlns:wa= \"http://fsrar.ru/WEGAIS/ActTTNSingle_v4\" xmlns:c=\"http://fsrar.ru/WEGAIS/Common\" xmlns:ce=\"http://fsrar.ru/WEGAIS/CommonV3\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:WayBillAct_v4>\n";
		$xml.="<wa:Header>\n";
		$xml.="<wa:IsAccept>".$data['IsAccept']."</wa:IsAccept>\n";
		$xml.="<wa:ACTNUMBER>".$number."</wa:ACTNUMBER>\n";
		$xml.="<wa:ActDate>".date('Y-m-d')."</wa:ActDate>\n";
		$xml.="<wa:WBRegId>".$data['WBRegId']."</wa:WBRegId>\n";
		$xml.="<wa:Note></wa:Note>\n";
		$xml.="</wa:Header>\n";
		if($data['IsAccept']=='Differences') {
			$xml.="<wa:Content>\n";
			foreach($data['position'] as $Identity=>$position) {
				//if($position['RealQuantity']==$position['Quantity']) continue;
				$xml.="<wa:Position>\n";
				$xml.="<wa:Identity>".$Identity."</wa:Identity>\n";
				$xml.="<wa:InformF2RegId>".$position['InformF2RegId']."</wa:InformF2RegId>\n";
				$xml.="<wa:RealQuantity>".number_format($position['RealQuantity'], 5, '.', '')."</wa:RealQuantity>\n";

				if($position['MarkCodeInfo'] && $position['MarkCodeInfo']!='') {
					$marks=explode("\n", $position['MarkCodeInfo']);
					if(is_array($marks)) {
						$xml.="<wa:MarkInfo>\n";
						foreach($marks as $m) {
							$xml.="<ce:amc>".$m."</ce:amc>";
						}
						$xml.="</wa:MarkInfo>\n";
					}
				}

				$xml.="</wa:Position>\n";
			}
			$xml.="</wa:Content>\n";
		}
		$xml.="</ns:WayBillAct_v4>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";

		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/WayBillAct_v4', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function ttnact_repeal($data) {
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$number=array_reverse(explode('-', $data['WBRegId']))[0];
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:qp=\"http://fsrar.ru/WEGAIS/RequestRepealWB\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:RequestRepealWB>\n";
		$xml.="<qp:ClientId>".$data['ClientId']."</qp:ClientId>\n";
		$xml.="<qp:RequestNumber>".$number."</qp:RequestNumber>\n";
		$xml.="<qp:RequestDate>".date('Y-m-d')."T".date('H:m:s')."</qp:RequestDate>\n";
		$xml.="<qp:WBRegId>".$data['WBRegId']."</qp:WBRegId>\n";
		$xml.="</ns:RequestRepealWB>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";

		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/RequestRepealWB', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function get_rests() {
		$stop=false;
		$limit=100;
		$offset=0;
		$end_time=time()-3600*24*10;
		while(!$stop) {
			$request=$this->web->request($this->url_egais.'/api/db/out/list?limit='.$limit.'&offset='.$offset, $options);
			if(mb_strpos($request['headers'][0], '200')===false && mb_strpos($request['headers'][1], '200')===false) {
				return array(
					'success'=>false,
					'txt'=>$request['body']
				);
			}
			$body=json_decode($request['body'], true);
			if(empty($body['rows'])) {
				$stop=true;
				break;
			}
			foreach($body['rows'] as $r) {
				if(strtotime($r['createTimestamp'])<$end_time) {
					$stop=true;
					break;
				}
				$r['docType']=mb_strtolower($r['docType']);
				if($r['docType']=='replyrests') {
					// разбираем документ и формируем остатки
					$ticket=$this->rests_array($r['id']);
					if(!$ticket['success']) {
						return $ticket;
					}
					$r['positions']=$ticket['receipt']['positions'];
					foreach($r['positions'] as $key=>$position) {
						$alcocode=$position['Product']['AlcCode'];
						if(!$products[$alcocode]) {
							$product=$this->db->exec("SELECT price, vat, vat_type, buy_price FROM products WHERE date_delete=0 AND alcocode=? LIMIT 1", $alcocode);
							if($product) {
								if($product[0]['price']>0) {
									$product[0]['price']=$product[0]['price']=$product[0]['price']+($product[0]['price']*($product[0]['vat']/100))*max(0, $product[0]['vat_type']);
								}
								else {
									$product[0]['price']=$product[0]['buy_price'];
								}
								$products[$alcocode]=array('price'=>$product[0]['price'], 'buy_price'=>$product[0]['buy_price']);
							}
							else {
								$products[$alcocode]=array('price'=>0, 'buy_price'=>0);
							}
						}
						$r['positions'][$key]['price']=$products[$alcocode]['price'];
						$r['positions'][$key]['buy_price']=$products[$alcocode]['buy_price'];
					}
					return array(
						'success'=>true,
						'receipt'=>$r
					);
				}

			}
			$offset+=$limit;
		}
		return array(
			'success'=>false,
			'txt'=>'rests_not_found'
		);
	}

	function writeoff($data) {
		$positions=array();
		if($data['position']) {
			foreach($data['position'] as $key=>$position) {
				if($position['Quantity']>0) {
					if($data['TypeWriteOff']=='Реализация' && $position['price']==0) {
						return array(
							'success'=>false,
							'txt'=>'not_enough_data'
						);
					}
					$positions[$key]=$position;
				}
			}
		}
		if(!$positions) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$number=time();
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:pref=\"http://fsrar.ru/WEGAIS/ProductRef_v2\" xmlns:awr=\"http://fsrar.ru/WEGAIS/ActWriteOff_v3\" xmlns:ce=\"http://fsrar.ru/WEGAIS/CommonV3\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:ActWriteOff_v3>\n";
		$xml.="<awr:Identity>".$number."</awr:Identity>\n";
		$xml.="<awr:Header>\n";
		$xml.="<awr:ActNumber>".$number."</awr:ActNumber>\n";
		$xml.="<awr:ActDate>".date('Y-m-d')."</awr:ActDate>\n";
		$xml.="<awr:TypeWriteOff>".$data['TypeWriteOff']."</awr:TypeWriteOff>\n";
		$xml.="</awr:Header>\n";
		$xml.="<awr:Content>\n";
		foreach($positions as $key=>$position) {
			$xml.="<awr:Position>\n";
			$xml.="<awr:Identity>".$key."</awr:Identity>\n";
			$xml.="<awr:Quantity>".number_format($position['Quantity'], 5, '.', '')."</awr:Quantity>\n";
			if($data['TypeWriteOff']=='Реализация') {
				$xml.="<awr:SumSale>".number_format($position['price']?$position['Quantity']*$position['price']:0, 2, '.', '')."</awr:SumSale>\n";
			}
			$xml.="<awr:InformF1F2>\n";
			$xml.="<awr:InformF2>\n";
			$xml.="<pref:F2RegId>".($position['InformBRegId']?$position['InformBRegId']:$position['InformARegId'])."</pref:F2RegId>\n";
			$xml.="</awr:InformF2>\n";
			$xml.="</awr:InformF1F2>\n";
			if($position['MarkCodeInfo']) {
				$marks=explode("\n", $position['MarkCodeInfo']);
				if($marks) {
					$xml.="<awr:MarkCodeInfo>\n";
					foreach($marks as $m) {
						$m=trim($m);
						if($m!='') {
							$xml.="<ce:amc>".$m."</ce:amc>\n";
						}
					}
					$xml.="</awr:MarkCodeInfo>\n";
				}
			}
			$xml.="</awr:Position>\n";
		}
		$xml.="</awr:Content>\n";
		$xml.="</ns:ActWriteOff_v3>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/ActWriteOff_v3', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function writeoff_repeal($data) {
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$number=time();
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:qp=\"http://fsrar.ru/WEGAIS/RequestRepealAWO\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:RequestRepealAWO>\n";
		$xml.="<qp:ClientId>".$utminfo['request']['ownerId']."</qp:ClientId>\n";
		$xml.="<qp:RequestNumber>".$number."</qp:RequestNumber>\n";
		$xml.="<qp:RequestDate>".date('Y-m-d').'T'.date('H:i:s')."</qp:RequestDate>\n";
		$xml.="<qp:AWORegId>".$data['AWORegId']."</qp:AWORegId>\n";
		$xml.="</ns:RequestRepealAWO>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/RequestRepealAWO', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function get_organization($data) {
		$json_key=array('ClientRegId'=>'owner_ID', 'INN'=>'inn', 'KPP'=>'kpp', 'FullName'=>"full_name");
		$vals=array();
		$json_vals=array();
		foreach($data as $key=>$val) {
			if(trim($val)!='') {
				$vals[$key]=trim($val);
				$json_vals[$json_key[$key]]=$val;
			}
		}
		if(count($vals)==1 && isset($vals['ClientRegId'])) {
			$options = array(
				'method'=>'GET',
    			'header'=>array(
    				'accept: application/json'
    			),
    			'content'=>array('fsrarids'=>$vals['ClientRegId'])
			);
		}
		else {
			$options = array(
				'method'=>'POST',
    			'header'=>array(
    				'accept: application/json',
    				'Content-Type: application/json',
    			),
    			'content'=>json_encode($json_vals)
			);
		}
		$request=$this->web->request($this->url_egais.'/api/services/nsi/organizations', $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			if(is_array($body) && !empty($body)) {
				$organizations=array();
				foreach($body as $row) {
					if((int)$row['country_Code']==643) {
						if(mb_strlen($row['inn']==12)) {
							$row['OrgType']='FL';
						}
						else {
							$row['OrgType']='UL';
						}
					}
					elseif(isset($row['inn'])) {
						$row['OrgType']='TS';
					}
					else {
						$row['OrgType']='FO';
					}
					$organizations[]=$row;
				}
				return array(
					'success'=>true,
					'organizations'=>$organizations
				);
			}
			return array(
				'success'=>false,
				'txt'=>'organization_not_found'
			);
		}
		if($body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	function createttn($data) {
		$positions=array();
		if($data['position']) {
			foreach($data['position'] as $key=>$position) {
				if($position['Quantity']>0) {
					$positions[$key]=$position;
				}
			}
		}
		if(!$positions || !$data['ClientRegId']
			|| !$data['FullName']
			|| !$data['address_description']
			|| ($data['OrgType']=='UL' && !$data['INN'] && !$data['KPP'] && !$data['address_Country'] && !$data['address_RegionCode'])
			|| ($data['OrgType']=='FL' && !$data['INN'] && !$data['address_Country'] && !$data['address_RegionCode'])
		) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		if(mb_strlen($this->sets['inn'])==12) {
			$shipper_type='FL';
		}
		else {
			$shipper_type='UL';
		}
		if(!$data['NUMBER']) $data['NUMBER']=time();
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
		$xml.="<ns:Documents xmlns:ce=\"http://fsrar.ru/WEGAIS/CommonV3\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:oref=\"http://fsrar.ru/WEGAIS/ClientRef_v2\" xmlns:pref=\"http://fsrar.ru/WEGAIS/ProductRef_v2\" xmlns:wb=\"http://fsrar.ru/WEGAIS/TTNSingle_v4\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" Version=\"1.0\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:WayBill_v4>\n";
		$xml.="<wb:Identity>".time()."</wb:Identity>\n";
		$xml.="<wb:Header>\n";
		$xml.="<wb:NUMBER>".$data['NUMBER']."</wb:NUMBER>\n";
		$xml.="<wb:Date>".date('Y-m-d')."</wb:Date>\n";
		$xml.="<wb:ShippingDate>".date('Y-m-d', strtotime($data['ShippingDate']))."</wb:ShippingDate>\n";
		$xml.="<wb:Type>".$data['Type']."</wb:Type>\n";
		$xml.="<wb:Shipper>\n";
		$xml.="<oref:".$shipper_type.">\n";
		$xml.="<oref:ClientRegId>".$utminfo['request']['ownerId']."</oref:ClientRegId>\n";
		$xml.="<oref:INN>".$this->sets['inn']."</oref:INN>\n";
		if($shipper_type=='UL') {
			$xml.="<oref:KPP>".$this->sets['kpp']."</oref:KPP>\n";
		}
		$xml.="<oref:FullName>".$this->sets['org_name']."</oref:FullName>\n";
		$xml.="<oref:address>\n";
		$xml.="<oref:Country>".$this->sets['org_country']."</oref:Country>\n";
		$xml.="<oref:RegionCode>".$this->sets['org_region']."</oref:RegionCode>\n";
		$xml.="<oref:description>".$this->sets['org_address']."</oref:description>\n";
		$xml.="</oref:address>\n";
		$xml.="</oref:".$shipper_type.">\n";
		$xml.="</wb:Shipper>\n";
		$xml.="<wb:Consignee>\n";
		$xml.="<oref:".$data['OrgType'].">\n";
		$xml.="<oref:ClientRegId>".$data['ClientRegId']."</oref:ClientRegId>\n";
		if($data['OrgType']=='UL' || $data['OrgType']=='FL' || ($data['TS'] && $data['INN'])) {
			$xml.="<oref:INN>".$data['INN']."</oref:INN>\n";
		}
		if($data['OrgType']=='UL') {
			$xml.="<oref:KPP>".$data['KPP']."</oref:KPP>\n";
		}
		$xml.="<oref:FullName>".$data['FullName']."</oref:FullName>\n";
		$xml.="<oref:address>\n";
		if($data['OrgType']=='UL' || $data['OrgType']=='FL') {
			$xml.="<oref:Country>".$data['address_Country']."</oref:Country>\n";
			$xml.="<oref:RegionCode>".$data['address_RegionCode']."</oref:RegionCode>\n";
		}
		$xml.="<oref:description>".$data['address_description']."</oref:description>\n";
		$xml.="</oref:address>\n";
		$xml.="</oref:".$data['OrgType'].">\n";
		$xml.="</wb:Consignee>\n";
		$xml.="</wb:Header>\n";
		$xml.="<wb:Content>\n";
		foreach($positions as $key=>$position) {
			$xml.="<wb:Position>\n";
			$xml.="<wb:Identity>".$key."</wb:Identity>\n";
			$xml.="<wb:Product>\n";
			$xml.="<pref:FullName>".$position['FullName']."</pref:FullName>\n";
			$xml.="<pref:AlcCode>".$position['AlcCode']."</pref:AlcCode>\n";
			if($position['Capacity']) {
				$xml.="<pref:Capacity>".$position['Capacity']."</pref:Capacity>\n";
			}
			$xml.="<pref:UnitType>".($position['UnitType']=='packed'?'Packed':'Unpacked')."</pref:UnitType>\n";
			$xml.="<pref:AlcVolume>".$position['AlcVolume']."</pref:AlcVolume>\n";
			$xml.="<pref:ProductVCode>".$position['ProductVCode']."</pref:ProductVCode>\n";
			$xml.="<pref:Producer>\n";
			$producer=json_decode(urldecode($position['Producer']), true);
			if(mb_strlen($producer['inn'])==12) {
				$producer_type='FL';
			}
			else {
				$producer_type='UL';
			}
			$xml.="<oref:".$producer_type.">\n";
			$xml.="<oref:ClientRegId>".$producer['ClientRegId']."</oref:ClientRegId>\n";
			$xml.="<oref:FullName>".$producer['FullName']."</oref:FullName>\n";
			$xml.="<oref:INN>".$producer['INN']."</oref:INN>\n";
			if($producer['KPP']) {
				$xml.="<oref:KPP>".$producer['KPP']."</oref:KPP>\n";
			}
			$xml.="<oref:address>\n";
			$xml.="<oref:Country>".$producer['address']['Country']."</oref:Country>\n";
			$xml.="<oref:RegionCode>".$producer['address']['RegionCode']."</oref:RegionCode>\n";
			$xml.="<oref:description>".$producer['address']['description']."</oref:description>\n";
			$xml.="</oref:address>\n";
			$xml.="</oref:".$producer_type.">\n";
			$xml.="</pref:Producer>\n";
			$xml.="</wb:Product>\n";
			$xml.="<wb:Quantity>".number_format($position['Quantity'], 5, '.', '')."</wb:Quantity>\n";
			$xml.="<wb:Price>".number_format($position['Price'], 2, '.', '')."</wb:Price>\n";
			$xml.="<wb:FARegId>".$position['InformARegId']."</wb:FARegId>\n";
			$xml.="<wb:InformF2>\n";
			$xml.="<ce:F2RegId>".$position['InformBRegId']."</ce:F2RegId>\n";
			if($position['MarkCodeInfo'] || $position['UnitType']=='packed') {
				$xml.="<ce:MarkInfo>\n";
				$xml.="<ce:boxpos>\n";
				if($position['UnitType']=='packed') {
					$xml.="<ce:boxnumber>".$position['boxnumber']."</ce:boxnumber>\n";
				}
				if($position['MarkCodeInfo']) {
					$marks=explode("\n", $position['MarkCodeInfo']);
					if($marks) {
						$xml.="<ce:amclist>\n";
						foreach($marks as $m) {
							$m=trim($m);
							if($m!='') {
								$xml.="<ce:amc>".$m."</ce:amc>\n";
							}
						}
						$xml.="</ce:amclist>\n";
					}
				}
				$xml.="</ce:boxpos>\n";
				$xml.="</ce:MarkInfo>\n";
			}
			$xml.="</wb:InformF2>\n";
			$xml.="</wb:Position>\n";
		}
		$xml.="</wb:Content>\n";
		$xml.="</ns:WayBill_v4>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";

		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/WayBill_v4', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	function beer_currentstock($rests, $stock) {
		$positions=array();
		$beer=array();
		$error=array();

		// Массив с пивом
		foreach($stock as $s) {
			if($s['alcocode']=='') {
				$s['alcocode']=-$s['id'];
			}
			$beer[$s['alcocode']]=$s;
		}

		// Остатки по ЕГАИС
		foreach($rests as $r) {
			$code=$r['Product']['AlcCode'];
			if(!$beer[$code]) {
				continue;
			}
			$beer[$code]['stock_egais']+=$r['Quantity'];
			$beer[$code]['title_egais']=$r['Product']['FullName'];
		}

		// Сколько надо списать
		foreach($beer as $code=>$b) {
			$beer[$code]['writeoff']=$b['stock_egais']-$b['stock'];
		}

		// Формируем строки для списания
		foreach($rests as $r) {
			$code=$r['Product']['AlcCode'];
			if(!$beer[$code] || $beer[$code]['writeoff']==0) {
				continue;
			}
			if($beer[$code]['writeoff']<0) {
				$error[$code]=$beer[$code];
				continue;
			}
			if($beer[$code]['writeoff']>$r['Quantity']) {
				$writeoff=$r['Quantity'];
			}
			else {
				$writeoff=$beer[$code]['writeoff'];
			}
			if($writeoff==0) {
				continue;
			}
			$beer[$code]['writeoff']-=$writeoff;
			$r['writeoff']=$writeoff;
			$r['stock']=$beer[$code]['stock'];
			$r['stock_egais']=$beer[$code]['stock_egais'];
			if(!$r['price']) {
				$r['price']=$beer[$code]['price'];
			}
			$positions[]=$r;
		}

		// Формируем ошибки
		foreach($beer as $b) {
			if($b['alcocode']<0 || $b['writeoff']>0) {
				$error[]=$b;
			}
		}
		return array(
			'success'=>true,
			'positions'=>$positions,
			'error'=>$error
		);
	}

	function related($id) {
		$ticket=$this->ticket_xml('out', $id);
		if(!$ticket['success']) {
			return $ticket;
		}
		$last=$this->out_list(1, 0);
		if(!$last['success']) {
			return $last;
		}
		$identity='';
		$reg_id='';
		$xml=mb_strtolower($ticket['xml']);
		$xml=preg_replace('/(<\/([^>]+):)/U', '</', $xml);
		$xml=preg_replace('/(<([^>]+):)/U', '<', $xml);
		$xml.=str_replace(' ', '', $xml);
		$xml.=str_replace("\n", '', $xml);
		$xml.=str_replace("\r", '', $xml);
		if(mb_strpos($xml, '<regid>')>0) {
			$reg_id=mb_substr($xml, mb_strpos($xml, '<regid>')+7);
			$reg_id=mb_substr($reg_id, 0, mb_strpos($reg_id, '<'));
		}
		if($reg_id=='' && mb_strpos($xml, '<wbregid>')>0) {
			$reg_id=mb_substr($xml, mb_strpos($xml, '<wbregid>')+9);
			$reg_id=mb_substr($reg_id, 0, mb_strpos($reg_id, '<'));
		}
		if(mb_strpos($xml, '<identity>')>0) {
			$identity=mb_substr($xml, mb_strpos($xml, '<identity>')+10);
			$identity=mb_substr($identity, 0, mb_strpos($identity, '<'));
		}

		if($identity=='' && $reg_id=='') {
			return array(
				'success'=>false,
				'txt'=>'identity_not_found'
			);
		}
		$last_id=(int)$last['receipts'][0]['id'];
		$next_id=$id-50;
		$receipts=array();
		$types_data=$this->tickets_types();
		if($types_data['success']) {
			$types=$types_data['data'];
		}
		else {
			$types=array();
		}
		$operations=array(
			'confirm'=>'Подтверждение',
			'unconfirm'=>'Отменить',
			'accepted'=>'Подтвердить полностью',
			'differences'=>'Подтвердить с рознагласиями',
			'rejected'=>'Отказать',
		);
		$results=array(
			'accepted'=>'Успешно',
			'rejected'=>'Отклонено',
		);
		while($next_id<=$last_id) {
			if($next_id==$id) {
				$next_id+=1;
				continue;
			}
			$ticket=$this->ticket_xml('out', $next_id);
			if(!$ticket['success']) {
				$next_id+=1;
				continue;
			}
			$xml=mb_strtolower($ticket['xml']);
			$xml=preg_replace('/(<\/([^>]+):)/U', '</', $xml);
			$xml=preg_replace('/(<([^>]+):)/U', '<', $xml);
			$xml_xml=$xml;
			$xml.=str_replace(' ', '', $xml);
			$xml.=str_replace("\n", '', $xml);
			$xml.=str_replace("\r", '', $xml);
			if(($identity!='' && mb_strpos($xml, '<identity>'.$identity.'<')>0) || ($reg_id!='' && mb_strpos($xml, '<regid>'.$reg_id.'<')>0) || ($reg_id!='' && mb_strpos($xml, '<wbregid>'.$reg_id.'<')>0)) {
				if($reg_id=='' && mb_strpos($xml, '<regid>')>0) {
					$reg_id=mb_substr($xml, mb_strpos($xml, '<regid>')+7);
					$reg_id=mb_substr($reg_id, 0, mb_strpos($reg_id, '<'));
				}
				if($reg_id=='' && mb_strpos($xml, '<wbregid>')>0) {
					$reg_id=mb_substr($xml, mb_strpos($xml, '<wbregid>')+9);
					$reg_id=mb_substr($reg_id, 0, mb_strpos($reg_id, '<'));
				}
				if($identity=='' && mb_strpos($xml, '<identity>')>0) {
					$identity=mb_substr($xml, mb_strpos($xml, '<identity>')+10);
					$identity=mb_substr($identity, 0, mb_strpos($identity, '<'));
				}
				$xml=simplexml_load_string($xml_xml);
				$type=mb_strtolower(array_key_first((array)$xml->document));
				if(isset($types[$type])) {
					$type_name=$types[$type]['title'];
				}
				else {
					$type_name=$type;
				}

				$number='';
				if(isset($xml->document->header->number)) {
					$number=(string)$xml->document->header->number;
				}
				elseif(isset($xml->document->confirmticket->header->ticketnumber)) {
					$number=(string)$xml->document->confirmticket->header->ticketnumber;
				}

				$date='';
				if(isset($xml->document->ticket->ticketdate)) {
					$date=(string)$xml->document->ticket->ticketdate;
				}
				elseif(isset($xml->document->confirmticket->header->ticketdate)) {
					$date=(string)$xml->document->confirmticket->header->ticketdate;
				}
				elseif(isset($xml->document->header->date)) {
					$date=(string)$xml->document->header->date;
				}

				$operation='';
				if(isset($xml->document->ticket->operationresult->operationname)) {
					$operation=(string)$xml->document->ticket->operationresult->operationname;
				}
				elseif(isset($xml->document->confirmticket->header->isconfirm)) {
					$operation=(string)$xml->document->confirmticket->header->isconfirm;
				}
				if($operation!='' && isset($operations[$operation])) {
					$operation=$operations[$operation];
				}

				$result='';
				if(isset($xml->document->ticket->operationresult->operationresult)) {
					$result=(string)$xml->document->ticket->operationresult->operationresult;
				}
				elseif(isset($xml->document->ticket->result->conclusion)) {
					$result=(string)$xml->document->ticket->result->conclusion;
				}
				if($result!='' && isset($results[$result])) {
					$result=(string)$results[$result];
				}

				$comment='';
				if(isset($xml->document->ticket->operationresult->operationresult)) {
					$comment=(string)$xml->document->ticket->operationresult->operationcomment;
				}
				elseif(isset($xml->document->confirmticket->header->note)) {
					$comment=(string)$xml->document->confirmticket->header->note;
				}
				elseif(isset($xml->document->ticket->result->comments)) {
					$comment=(string)$xml->document->ticket->result->comments;
				}
				$receipts[]=array(
					'id'=>$next_id,
					'type'=>$type,
					'type_name'=>$type_name,
					'number'=>$number,
					'date'=>$date,
					'operation'=>$operation,
					'result'=>$result,
					'comment'=>$comment
				);
			}
			$next_id+=1;
		}
		return array(
			'success'=>true,
			'receipts'=>array_reverse($receipts)
		);
	}

	function search_ttn($data) {
		$next_id=$data['nattnid']-1;
		$reg_id=mb_strtolower($data['regid']);
		$id=0;
		$identity='';
		while($next_id>0 && $id==0) {
			$ticket=$this->ticket_xml('out', $next_id);
			if($ticket['success']) {
				$xml=mb_strtolower($ticket['xml']);
				$xml=preg_replace('/(<\/([^>]+):)/U', '</', $xml);
				$xml=preg_replace('/(<([^>]+):)/U', '<', $xml);
				$xml_xml=$xml;
				$xml.=str_replace(' ', '', $xml);
				$xml.=str_replace("\n", '', $xml);
				$xml.=str_replace("\r", '', $xml);
				if($identity=='') {
					if(mb_strpos($xml, "<wbregid>".$reg_id."</wbregid>")>0 && mb_strpos($xml, "<identity>")>0) {
						$identity=mb_substr($xml, mb_strpos($xml, '<identity>')+10);
						$identity=mb_substr($identity, 0, mb_strpos($identity, '<'));
					}
				}
				else {
					if(mb_strpos($xml, "<identity>".$identity."</identity>")>0) {
						$id=$next_id;
					}
				}
			}
			$next_id-=1;
		}

		if($id>0) {
			return array(
				'success'=>true,
				'id'=>$id
			);
		}
		return array(
			'success'=>false,
			'txt'=>'ttn_not_found'
		);
	}

	function product_from_bcode($id, $bcode) {
		$bcode=mb_strtolower($bcode);
		$next_id=$id-1;
		$end=$id-15;
		$product='';
		while($next_id>$end && $product=='') {
			$ticket=$this->ticket_xml('out', $next_id);
			if(!$ticket['success']) {
				$next_id+=1;
				continue;
			}
			$xml=mb_strtolower($ticket['xml']);
			$xml=preg_replace('/(<\/([^>]+):)/U', '</', $xml);
			$xml=preg_replace('/(<([^>]+):)/U', '<', $xml);
			$xml_xml=$xml;
			$xml.=str_replace(' ', '', $xml);
			$xml.=str_replace("\n", '', $xml);
			$xml.=str_replace("\r", '', $xml);
			if(mb_strpos($xml, '<informbregid>'.$bcode.'<')>0) {
				$rest=$this->xml_to_rests($ticket['xml']);
				if($rest['success'] && $rest['receipt']['positions']) {
					foreach($rest['receipt']['positions'] as $p) {
						if(mb_strtolower($p['InformBRegId'])==$bcode) {
							$product=$p['Product']['FullName'];
							return array(
								'success'=>true,
								'product'=>$product
							);
							break(2);
						}
					}
				}
			}
			elseif(mb_strpos($xml, '<f2regid>'.$bcode.'<')>0) {
				$ttn=$this->xml_to_ttn($ticket['xml']);
				if($ttn['success'] && $ttn['ttn']['products']) {
					foreach($ttn['ttn']['products'] as $p) {
						if(mb_strtolower($p['FormB'])==$bcode) {
							$product=$p['FullName'];
							return array(
								'success'=>true,
								'product'=>$product
							);
							break(2);
						}
					}
				}
			}
			$next_id-=1;
			usleep(50000);
		}
		return array(
			'success'=>false,
			'txt'=>'not_found'
		);
	}

	function restbcode($formb) {
		if(!$formb) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$utminfo=$this->utminfo();
		if(!$utminfo['success']) {
			return $utminfo;
		}
		$xml="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n";
		$xml.="<ns:Documents Version=\"1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:ns=\"http://fsrar.ru/WEGAIS/WB_DOC_SINGLE_01\" xmlns:qp=\"http://fsrar.ru/WEGAIS/QueryParameters\">\n";
		$xml.="<ns:Owner>\n";
		$xml.="<ns:FSRAR_ID>".$utminfo['request']['ownerId']."</ns:FSRAR_ID>\n";
		$xml.="</ns:Owner>\n";
		$xml.="<ns:Document>\n";
		$xml.="<ns:QueryRestBCode>\n";
		$xml.="<qp:Parameters>\n";
		$xml.="<qp:Parameter>\n";
		$xml.="<qp:Name>ФОРМА2</qp:Name>\n";
		$xml.="<qp:Value>".$formb."</qp:Value>\n";
		$xml.="</qp:Parameter>\n";
		$xml.="</qp:Parameters>\n";
		$xml.="</ns:QueryRestBCode>\n";
		$xml.="</ns:Document>\n";
		$xml.="</ns:Documents>\n";
		$xml_name=$this->f3->get('ROOT').'/tmp/'.(microtime(true)*10000).'.xml';
		$this->f3->write($xml_name, $xml);

		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: text/xml',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/opt/in/QueryRestBCode', $options);
		unlink($xml_name);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			$reuest['body']=str_replace("&'", "'", $request['body']);
			$xml=new \SimpleXMLElement($request['body']);
			if($xml->error!='') {
				return array(
					'success'=>false,
					'txt'=>$xml->error
				);
			}
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		if(is_array($body) && $body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		elseif($xml->error!='') {
			return array(
				'success'=>false,
				'txt'=>$xml->error
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}
	}

	// Информация по организациям по ФСРАР ID
	function nsi_organizations($ids) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$data='';
		foreach($ids as $i) {
			$data.='&fsrarids='.$i;
		}
		$request=$this->web->request($this->url_egais.'/api/services/nsi/organizations?'.$data, $options);
		$body=json_decode($request['body'], true);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			return array(
				'success'=>true,
				'organizations'=>$body
			);
		}
		if($body['error']) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		return array(
			'success'=>false,
			'txt'=>implode(';', $request)
		);
	}

	// Информация о продукции по алкокодам
	function nsi_productions($codes) {
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		$products=array();
		$data=array_chunk($codes, 10, true);
		foreach($data as $codes){
			$url='';
			foreach($codes as $c) {
				$url.='&codes='.$c;
			}
			$request=$this->web->request($this->url_egais.'/api/services/nsi/productions?'.$url, $options);
			$body=json_decode($request['body'], true);
			if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
				$products=array_merge($products, $body);
			}
			else {
				if($body['error']) {
					return array(
						'success'=>false,
						'txt'=>$body['message']
					);
				}
				return array(
					'success'=>false,
					'txt'=>implode(';', $request)
				);
			}
		}

		return array(
			'success'=>true,
			'products'=>$products
		);
	}

	// Создаем имя файла для декларации
	function gen_declaration_name($type, $q, $year) {
		$q=$q*3;
		if($q==12) $q=0;
		return $type.'_'.$this->sets['inn'].'_'.sprintf("%'.02d", $q).mb_substr($year, 3, 1).'_'.date('dmY').'_'.$this->GUID().'.xml';
	}

	// Формируем xml для пивной декларации
	function beer_declaration($number, $q, $year, $data) {
		$address="<АдрОрг>\n";
        $address.="<КодСтраны>".$this->sets['org_country']."</КодСтраны>\n";
        $address.="<Индекс>".$this->sets['org_postcode']."</Индекс>\n";
        $address.="<КодРегион>".$this->sets['org_region']."</КодРегион>\n";
        $address.="<Район>".$this->sets['org_rayon']."</Район>\n";
        $address.="<Город>".$this->sets['org_city']."</Город>\n";
        $address.="<НаселПункт>".$this->sets['org_punkt']."</НаселПункт>\n";
        $address.="<Улица>".$this->sets['org_street']."</Улица>\n";
        $address.="<Дом>".$this->sets['org_dom']."</Дом>\n";
        $address.="<Корпус>".$this->sets['org_korpus']."</Корпус>\n";
        $address.="<Литера>".$this->sets['org_litera']."</Литера>\n";
        $address.="<Кварт>".$this->sets['org_kv']."</Кварт>\n";
        $address.="</АдрОрг>\n";

		$xml="<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n";
		$xml.="<Файл xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ДатаДок=\"".date('d.m.Y')."\" ВерсФорм=\"4.4\" НаимПрог=\"".$this->f3->get('prog_name')."\">\n";
		$xml.="<ФормаОтч НомФорм=\"38\" ПризПериодОтч=\"".$q."\" ГодПериодОтч=\"".$year."\">\n";
		$xml.="<Первичная />\n";
		$xml.="</ФормаОтч>\n";
		$xml.="<Справочники>\n";
		if($data['importers']) {
			$n=1;
			foreach($data['importers'] as $owner_id=>$importer) {
				$data['importers'][$owner_id]['n']=$n;
				$xml.="<ПроизводителиИмпортеры ИДПроизвИмп=\"".$n."\" П000000000004=\"".htmlentities($importer['full_Name'])."\">\n";
				if(mb_strlen($importer['inn'])==12) {
					$xml.="<ФЛ П000000000005=\"".$importer['inn']."\" />\n";
				}
				else {
					$xml.="<ЮЛ П000000000005=\"".$importer['inn']."\" П000000000006=\"".$importer['kpp']."\" />\n";
				}
				$xml.="</ПроизводителиИмпортеры>\n";
				$n+=1;
			}
		}

		$xml.="</Справочники>\n";
		$xml.="<Документ>\n";
		$xml.="<Организация>\n";
		$xml.="<Реквизиты Наим=\"".htmlentities($this->sets['org_name'])."\" ТелОрг=\"\" EmailОтпр=\"\">\n";
		$xml.=$address;
        if(mb_strlen($this->sets['inn'])==12) {
        	$xml.="<ФЛ ИННФЛ=\"".$this->sets['inn']."\" />\n";
        }
        else {
        	$xml.="<ЮЛ ИННЮЛ=\"".$this->sets['inn']."\" КППЮЛ=\"".$this->sets['kpp']."\" />\n";
        }
        $xml.="</Реквизиты>\n";
		$xml.="<ОтветЛицо>\n";
		$xml.="<Руководитель>\n";
		$xml.="<Фамилия />\n";
		$xml.="<Имя />\n";
		$xml.="<Отчество />\n";
		$xml.="</Руководитель>\n";
		$xml.="<Главбух>\n";
		$xml.="<Фамилия />\n";
		$xml.="<Имя />\n";
		$xml.="<Отчество />\n";
		$xml.="</Главбух>\n";
		$xml.="</ОтветЛицо>\n";
		$xml.="</Организация>\n";
       	$xml.="<ОбъемОборота Наим=\"".htmlentities($this->sets['org_name'])."\">\n";
        $xml.=$address;
        // Оборот
        if($data['products']) {
        	$type_n=1;
        	foreach($data['products'] as $productType_Code=>$owners) {
        		$xml.="<Оборот ПN=\"".$type_n."\" П000000000003=\"".$productType_Code."\">\n";
        		$owner_n=1;
        		foreach($owners as $owner_id=>$products) {
        			$xml.="<СведПроизвИмпортер ПN=\"".$owner_n."\" ИдПроизвИмп=\"".$data['importers'][$owner_id]['n']."\">\n";
        			$product_n=1;
        			foreach($products as $product) {
        				$xml.="<Движение ПN=\"".$product_n."\" П100000000006=\"".number_format($product['stock0'], 5, '.', '')."\" П100000000007=\"0.00000\" П100000000008=\"".number_format($product['goods'], 5, '.', '')."\" П100000000009=\"0.00000\" П100000000010=\"".number_format($product['goods'], 5, '.', '')."\" П100000000011=\"".number_format($product['returns'], 5, '.', '')."\" П100000000012=\"".number_format($product['other_in'], 5, '.', '')."\" П100000000013=\"".number_format($product['movein'], 5, '.', '')."\" П100000000014=\"".number_format($product['goods']+$product['returns']+$product['other_in']+$product['movein'], 5, '.', '')."\" П100000000015=\"".number_format($product['sales'], 5, '.', '')."\" П100000000016=\"".number_format($product['other_out'], 5, '.', '')."\" П100000000017=\"0.00000\" П100000000018=\"".number_format($product['moveout'], 5, '.', '')."\" П100000000019=\"".number_format($product['sales']+$product['other_out']+$product['moveout'], 5, '.', '')."\" П100000000020=\"".number_format($product['stock1'], 5, '.', '')."\" />\n";
        				$product_n++;
        			}
        			$xml.="</СведПроизвИмпортер>\n";
        			$owner_n++;
        		}

        		$xml.="</Оборот>\n";
        		$type_n++;
        	}
        }
		$xml.="</ОбъемОборота>\n";
		$xml.="</Документ>\n";
		$xml.="</Файл>\n";
		return array(
			'xml'=>$xml,
			'name'=>$this->gen_declaration_name('08', $q, $year)
		);
	}

	// Формируем xml декларации по крепкому алкоголю
	function alc_declaration($number, $q, $year, $data) {
		$address="<АдрОрг>\n";
        $address.="<КодСтраны>".$this->sets['org_country']."</КодСтраны>\n";
        $address.="<Индекс>".$this->sets['org_postcode']."</Индекс>\n";
        $address.="<КодРегион>".$this->sets['org_region']."</КодРегион>\n";
        $address.="<Район>".$this->sets['org_rayon']."</Район>\n";
        $address.="<Город>".$this->sets['org_city']."</Город>\n";
        $address.="<НаселПункт>".$this->sets['org_punkt']."</НаселПункт>\n";
        $address.="<Улица>".$this->sets['org_street']."</Улица>\n";
        $address.="<Дом>".$this->sets['org_dom']."</Дом>\n";
        $address.="<Корпус>".$this->sets['org_korpus']."</Корпус>\n";
        $address.="<Литера>".$this->sets['org_litera']."</Литера>\n";
        $address.="<Кварт>".$this->sets['org_kv']."</Кварт>\n";
        $address.="</АдрОрг>\n";

		$xml="<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n";
		$xml.="<Файл xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ДатаДок=\"".date('d.m.Y')."\" ВерсФорм=\"4.4\" НаимПрог=\"".$this->f3->get('prog_name')."\">\n";
		$xml.="<ФормаОтч НомФорм=\"37\" ПризПериодОтч=\"".$q."\" ГодПериодОтч=\"".$year."\">\n";
		$xml.="<Первичная />\n";
		$xml.="</ФормаОтч>\n";
		$xml.="<Справочники>\n";
		if($data['importers']) {
			$n=1;
			foreach($data['importers'] as $owner_id=>$importer) {
				$data['importers'][$owner_id]['n']=$n;
				$xml.="<ПроизводителиИмпортеры ИДПроизвИмп=\"".$n."\" П000000000004=\"".htmlentities($importer['full_Name'])."\" П000000000005=\"".$importer['inn']."\" П000000000006=\"".$importer['kpp']."\" />\n";
				$n+=1;
			}
		}
		$xml.="</Справочники>\n";
		$xml.="<Документ>\n";
		$xml.="<Организация>\n";
		$xml.="<Реквизиты Наим=\"".htmlentities($this->sets['org_name'])."\" ТелОрг=\"\" EmailОтпр=\"\">\n";
		$xml.=$address;
        if(mb_strlen($this->sets['inn'])==12) {
        	$xml.="<ФЛ ИННФЛ=\"".$this->sets['inn']."\" />\n";
        }
        else {
        	$xml.="<ЮЛ ИННЮЛ=\"".$this->sets['inn']."\" КППЮЛ=\"".$this->sets['kpp']."\" />\n";
        }
        $xml.="</Реквизиты>\n";
		$xml.="<ОтветЛицо>\n";
		$xml.="<Руководитель>\n";
		$xml.="<Фамилия />\n";
		$xml.="<Имя />\n";
		$xml.="<Отчество />\n";
		$xml.="</Руководитель>\n";
		$xml.="<Главбух>\n";
		$xml.="<Фамилия />\n";
		$xml.="<Имя />\n";
		$xml.="<Отчество />\n";
		$xml.="</Главбух>\n";
		$xml.="</ОтветЛицо>\n";
		$xml.="<Деятельность>\n";
		$xml.="<Лицензируемая />\n";
		$xml.="</Деятельность>\n";
		$xml.="</Организация>\n";
		if(mb_strlen($this->sets['inn'])==12) {
        	$xml.="<ОбъемОборота Наим=\"".htmlentities($this->sets['org_name'])."\">\n";
        }
        else {
        	$xml.="<ОбъемОборота Наим=\"".htmlentities($this->sets['org_name'])."\" КППЮЛ=\"".$this->sets['kpp']."\">\n";
        }
        $xml.=$address;
        // Оборот
        if($data['products']) {
        	$type_n=1;
        	foreach($data['products'] as $productType_Code=>$owners) {
        		$xml.="<Оборот ПN=\"".$type_n."\" П000000000003=\"".$productType_Code."\">\n";
        		$owner_n=1;
        		foreach($owners as $owner_id=>$products) {
        			$xml.="<СведПроизвИмпортер ПN=\"".$owner_n."\" ИдПроизвИмп=\"".$data['importers'][$owner_id]['n']."\">\n";
        			$product_n=1;
        			foreach($products as $product) {
        				$xml.="<Движение ПN=\"".$product_n."\" П100000000006=\"".number_format($product['stock0'], 5, '.', '')."\" П100000000007=\"0.00000\" П100000000008=\"".number_format($product['goods'], 5, '.', '')."\" П100000000009=\"".number_format($product['goods'], 5, '.', '')."\" П100000000010=\"".number_format($product['returns'], 5, '.', '')."\" П100000000011=\"".number_format($product['other_in'], 5, '.', '')."\" П100000000012=\"".number_format($product['movein'], 5, '.', '')."\" П100000000013=\"".number_format($product['goods']+$product['returns']+$product['other_in']+$product['movein'], 5, '.', '')."\" П100000000014=\"".number_format($product['sales'], 5, '.', '')."\" П100000000015=\"".number_format($product['other_out'], 5, '.', '')."\" П100000000016=\"0.00000\" П100000000017=\"".number_format($product['moveout'], 5, '.', '')."\" П100000000018=\"".number_format($product['sales']+$product['other_out']+$product['moveout'], 5, '.', '')."\" П100000000019=\"".number_format($product['stock1'], 5, '.', '')."\" П100000000020=\"0\" />\n";
        				$product_n++;
        			}
        			$xml.="</СведПроизвИмпортер>\n";
        			$owner_n++;
        		}

        		$xml.="</Оборот>\n";
        		$type_n++;
        	}
        }
		$xml.="</ОбъемОборота>\n";
		$xml.="</Документ>\n";
		$xml.="</Файл>\n";
		return array(
			'xml'=>$xml,
			'name'=>$this->gen_declaration_name('07', $q, $year)
		);
	}

	// Отправка декларации
	function send_declaration($name, $xml) {
		$xml_file=$this->f3->get('ROOT').'/tmp/'.$name;
		$xml=iconv("UTF-8", "windows-1251", $xml);
		$this->f3->write($xml_file, $xml);
		$options = array(
			'method'=>'POST',
    		'header'=>array(
    			'accept: application/json',
    			'Content-Type: multipart/form-data'
    		),
    		'content'=>array(
    			'xml_file'=>new \CURLFile($xml_file, '', $name)
    		),
    		'timeout'=>5
		);
		$request=$this->web->request($this->url_egais.'/api/declaration', $options);
		$body=json_decode($request['body'], true);
		unlink($xml_file);
		if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		elseif(is_array($body)) {
			return array(
				'success'=>false,
				'txt'=>$body['message']
			);
		}
		else {
			return array(
				'success'=>false,
				'txt'=>$request['body']
			);
		}

		return array(
			'success'=>false,
			'txt'=>'error'
		);
	}

	function declaration($data) {
		// Распределяем данные, чтобы формировать декларации отдельно по крепкому алкоголю и пиву, переводим кол-во в литры
		$quantity_key=array(
			'stock0',
			'goods',
			'returns',
			'movein',
			'other_in',
			'sales',
			'moveout',
			'other_out',
			'stock1'
		);
		foreach ($data['product'] as $key => $value) {
			$oborot=0;
			foreach($quantity_key as $qkey) {
				$value[$qkey]=($value[$qkey]*$value['capacity'])/10;
				if($qkey!='stock0' && $qkey!='stock1') $oborot+=$value[$qkey];
			}
			if($oborot>0) $declaration[$value['egais']]['products'][$value['productType_Code']][$value['owner_id']][]=$value;
			$owner=array(
				'owner_ID'=>$value['owner_id'],
				'full_Name'=>$value['full_Name'],
				'kpp'=>$value['kpp'],
				'inn'=>$value['inn'],
			);
			$declaration[$value['egais']]['importers'][$value['owner_id']]=$owner;
		}

		$declaration_number=time();

		if(isset($declaration[1])) {
			// Формируем декларацию по крепкому алкоголю
			$xml=$this->alc_declaration($declaration_number, $this->q[$data['q']], $data['year'], $declaration[1]);
			$alc_result=$this->send_declaration($xml['name'], $xml['xml']);
		}
		else {
			$alc_result=array(
				'success'=>true
			);
		}

		if(isset($declaration[2])) {
			// Формируем декларацию по крепкому алкоголю
			$xml=$this->beer_declaration($declaration_number, $this->q[$data['q']], $data['year'], $declaration[2]);
			$beer_result=$this->send_declaration($xml['name'], $xml['xml']);
		}
		else {
			$beer_result=array(
				'success'=>true
			);
		}


		if($alc_result['success'] && $beer_result['success']) {
			return array(
				'success'=>true,
				'txt'=>'request_is_sended'
			);
		}
		else {
			$errors=array();
			if(!$alc_result['success']) {
				$errors[]=$xml_result['txt'];
			}
			if(!$beer_result['success']) {
				$errors[]=$beer_result['txt'];
			}
			return array(
				'success'=>false,
				'txt'=>implode('; ', $errors)
			);
		}
	}

	// Документы по фильтру
	function receipt_filtr($period=array(), $types=array()) {
		$limit=100;
		$offset=0;
		$stop=false;
		$receipts=array();
		$options = array(
			'method'=>'GET',
    		'header'=>array(
    			'accept: application/json'
    		)
		);
		while(!$stop) {
			$request=$this->web->request($this->url_egais.'/api/db/out/list?limit='.$limit.'&offset='.$offset, $options);
			$body=json_decode($request['body'], true);
			if(mb_strpos($request['headers'][0], '200')>0 || mb_strpos($request['headers'][1], '200')>0) {
				if(!$body['rows']) {
					$stop=true;
					break;
				}
				foreach($body['rows'] as $r) {
					if($period) {
						$time=strtotime($r['createTimestamp']);
						if($time<$period[0] || $time>$period[1]) {
							continue;
						}
						if($time<$period[0]) {
							$stop=true;
							break;
						}
					}
					if($types) {
						if(!in_array($r['docType'], $types)) {
							continue;
						}
					}
					$xml=$this->ticket_xml('out', $r['id']);
					if(!$xml['success']) {
						return $xml;
					}
					$r['xml']=$xml['xml'];
					$receipts[]=$r;
				}
				$offset+=$limit;
				continue;
			}
			if($body['message']) {
				return array(
					'success'=>false,
					'txt'=>$body['message']
				);
			}
			if($body['error']) {
				return array(
					'success'=>false,
					'txt'=>$body['error']
				);
			}
			return array(
				'success'=>false,
				'txt'=>implode(';', $request)
			);
		}

		return array(
			'success'=>true,
			'receipts'=>$receipts
		);
	}

	function searchindocs($code) {
		$offset=0;
		$limit=100;
		$stop=false;
		$receipt=array();
		while(!$stop) {
			$receipts=$this->out_list($limit, $offset);
			if($receipts['success']) {
				if(!$receipts['receipts']){
					return array(
						'success'=>false,
						'txt'=>'not_found'
					);
				}
				foreach($receipts['receipts'] as $r){
					if($r['docType']=='waybill_v4' || $r['docType']=='replyrests') {
						$ticket=$this->ticket_xml('out', $r['id']);
						if($ticket['success'] && mb_strpos($ticket['xml'], $code)>0) {
							$r['xml']=$ticket['xml'];
							$receipt=$r;
							$stop=true;
							break;
						}
					}
				}
			}
			$offset+=$limit;
			if(!$receipts['receipts']){
				return array(
					'success'=>false,
					'txt'=>'not_found'
				);
			}
		}
		if($receipt['id']>0) {
			if($receipt['docType']=='waybill_v4') {
				$data=$this->xml_to_ttn($receipt['xml']);
				if($data['ttn']['products']) {
					foreach($data['ttn']['products'] as $p) {
						if($p['AlcCode']==$code) {
							return array(
								'success'=>true,
								'product'=>$p
							);
						}
					}
				}
			}
			if($receipt['docType']=='replyrests') {
				$data=$this->xml_to_rests($receipt['xml']);
				if($data['receipt']['positions']) {
					foreach($data['receipt']['positions'] as $p){
						if($p['Product']['AlcCode']==$code) {
							return array(
								'success'=>true,
								'product'=>$p['Product']
							);
						}
					}
				}
			}
		}
		return array(
			'success'=>false,
			'txt'=>'not_found'
		);
	}
}
