<?php
namespace Controllers;
// Контроллер для кранов
class Taps extends Controller {

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

	// Список кранов
	function list() {
		$taps=$this->model->select_taps();
		$this->f3->set('taps', $taps);
		$this->f3->set('page_data', $this->model->page_data('list'));
	}

	// Форма добавления и редактирования кранов
	function form() {
		$inc='add';
		$id=$this->f3->get('GET.id');
		if($id) {
			$tap=$this->model->select_taps(array('id=?', $id), array('limit'=>1));
			if(empty($tap)) {
				$this->f3->set('page_data', $this->messages->message('not_found'));
				return;
			}
			$inc='change';
		}
		$this->f3->set('data', $tap[0]);
		$this->f3->set('page_data', $this->model->page_data($inc));
	}

	function post_form() {
		$post=$this->f3->get('POST');
		$res=$this->model->save_tap($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Страница крана
	function tap() {
		$id=$this->f3->get('GET.id');
		$tap=$this->model->select_taps(array('id=?', $id), array('limit'=>1));
		if(empty($tap)) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$this->f3->set('tap', $tap[0]);
		$this->f3->set('page_data', $this->model->page_data('tap'));
	}

	// Удаление крана
	function delete() {
		$id=$this->f3->get('GET.id');
		$res=$this->model->delete_tap($id);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	//Подключение к крану
	function connection() {
		$id=$this->f3->get('GET.id');
		$tap=$this->model->select_taps(array('id=?', $id), array('limit'=>1));
		if(empty($tap)) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$this->f3->set('tap', $tap[0]);
		$this->f3->set('page_data', $this->model->page_data('connection'));
	}

	function connection_select_product() {
		$post=$this->f3->get('REQUEST');
		$products=array();
		$p=new \Models\Products($this->db, $this->f3);
		$page=$post['page'];
		if(!$page) $page=1;
		$limit=$this->f3->get('lines_of_page');
		$res=$p->search($post['product_search'], ($page-1)*$limit, $limit, false, $post['exact_match']??0, $post['in_stock']??0, $post['order']??null, true);
		$this->f3->set('pagination', $this->pagination($res['count'], $page));
		$this->f3->set('products', $res['products']);
		$this->f3->set('page_data', $this->model->page_data('connection_select_product'));
	}

	// Сохранение подключеной тары
	function post_connection() {
		$post=$this->f3->get('REQUEST');
		$tap=$this->model->select_taps(array('id=?', $post['id']), array('limit'=>1));
		if(empty($tap)) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('not_found')['txt']
			);
			echo json_encode($res);
			exit();
		}

		$mark=$post['mark'];
		$mark_line=$mark;

		if($this->sets['gs1_symbols']!='') {
        	$mark=str_replace($this->sets['gs1_symbols'], '', $mark);
        	$mark_line=str_replace($this->sets['gs1_symbols'], '\\u001d', $mark);
        	//$post['mark']=str_replace($this->sets['gs1_symbols'], '\u001d', $post['mark']);
        }

		$receipts=new \Models\Receipts($this->db, $this->f3);
		$changes=new \Models\Changes($this->db, $this->f3);
		$change=$changes->get_change();

		if(!isset($post['connection'])) {
			if($this->model->count(array('mark=? AND connection=1', array($post['mark'])))>0) {
				$this->f3->set('txt', $this->messages->message('keg_is_connection')['txt']);
				$this->f3->set('base_settings.check_mark', 0);
				$this->f3->set('page_data', $this->model->page_data('tap_marking_error'));
				return;
			}

			if(preg_match("/[А-Яа-я]/", $mark)) {
    			$this->f3->set('base_settings.check_mark', 0);
				$this->f3->set('txt', $this->messages->message('cyrilic_symbols_from_mark')['txt']);
				$this->f3->set('page_data', $this->model->page_data('tap_marking_error'));
				return;
    		}
    		
			$this->f3->set('alert', 0);
			if(mb_substr($post['mark'], 2, 14)==mb_substr($tap[0]['mark'], 2, 14)) {
				$this->f3->set('tap', $tap[0]);
			}
			elseif($tap[0]['mark']!='') {
				$this->f3->set('alert', 1);
			}
			if(!isset($post['not_check_mark']) || $post['not_check_mark']!=1) {

				if((!isset($post['not_check_mark']) || $post['not_check_mark']<1) && !$this->model->check_mark_connection($post['mark'])) {
					$this->f3->set('not_check_mark', 2);
					$this->f3->set('base_settings.check_mark', 1);
					$this->f3->set('txt', $this->messages->message('keg_is_connection_previously')['txt']);
					$this->f3->set('page_data', $this->model->page_data('tap_marking_error'));
					return;
				}

				$required_check=$this->sets['required_check_16']??0;
				if((int)$required_check>0) {
					$this->sets['check_chz']=0;
					$line=array(
						'marking_group'=>'16',
						'price'=>0,
						'vat'=>0,
						'vat_type'=>0
					);
					$mark_res=$receipts->check_mark_chz($this->sets, $line, $mark);
					$this->f3->set('result', $mark_res['result']);

					if($mark_res['success']===false) {
						$this->f3->set('mark_code', $mark_code);
						$this->f3->set('check_result', $mark_res['check_result']);
						$this->f3->set('txt', $this->messages->message($mark_res['txt'])['txt']);
						$this->f3->set('error_type', $mark_res['error_type']);
						$this->f3->set('page_data', $this->model->page_data('tap_marking_error'));
						return;
					}
				}
				else {
					$mark_res=$receipts->check_mark($mark, 1, 41, $this->sets['check_chz']);
					if($mark_res['success']===false) {
						$this->f3->set('txt', $this->messages->message($mark_res['txt'])['txt']);
						$this->f3->set('error_type', $mark_res['error_type']);
						$this->f3->set('page_data', $this->model->page_data('tap_marking_error'));
						return;
					}
				}
			}
			$products=array();
			$p=new \Models\Products($this->db, $this->f3);
			if(isset($post['product_id']) && $post['product_id']>0) {
				$products=$p->select_product(array('p.id=?', $post['product_id']), array('limit'=>1));
			}
			if(empty($products)) {
				$barcode=mb_substr($mark, 3, 13);
				$prod=$p->search($barcode, 0, 1, true);
				if($prod['success']) {
					$products=$prod['products'];
				}
			}
			$count=count($products);
			if($count==0 && (!isset($post['product_id']) || $post['product_id']>0)) {
				$this->f3->set('GET.page', 1);
				$this->f3->set('URI', '/taps/connection_select_product?'.http_build_query($post).'&page=1');
				return $this->connection_select_product();
			}
			if($count!=1 && (!isset($post['product_id']) || $post['product_id']>0)) {
				$this->f3->set('products', $products);
				$this->f3->set('page_data', $this->model->page_data('connection_select_product'));
				return;
			}

			$products[0]['capacity']=$p->get_capacity($products[0]['id']);
			$this->f3->set('products', $products);

			$this->f3->set('page_data', $this->model->page_data('connection'));
			return;
		}
		$p=new \Models\Products($this->db, $this->f3);
		$products=$p->select_product(array('p.id=?', $post['product_id']), array('limit'=>1));
		$tap[0]['product']=$products[0];
		$tap[0]['mark']=$mark_line;
		$tap[0]['product_title']=$post['product_title'];
		$tap[0]['connection_time']=time();
		$tap[0]['expiration']=$post['expiration'];
		$tap[0]['volume']=$post['volume'];
		$tap[0]['current_volume']=$post['volume'];
		$tap[0]['type']=$this->f3->get('receipt_keg_connection');
		$tap[0]['rm']=$this->api_data['rm_id'];
		$tap[0]['store']=$this->api_data['store_id'];
		$tap[0]['connection']=$post['connection'];
		$tap[0]['product_id']=$post['product_id'];
		$res=$receipts->keg_connection($tap[0], $change);
		if($res['success']==true) {
			$receiptlines=new \Models\Receiptlines($this->db, $this->f3);
			$time=str_replace(',', '.', microtime(true));
			$line=array(
				'product_title'=>$tap[0]['product_title']!=''?$tap[0]['product_title'].' ('.$tap[0]['title'].')':$tap[0]['title'],
				'price'=>0,
				'count'=>$tap[0]['volume'],
				'id'=>-time(),
				'mark'=>json_encode(array($mark_line)),
				'other_info'=>json_encode($tap[0]),
			);
			$receiptlines->add_line($res['id'], $line, $line['count'], 0, $time, $time, $time);
			$res=$this->model->save_tap($tap[0]);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function product_add() {
		$this->f3->set('page_data', $this->model->page_data('product_add'));
	}

	function post_product_add() {
		$post=$this->f3->get("POST");
		$res_products=array();
		if(isset($post['product_add_search'])) {
			$products=new \Models\Products($this->db, $this->f3);
			$prods=$products->search($post['product_add_search']);
			if($prods['success']) {
				foreach($prods['products'] as $p) {
					if((int)$p['marking_group']==16) {
						$res_products[]=$p;
					}
				}
			}
			if(count($res_products)==1) {
				$post['product_id'][]=$res_products[0]['id'];
			}
			elseif(!empty($res_products)) {
				$this->f3->set('products', $res_products);
				$this->f3->set('page_data', $this->model->page_data('product_add'));
				return;
			}
		}
		if(isset($post['product_id'])) {
			foreach($post['product_id'] as $product_id) {
				$data=array(
					'tap_id'=>$post['tap_id'],
					'product_id'=>$product_id
				);
				$res=$this->model->product_add($data);
				if(!$res['success']) {
					break;
				}
			}
			$res['txt']=$this->messages->message($res['txt'])['txt'];
			echo json_encode($res);
			exit();
		}

		$res=array(
			'success'=>false,
			'txt'=>$this->messages->message('not_found')['txt']
		);
		echo json_encode($res);
		exit();
	}

	// Удаление товара с крана
	function product_delete() {
		$get=$this->f3->get('GET');
		$res=$this->model->product_delete($get);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Отключение кега
	function unconnection() {
		$get=$this->f3->get('GET');
		$res=$this->model->unconnection($get);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Окно переноса на другой кран
	function move() {
		$id=$this->f3->get('GET.id');
		$tap=$this->model->select_taps(array('id=?', $id), array('limit'=>1));
		if(empty($tap)) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$this->f3->set('tap', $tap[0]);
		$taps=$this->model->select_taps(array('connection=?', 0));
		$this->f3->set('taps', $taps);
		$this->f3->set('page_data', $this->model->page_data('move'));
	}

	// Перенос на другой кран
	function post_move() {
		$post=$this->f3->get('POST');
		$res=$this->model->move($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}
}
