<?php
namespace Controllers;
// Контроллер Настроек
class Egais extends Controller {

	public function __construct() {
		parent::__construct();
		$this->model=new \Models\Egais($this->db, $this->f3);
	}

	// Главная страница (Входящие документы)
	function main() {
		$limit=$this->f3->get('lines_of_page');
		$page=$this->f3->get('GET.page');
		if(!$page)$page=1;
		$data=$this->model->out_list($limit, ($page-1)*$limit);
		$this->f3->set('pagination', $this->pagination($data['total'], $page));
		if($data['success']) {
			$data['receipts']=$this->model->filtr_type($data['receipts'], array('replyrests', 'replynattn', 'waybillticket', 'waybill_v4', 'waybillact_v4', 'replyrestbcode'));
		}
		$this->f3->set('data', $data);
		$this->f3->set('page_data', $this->model->page_data('main'));
	}

	function preview_waybill_v4() {
		$get=$this->f3->get('GET');
		$ttn=$this->model->ttn($get['id']);
		if(!$ttn['success']) {
			$this->f3->set('page_data', $this->messages->message($ttn['txt']));
			return;
		}
		$this->f3->set('ttn', $ttn['ttn']);
		$this->f3->set('page_data', $this->model->page_data('waybill_v4'));
	}

	function preview_replyrests() {
		$get=$this->f3->get('GET');
		$rests=$this->model->rests_array($get['id']);
		if(!$rests['success']) {
			$this->f3->set('page_data', $this->messages->message($rests['txt']));
			return;
		}
		$this->f3->set('rests', $rests['receipt']);
		$this->f3->set('page_data', $this->model->page_data('replyrests'));
	}

	function preview_replynattn() {
		$get=$this->f3->get('GET');
		$nattn=$this->model->replynattn($get['id']);
		if(!$nattn['success']) {
			$this->f3->set('page_data', $this->messages->message($nattn['txt']));
			return;
		}
		$this->f3->set('nattn', $nattn['nattn']);
		$this->f3->set('page_data', $this->model->page_data('replynattn'));
	}

	function preview_replyrestbcode() {
		$get=$this->f3->get('GET');
		$rest=$this->model->replyrestbcode($get['id']);
		if(!$rest['success']) {
			$this->f3->set('page_data', $this->messages->message($rest['txt']));
			return;
		}
		$product=$this->model->product_from_bcode($get['id'], $rest['rest']['Inform2RegId']);
		if($product['success']) {
			$this->f3->set('product', $product['product']);
		}
		else {
			$this->f3->set('product', '');
		}
		$this->f3->set('rest', $rest['rest']);
		$this->f3->set('page_data', $this->model->page_data('replyrestbcode'));
	}

	// Просмотр документа
	function ticket() {
		$get=$this->f3->get('GET');
		if(method_exists($this, 'preview_'.$get['type'])) {
			$class='preview_'.$get['type'];
			return $this->$class();
		}
		$ticket=$this->model->ticket($get['folder'], $get['type'], $get['id']);
		$this->f3->set('ticket', $ticket);
		$this->f3->set('page_data', $this->model->page_data('ticket'));
	}

	// Служебная информация
	function utminfo() {
		$res=$this->model->utminfo();
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		$this->f3->set('data', $res);
		$this->f3->set('page_data', $this->model->page_data('utminfo'));
	}

	// Запрос остатков
	function rests() {
		$res=$this->model->rests();
		$this->f3->set('data', $res);
		$this->f3->set('page_data', $this->messages->message($res['txt']));
	}

	// Акт по накладной
	function ttnact() {
		$get=$this->f3->get('GET');
		$ttn=$this->model->ttn($get['id']);
		if(!$ttn['success']) {
			$this->f3->set('page_data', $this->messages->message($ttn['txt']));
			return;
		}
		if($ttn['ttn']['identity']) {
			// Пытаемся найти regId
			$regid=$this->model->ttn_regid($ttn['ttn'], $get['id']);
			if($regid['success']) {
				$ttn['ttn']['regid']=$regid['regid'];
				if($regid['position']) {
					foreach ($regid['position'] as $i => $v) {
						$ttn['ttn']['products'][(string)$i]=array_merge($ttn['ttn']['products'][(string)$i], $v);
					}
				}
			}
		}
		$this->f3->set('ttn', $ttn['ttn']);
		if($get['accept']=='repeal') {
			$this->f3->set('page_data', $this->model->page_data('ttnact_repeal'));
		}
		else {
			$this->f3->set('page_data', $this->model->page_data('ttnact'));
		}
	}

	// Отправка акта по накладной
	function post_ttnact() {
		$post=$this->f3->get('POST');
		$res=$this->model->ttnact($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Отправка запроса отмены акта по накладной
	function post_ttnact_repeal() {
		$post=$this->f3->get('POST');
		$res=$this->model->ttnact_repeal($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Запрос на получения списка необработанных накладных
	function nattn() {
		$res=$this->model->nattn();
		$this->f3->set('data', $res);
		$this->f3->set('page_data', $this->messages->message($res['txt']));
	}

	// Списание
	function writeoff() {
		$rests=$this->model->get_rests();
		if(!$rests['success']) {
			$rests['txt']=$this->messages->message($res['txt'])['txt'];
		}
		$this->f3->set('data', $rests);
		$this->f3->set('page_data', $this->model->page_data('writeoff'));
	}

	// Отправка запроса на списание
	function post_writeoff() {
		$post=$this->f3->get('POST');
		$res=$this->model->writeoff($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
	}

	// Отменить списание
	function writeoff_repeal() {
		$this->f3->set('page_data', $this->model->page_data('writeoff_repeal'));
	}

	// Отправка отмены списания
	function post_writeoff_repeal() {
		$post=$this->f3->get('POST');
		$res=$this->model->writeoff_repeal($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
	}

	// Накладная
	function createttn() {
		$get=$this->f3->get('GET');
		if($get['ClientRegId']) {
			if($get['address_data']) {
				$get['address']=$get['address_data'];
			}
			$this->f3->set('partner', $get);
		}

		$rests=$this->model->get_rests();
		if(!$rests['success']) {
			$rests['txt']=$this->messages->message($rests['txt'])['txt'];
		}
		$this->f3->set('data', $rests);
		$this->f3->set('page_data', $this->model->page_data('ttn'));
	}

	// Отправка накладной
	function post_createttn() {
		$post=$this->f3->get('POST');
		$res=$this->model->createttn($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
	}

	// Поиск организации
	function organizations() {
		$get=$this->f3->get('GET');
		$data=$this->model->get_organization($get);
		if(!$data['success']) {
			$data['txt']=$this->messages->message($data['txt'])['txt'];
		}
		$this->f3->set('data', $data);
		$this->f3->set('page_data', $this->model->page_data('organizations'));
	}

	// Актуализация пивных остатков
	function beer_currentstock() {
		$rests=$this->model->get_rests();
		if(!$rests['success']) {
			$rests['txt']=$this->messages->message($rests['txt'])['txt'];
			$data=$rests;
		}
		else {
			$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
			$beer=$api->beers_stock();
			if(!$beer['success']) {
				$data=$beer;
			}
			else {
				$positions=$this->model->beer_currentstock($rests['receipt']['positions'], $beer['stock']);
				if($positions['success']) {
					$rests['positions']=$positions['positions'];
					$rests['error']=$positions['error'];
				}
				$data=$rests;
			}
		}
		$this->f3->set('data', $data);
		$this->f3->set('page_data', $this->model->page_data('beer_currentstock'));
	}

	function related() {
		$get=$this->f3->get('GET');
		$receipts=$this->model->related($get['id']);
		if(!$receipts['success']) {
			$receipts['txt']=$this->messages->message($receipts['txt'])['txt'];
		}
		$this->f3->set('receipts', $receipts);
		$this->f3->set('page_data', $this->model->page_data('related'));
	}

	function send_ttn() {
		$get=$this->f3->get('GET');
		$ttn=$this->model->ttn($get['id']);
		if(!$ttn['success']) {
			$this->f3->set('page_data', $this->messages->message($ttn['txt']));
			return;
		}
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		$res=$api->send_ttn($ttn['ttn']);
		$this->f3->set('result', $res);
		$this->f3->set('page_data', $this->model->page_data('send_ttn'));
	}

	// Поиск ТТН по рег. номеру
	function search_ttn() {
		$get=$this->f3->get('GET');
		$ttn=$this->model->search_ttn($get);
		if(!$ttn['success']) {
			$this->f3->set('page_data', $this->messages->message($ttn['txt']));
			return;
		}
		$this->f3->set('GET.id', $ttn['id']);
		$ttn=$this->model->ttn($ttn['id']);
		if(!$ttn['success']) {
			$this->f3->set('page_data', $this->messages->message($ttn['txt']));
			return;
		}
		$this->f3->set('ttn', $ttn['ttn']);
		$this->f3->set('page_data', $this->model->page_data('waybill_v4'));
	}

	// Отправляем в Агорту остатки по складу, чтобы создать документ инвентаризации
	function send_replyrests() {
		$get=$this->f3->get('GET');
		$rests=$this->model->rests_array($get['id']);
		if(!$rests['success']) {
			$this->f3->set('page_data', $this->messages->message($rests['txt']));
			return;
		}
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		$res=$api->send_replyrests($rests['receipt']);
		$this->f3->set('result', $res);
		$this->f3->set('page_data', $this->model->page_data('send_replyrests'));
	}

	// Запрос оставшихся марок в форме Б
	function restbcode() {
		$formb=$this->f3->get('GET.formb');
		$res=$this->model->restbcode($formb);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
	}

	function declaration_from_agorta($period) {
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		$times=explode('-', $period);
		$time0=date('Y-m-d', strtotime($times[2]));
		$time1=date('Y-m-d', strtotime($times[3]));
		$res=$api->alcodeclaration($time0, $time1);
		if($res['success']) {
			// Найдем по алкокодам информацию о продукции
			$alcocodes=array_column($res['result'], 'alcocode');
			$products_info=array();
			if($alcocodes) {
				$products_info=$this->model->nsi_productions($alcocodes);
				$products_info=array_combine(array_column($products_info['products'], 'alc_Code'), $products_info['products']);
				// найдем информацию по производителям
				$owners=array();
				$owner_id=array_column($products_info, 'owner_id');
				$owners_info=$this->model->nsi_organizations(array_unique($owner_id));
				if($owners_info['success']) {
					$owners=array_combine(array_column($owners_info['organizations'], 'owner_ID'), $owners_info['organizations']);
				}
			}
			$this->f3->set('products_info', $products_info);
			$this->f3->set('owners', $owners);
			$this->f3->set('products', $res['result']);
		}
		else {
			$this->f3->set('error', $this->messages->message($res['error'][0])['txt']);
		}
		$this->f3->set('Q', $times[0]);
		$this->f3->set('year', $times[1]);
	}

	function declaration_from_utm($period) {
		$times=explode('-', $period);
		$time0=strtotime($times[2]);
		$time1=strtotime($times[3]);
		$this->f3->set('Q', $times[0]);
		$this->f3->set('year', $times[1]);
		$receipts=$this->model->receipt_filtr(array($time0, $time1), array('WayBill_v4'));
		if($receipts['success']) {
			$products_info=array();
			$owners=array();
			foreach($receipts['receipts'] as $r) {
				$ttn=$this->model->xml_to_ttn($r['xml'])['ttn'];
				foreach($ttn['products'] as $p) {
					if(!$products_info[$p['AlcCode']]) {
						$p['productType_Code']=$p['ProductVCode'];
						$p['capacity']=$p['Capacity'];
						$p['owner_id']=$p['Producer']['ClientRegId'];
						$p['Producer']['full_Name']=$p['Producer']['FullName'];
						$p['Producer']['inn']=$p['Producer']['INN'];
						$p['Producer']['kpp']=$p['Producer']['KPP'];
						$products_info[$p['AlcCode']]=$p;
					}
					if(!$owners[$p['Producer']['ClientRegId']]) {
						$owners[$p['Producer']['ClientRegId']]=$p['Producer'];
					}
					$products_info[$p['AlcCode']]['goods']+=$p['Quantity'];
					$products[$p['AlcCode']]=array(
						'title'=>$p['FullName'],
						'egais'=>($p['MarkInfo']['amc']?1:2),
						'goods'=>$products_info[$p['AlcCode']]['goods'],
						'stock1'=>$products_info[$p['AlcCode']]['goods']
					);
				}
			}
			$this->f3->set('products_info', $products_info);
			$this->f3->set('owners', $owners);
			$this->f3->set('products', $products);
		}
		else {
			$this->f3->set('error', $this->messages->message($res['error'])['txt']);
		}
	}

	// Алкодекларации
	function declaration() {
		$get=$this->f3->get('GET');
		if($get['period']) {
			$method='declaration_from_'.$get['from'];
			$this->$method($get['period']);
		}
		$period=array(
			1=>array('start'=>'01.01', 'end'=>'31.03'),
			2=>array('start'=>'01.04', 'end'=>'30.06'),
			3=>array('start'=>'01.07', 'end'=>'30.09'),
			4=>array('start'=>'01.10', 'end'=>'31.12'),
		);
		$this->f3->set('period', $period);
		$this->f3->set('page_data', $this->model->page_data('declaration'));
	}

	// Отправка алкодекларации
	function post_declaration() {
		$post=$this->f3->get('POST');
		$res=$this->model->declaration($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
	}

	// Поиск информации о продукции в документах
	function searchindocs() {
		$get=$this->f3->get('GET');
		$res=$this->model->searchindocs($get['alcocode']);
		if(!$res['success']) {
			$this->f3->set('page_data', $this->messages->message($res['txt']));
			return;
		}
		$this->f3->set('product', $res['product']);
		$this->f3->set('page_data', $this->model->page_data('searchindocs'));
	}
}