<?php
namespace Controllers;

// Контроллер для чеков
class Receipts extends Controller {
	public $products, $changes, $receiptlines, $receipts_types, $receipt_sets, $device;

	public function __construct() {
		parent::__construct();
		$device=$this->f3->get('GET.device');
		if(!$device)$device='kkm';
		$this->device=$device;
		$this->model=new \Models\Receipts($this->db, $this->f3, $device);
		$this->receiptlines=new \Models\Receiptlines($this->db, $this->f3);
		$this->products=new \Models\Products($this->db, $this->f3);
		$this->changes=new \Models\Changes($this->db, $this->f3);
		$this->receipts_types=array(
			'sales'=>$this->f3->get('receipt_sales'),
			'return'=>$this->f3->get('receipt_return'),
			'correct_sales'=>$this->f3->get('receipt_correct_sales'),
			'correct_return'=>$this->f3->get('receipt_correct_return'),
			'cashin'=>$this->f3->get('receipt_cashin'),
			'cashout'=>$this->f3->get('receipt_cashout')
		);
		$this->receipt_sets=array(
			'rm'=>$this->api_data['rm_id'],
			'store'=>$this->api_data['store_id'],
			'prefix'=>$this->sets['orders_prefix']
		);
		if(!$this->cd) {
			$this->cd=new \Models\Cd($this->db, $this->f3);
		}
	}

	function product_search() {
		$product_model=new \Models\Products($this->db, $this->f3);
		$config=parse_ini_file($this->f3->get('ROOT').'/ui/kiosk/'.$this->sets['kiosk_type'].'/config.ini');
		$term=$this->f3->get('GET.product_search');
		$order=$this->f3->get('GET.order');
		$exact_match=$this->f3->get('GET.exact_match');
		$this->f3->set('exact_match', $exact_match);
		$in_stock=$this->f3->get('GET.in_stock');
		$this->f3->set('in_stock', $in_stock);
		if(!$order) {
			$order=false;
		}
		$products=array();
		if($config['pagination']==1) {
			$page=$this->f3->get('GET.page');
			if(!$page) $page=1;
			$this->f3->set('page', $page);
			$limit=$this->sets['lines_of_list'];
			$res=$product_model->search($term, ($page-1)*$limit, $limit, false, $exact_match, $in_stock, $order);
		}
		else {
			$res=$product_model->search($term, 0, 0, false, $exact_match, $in_stock, $order);
		}
		if($res['success']) {
			$products=$res['products'];
		}

		if($config['catalog']==1 && $config['pagination']==0 && $products) {
			$c=new \Models\Productcategories($this->db, $this->f3);
			$categories=$c->categories_list();
			if($categories) {
				$categories=array_combine(array_column($categories, 'id'), $categories);
				foreach($products as $p) {
					$categories[$p['category_id']]['products'][]=$p;
				}
			}
			$this->f3->set('categories', $categories);
		}
		
		$this->f3->set('products', $products);
		$this->f3->set('page_data', $this->model->page_data('sales'));
	}

	// Раздел продаж
	function sales() {
		if(!$this->f3->get('AJAX')) {
			$this->f3->set('COOKIE.return', $this->f3->get('return'));
		}
		if($this->f3->get('authorization_user.kiosk')==1 && file_exists($this->f3->get('ROOT').'/ui/kiosk/'.$this->sets['kiosk_type'].'/config.ini')) {
			$config=parse_ini_file($this->f3->get('ROOT').'/ui/kiosk/'.$this->sets['kiosk_type'].'/config.ini');

			if($config['catalog']==1 && $config['pagination']==0) {
				$c=new \Models\Productcategories($this->db, $this->f3);
				$categories=$c->categories_list();
				if($categories) {
					$categories=array_combine(array_column($categories, 'id'), $categories);
					$products=$this->products->select_product(array('p.date_delete=0 AND (p.stop=0 OR p.stop IS NULL)'));
					if($products) {
						foreach($products as $p) {
							$p['img']=json_decode($p['img'], true);
							if(!isset($categories[$p['category_id']])) {
								$categories[$p['category_id']]=array(
									'title'=>'Без категории',
									'show'=>1,
									'partner_id'=>0
								);
							}
							$categories[$p['category_id']]['products'][]=$p;
						}
					}
				}
				$this->f3->set('categories', $categories);
			}
			if($config['catalog']==1 && $config['pagination']==1) {
				$c=new \Controllers\Products();
				$c->list(false);
			}
		}
		elseif((int)$this->sets['product_menu']>0) {
			$c=new \Controllers\Products();
			$c->list();
		}

		$scales=new \Models\Scales($this->db, $this->f3);
		$this->f3->set('scales_settings', $scales->sets);
		// Проверяем нужно ли выбрать стол
		if($this->sets['cafe_mode']==1 && $this->f3->get('authorization_user.kiosk')!=1) {
			$table_id=$this->f3->get('GET.table_id');
			if(!$table_id) {
				$table_id=$this->f3->get('COOKIE.table_id');
			}
			$t=new \Models\Tables($this->db, $this->f3);
			$tables=$t->select_tables();
			$tables_count=count($tables);
			if(!$table_id || $this->f3->get('GET.room_id')) { // Если стол не выбран, то откроем режим выбора столов
				// Сначала проверим сколько столов во всех залах
				$t=new \Models\Tables($this->db, $this->f3);
				$tables=$t->select_tables();
				// Если стол всего один, то автоматом его выбираем
				if($tables_count==1) {
					$table_id=$tables[0]['id'];
					$this->f3->set('COOKIE.table_id', $table_id);
				}
				else {
					$r=new \Controllers\Rooms($this->db, $this->f3);
					$r->select_table();
					return;
				}
			}
			if($tables_count>1) {
				$r=new \Models\Rooms($this->db, $this->f3);
				$rooms=$r->select_rooms();
			}
			else {
				$rooms=array();
			}
			$this->f3->set('tables_count', $tables_count);
			$this->f3->set('kkm_sets', $this->model->fr->sets);
			$this->f3->set('rooms', $rooms);
			$fr=new \Models\Fr($this->db, $this->f3, 'kitchen', false);
			$this->f3->set('kitchen_sets', $fr->sets);
			$fr=new \Models\Fr($this->db, $this->f3, 'bar', false);
			$this->f3->set('bar_sets', $fr->sets);
			$fr=new \Models\Fr($this->db, $this->f3, 'pre', false);
			$this->f3->set('pre_sets', $fr->sets);
		}
		else {
			$rooms=array();
			$table_id=0;
		}
		$this->f3->set('modifiers', $this->products->count('related!="" AND date_delete=0'));
		$this->f3->set('COOKIE.table_id', $table_id);
		if(!$this->f3->get('return') && !$this->f3->get('AJAX')) {
			$this->cd->seller_txt();
		}
		if($this->f3->get('return')) {
			$this->cd->close_txt();
		}
		$receiptlines=array();
		$receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts']);
		if($receipt['success']) {
			if(!empty($rooms)) {
				foreach ($rooms as $r) {
					if($r['id']==$receipt['receipt']['table']['room']) {
						$this->f3->set('room', $r);
						break;
					}
				}
			}
			$this->f3->set('COOKIE.receipt_id', $receipt['receipt']['id']);

			$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']), array('order'=>'turn, id'));
			$turns=array_unique(array_column($receiptlines, 'turn'));
			$this->f3->set('turns', $turns);
			if(isset($receipt['receipt']['partner']) && !empty($receipt['receipt']['partner']) && $receipt['receipt']['partner']['loyalty_type']!=1) {
				$receipt['receipt']['discount']=0;
				$this->model->set_discount(0);
			}
			$summ=$this->receiptlines->get_sum($receiptlines, $receipt['receipt']['discount'], $this->sets['round_kop'])['sum'];
			if((int)$this->sets['round_kop']==1) {
				$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']), array('order'=>'turn, id'));
			}
			$this->f3->set('summ', $summ);
			$this->f3->set('receiptlines', $receiptlines);
			$control_sno=$this->receiptlines->control_sno($receiptlines, $this->model->fr->sets['sno']);
			$this->f3->set('sno_org', $this->model->fr->sets['sno']);
			$this->f3->set('control_sno', $control_sno['status']);
			if($this->f3->get('authorization_user.kiosk')==1 && $config['catalog']==0) {
				$products=array();
				$mods=array();
				foreach($receiptlines as $l) {
					if($l['parent_id']>0) {
						$mods[$l['parent_id']][]=$l;
					}
				}
				foreach($receiptlines as $l) {
					if(!isset($mods[$l['id']]) && $l['parent_id']==0 && $l['combo_id']==0) {
						$l['count']+=$products[$l['product_id']]['count'];
						$products[$l['product_id']]=$l;
					}
					else {
						$l['count']=(float)$l['count'];
						$products[-$l['id']]=$l;
					}
				}
				$this->f3->set('mods', $mods);
				$this->f3->set('products', $products);
			}
			$max_bonus_pay=$this->receiptlines->max_bonus_pay($summ, $receipt['receipt']['partner'], $receiptlines);
			$receipt['receipt']['max_bonus_pay']=$max_bonus_pay;
			if($receipt['receipt']['bonus_pay']>0 && $receipt['receipt']['bonus_pay']!=$max_bonus_pay) {
				$bonus_pay_data=$receipt['receipt'];
				$bonus_pay_data['bonus_pay']=0;
				$bonus_pay_change=$this->model->bonus_pay($bonus_pay_data);
				if($bonus_pay_change['success']) {
					$receipt['receipt']['bonus_pay']=$max_bonus_pay;
				}
			}
			$this->f3->set('receipt', $receipt['receipt']);
			$this->f3->set('open_receipts', $receipt['open']);
			$line_id=$this->f3->get('GET.id');
			if(!$line_id && $receiptlines) {
				foreach (array_reverse($receiptlines) as $l) {
					if($l['parent_id']==0) {
						$line_id=$l['id'];
						break;
					}
				}
			}
			$this->f3->set('s', $line_id);
			$loyalty_models=new \Models\Loyalty($this->db, $this->f3);
			$this->f3->set('discounts', $loyalty_models->select_discounts());
			$this->f3->set('page_data', $this->model->page_data('sales'));
			$html=\Template::instance()->render('receiptlines.htm');
			if(file_exists($this->f3->get('UI').'receiptlines_html.htm')) {
				@unlink($this->f3->get('UI').'receiptlines_html.htm');
			}
			$this->f3->write($this->f3->get('UI').'receiptlines_html.htm', $html);
			if(file_exists($this->f3->get('UI').'qr_html.htm')) {
				@unlink($this->f3->get('UI').'qr_html.htm');
			}
			$receipttype=1;
			if($this->f3->get('return')) {
				$receipttype=2;
			}
			elseif($this->f3->get('correct_sales')) {
				$receipttype=128;
				$this->f3->set('page_data["title"]', $this->model->page_data('correct_sales')['title']);
			}
			elseif($this->f3->get('correct_return')) {
				$receipttype=130;
				$this->f3->set('page_data["title"]', $this->model->page_data('correct_return')['title']);
			}
			$this->f3->set('receipttype', $receipttype);
		}
		else {
			$this->f3->set('page_data', $this->messages->message($receipt['txt']));
		}
	}

	function add_linesset() {
		$id=$this->f3->get('GET.id');
		$lns=new \Models\Linesset($this->db, $this->f3);
		$linesset=$lns->select_linesset(array('id=?', $id), array('limit'=>1));
		if(!$linesset) {
			return array(
				'success'=>false,
				'txt'=>$this->messages->message('not_found')
			);
		}
		$pr=new \Models\Products($this->db, $this->f3);
		$res=$pr->add_lineset($linesset[0]['lines']);
		if($res['success']) {
			$res['reroute']='/receipts/sales';
		}
		echo json_encode($res);
		exit();
	}

	// Раздел возрата
	function return() {
		$receipt_id=$this->f3->get('GET.receipt_id');
		if(!$receipt_id) {
			$this->f3->set('return', 1);
			$this->sales();
			$this->f3->set('page_data["title"]', $this->model->page_data('return')['title']);
		}
		else {
			$this->f3->set('fr', $this->model->fr->sets['active']);
			$receipt=$this->model->select_receipts(array('r.id=? AND r.type=1', $receipt_id), array('limit'=>1));
			if($receipt) {
				$p=new \Models\Paymentmethods($this->db, $this->f3);
				$paymentmethods=$p->select_method(null);
				foreach ($paymentmethods as $n => $p) {
					$pays[$p['id']]=$p;
				}
				if($receipt[0]['partner_id']>0) {
					$partners_model=new \Models\Partners($this->db, $this->f3);
					$partner=$partners_model->select_partner(array('partner_id=?', $receipt[0]['partner_id']), array('limit'=>1));
					$this->f3->set('partner', $partner[0]);	
				}

				$this->f3->set('paymentmethods', $pays);
				$this->f3->set('receipt', $receipt[0]);
				$this->f3->set('page_data', $this->model->page_data('return'));
			}
			else {
				$this->f3->set('page_data', $this->messages->message('not_found'));
			}
		}
	}

	// Поиск чеков
	function search() {
		$id=$this->f3->get('GET.id');
		$changes=$this->f3->get('GET.changes');
		$barcode=$this->f3->get('GET.barcode');
		$s=new \Models\Settings($this->f3, $this->db);
		$sets=$s->get_settings(array('weight_code_pr', 'card_code_pr'));
		// Проверяем штрих-код на принадлежность к весовому типу
		if(mb_substr($barcode, 0, 2)==$sets['weight_code_pr'] && mb_strlen($barcode)==13) {
			$barcode=mb_substr($barcode, 0, 7);
		}
		$dates=$this->f3->get('GET.dates');
		$type=$this->f3->get('GET.type');
		if($dates) {
			$dates=str_replace(' ', '', $dates);
			$dates=explode('-', $dates);
			$dates[0]=strtotime($dates[0]);
			$dates[1]=strtotime($dates[1]);
		}
		$limit=$this->f3->get('lines_of_page');
		$page=$this->f3->get('GET.page');
		if(!$page)$page=1;
		$receipts=$this->model->search($id, $changes, $barcode, $dates, $type, ($page-1)*$limit, $limit);
		$this->f3->set('pagination', $this->pagination($receipts['count'], $page));
		$this->f3->set('receipts', $receipts['receipts']);
		$this->f3->set('page_data', $this->model->page_data('search'));
		$this->cd->close_txt();
	}

	// Просмотр чека
	function show() {
		$id=$this->f3->get('GET.id');
		$page_data=$this->messages->message('not_found');
		if($id) {
			$receipts=$this->model->select_receipts(array('r.id=?', $id), array('limit'=>1));
			if($receipts) {
				$p=new \Models\Paymentmethods($this->db, $this->f3);
				$paymentmethods=$p->select_method();
				$pays=array_combine(array_column($paymentmethods, 'id'), $paymentmethods);
				$this->f3->set('paymentmethods', $pays);
				
				$e=new \Models\Epays($this->db, $this->f3);
				$epays=$e->select_epays();
				$epays=array_combine(array_column($epays, 'id'), $epays);
				$this->f3->set('epays', $epays);

				$fr=new \Models\Fr($this->db, $this->f3);
				$sets=$fr->get_fr();
				$this->f3->set('fr', $sets);
				$this->f3->set('receipt', $receipts[0]);
				$page_data=$this->model->page_data('show');
			}
		}
		$this->f3->set('page_data', $page_data);
	}

	//Применение программм лояльности
	function loyalty($receipt, $product) {
		//$с=new \Models\Productcategories($this->db, $this->f3);
		//$parents=$с->get_parents($product['category_id']); // Родительские категории
		// Получаем программы лояльности
		if($receipt['type']==$this->f3->get('receipt_print')) return;
		$l=new \Models\Loyalty($this->db, $this->f3);
		$loyalty=$l->get_loyalty($receipt['partner_id'], $product);
		if(count($loyalty)>0) {
			$this->receiptlines->apply_loyalty($receipt, $product, $loyalty);
		}
	}

	// Отмена акций
	function cancel_loyalty($receipt, $product) {
		$this->receiptlines->cancel_loyalty($receipt, $product);
	}

	// Добавление маркированного товара
	function post_add_marking() {
		$post=$this->f3->get('POST');
		foreach ($post['product'] as $p) {
			$count=$post['count'][$p];
			$receipttype=$post['receipttype'][$p];
			if($this->sets['gs1_symbols']!='') {
        		$post['mark'][$p]=str_replace($this->sets['gs1_symbols'], '', $post['mark'][$p]);
        	}
			$mark=json_encode($post['mark'][$p]);
			$this->f3->set('GET.product_id', $p);
			$this->f3->set('GET.count', $count);
			$this->f3->set('GET.mark', $mark);
			$this->f3->set('GET.receipttype', $receipttype);
			$res=$this->add_line();
		}
	}

	function post_selectbarcode() {
		$post=$this->f3->get('POST');
		$product_id=$post['product'];
		$count=$post['count'];
		$this->f3->set('GET.product_id', $product_id);
		$this->f3->set('GET.count', $count);
		$this->f3->set('GET.mark', $post['mark']);
		$this->f3->set('GET.barcodes', json_encode($post['barcode']));
		$res=$this->add_line();
	}

	// добавление строки в чек
	function add_line() {
		$result=array(
			'success'=>false,
			'txt'=>$this->messages->message('not_found')['txt']
		);
		$product_id=$this->f3->get('GET.product_id');
		$count=$this->f3->get('GET.count');
		$mark=$this->f3->get('GET.mark');
		$receipttype=$this->f3->get('GET.receipttype');
		$parent_id=(int)$this->f3->get('GET.parent_id');
		if(is_array($mark)) {
			$mark=json_encode($mark);
		}

		$receipt_print=$this->f3->get('receipt_print');

		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		if($receipt_id>0) {
			$this->model->reset();
			$this->model->load(array('id=? AND time=0', $receipt_id), array('limit'=>1));
			if(!$this->model->dry()) {
				$open_receipt['success']=true;
				$open_receipt['receipt']=$this->model->cast();
				if(!$receipttype) $receipttype=$open_receipt['receipt']['type'];
			}
			else {
				$open_receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts']);
			}
		}
		else {
			$open_receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts']);
		}
		if(!$receipttype) $receipttype=1;

		//if(!$count) $count=1;
		if(isset($product_id)) {
			if($product_id!=0) {
				$res=$this->products->select_product(array('p.id=?', $product_id), array('limit'=>1));
				$price=$res[0]['price'];
				$return_receipt=$this->f3->get('COOKIE.return');
				if($res[0]['stop'] && !$return_receipt && $open_receipt['receipt']['type']!=$receipt_print) {
					$this->f3->set('page_data', $this->messages->message('product_stoped'));
					return;
				}
				if(!isset($count) || $count=='') {
					$count=$res[0]['quantity'];
				}

				if($this->sets['control_stock']>0 && $res[0]['stock']<$count && !$return_receipt) {
					$this->f3->set('page_data', $this->messages->message('no_required_amount'));
					return;
				}

				if($count!=1 && $res[0]['marking']>0 && $res[0]['units_fr']==0 && !$mark) {
					$this->f3->set('page_data', $this->messages->message('quantity_marked_goods_may_not_exceed_1'));
					return;
				}
				if($res[0]['ppr']==$this->f3->get('combo_ppr')) {
					$this->add_combo($res[0]);
					return;
				}

				if($this->products->count(array('date_delete=0 AND parent_id=?', $product_id))>0) {
					$this->f3->reroute('/products/search_barcodes?type='.$receipttype.'&parent_id='.$product_id.'&coeff='.$count);
				}

				$res[0]['count']=$count;
				if((int)$this->sets['check_mark']>0 && (($res[0]['marking']>0 && !$mark) || ($res[0]['marking']==1 && $mark=='[""]'))) {
					if($mark=='[""]') {
						$this->f3->set('page_data', $this->messages->message('incorrect_data'));
						return;
					}
					$this->f3->set('products', $res);
					$this->f3->set('page_data', $this->model->page_data('add_marking'));
					return;
				}
				if(((int)$this->sets['egais']>0 && (int)$this->sets['check_egais']>0) && (($res[0]['egais']==1 && !$mark) || ($res[0]['egais']==1 && $mark=='[""]' && (int)$this->sets['check_egais']==2))) {
					if($mark=='[""]') {
						$this->f3->set('page_data', $this->messages->message('incorrect_data'));
						return;
					}
					$this->f3->set('products', $res);
					$this->f3->set('page_data', $this->model->page_data('add_marking'));
					return;
				}
				if($open_receipt['receipt']['type']==$receipt_print) {
					$get_barcodes=$this->f3->get("GET.barcodes");
					if(is_array($res[0]['barcodes']) && count($res[0]['barcodes'])>1 && !$get_barcodes) {
						$this->f3->set('product', $res[0]);
						$this->f3->set('page_data', $this->model->page_data('select_barcode'));
						return;
					}
					elseif($get_barcodes) {
						$res[0]['barcodes']=$get_barcodes;
					}
					else {
						$res[0]['barcodes']=json_encode(array_column($res[0]['barcodes'], 'barcode'));
					}
				}
				if($mark=='[""]')$mark='';
				$mark_code=json_decode($mark)[0];
				if($this->sets['gs1_symbols']!='') {
        			$mark_code=str_replace($this->sets['gs1_symbols'], '', $mark_code);
        		}
        		$mark_code=str_replace('%2B', '+', $mark_code);
        		if(preg_match("/[А-Яа-я]/", $mark_code)) {
        			$this->f3->set('mark_code', $mark_code);
					$this->f3->set('txt', $this->messages->message('cyrilic_symbols_from_mark')['txt']);
					$this->f3->set('page_data', $this->model->page_data('marking_error'));
					return;
        		}
				if($receipttype==1) {
					if($mark!='' && $this->sets['check_mark']>0 && $res[0]['egais']==0 && (!$this->f3->get('GET.not_check_mark') || $this->sets['check_mark']==2)) {
						// Проверяем маркировку товара
						$this->changes->get_change();
						$mark_res=$this->model->check_mark(urldecode($mark_code), $count, $res[0]['units_fr'], $this->sets['check_chz']);
						if($mark_res['success']===false) {
							$this->f3->set('mark_code', $mark_code);
							$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('marking_error'));
							return;
						}
						$count=$mark_res['count'];
						$expiration_date=$mark_res['expiration_date'];
					}
					if($mark!='' && $this->sets['check_egais']>0 && $this->sets['egais']==1 && $res[0]['egais']==1 && (!$this->f3->get('GET.not_check_mark') || $this->sets['check_egais']==2)) {
						// Проверяем товар ЕГАИС
						$egais_res=$this->model->check_egais($mark_code);
						if($egais_res['success']===false) {
							$this->f3->set('mark_code', $mark_code);
							$this->f3->set('txt', $this->messages->message($egais_res['txt'])['txt']);
							$this->f3->set('page_data', $this->model->page_data('egais_error'));
							return;
						}
					}
					if($mark!='' && $this->sets['check_mrc']>0 && $res[0]['egais']==0 && (!$this->f3->get('GET.not_check_mrc') || $this->sets['check_mrc']==2)) {
						$price=$res[0]['price']+($res[0]['price']*($res[0]['vat']/100))*max(0, $res[0]['vat_type']);
						$mrc=$this->model->mark_for_chz(urldecode($mark_code))['mrc'];
						if($mrc<$price && $mrc>0) {
							$this->f3->set('mark_code', $mark_code);
							$this->f3->set('txt', $this->messages->message('mrc_error')['txt']);
							$this->f3->set('page_data', $this->model->page_data('mrc_error'));
							return;
						}
					}

					if($mark!='' && $this->sets['check_expiration_date']>0 && $res[0]['egais']==0 && (!$this->f3->get('GET.not_check_expiration_date') || $this->sets['check_expiration_date']==2)) {
						if(!$expiration_date) {
							$expiration_date=$this->model->mark_for_chz(urldecode($mark_code))['expiration_date'];
						}
						if($expiration_date<time() && $expiration_date>0) {
							$this->f3->set('mark_code', $mark_code);
							$this->f3->set('expiration_date', $expiration_date);
							$this->f3->set('txt', $this->messages->message('expiration_date_error')['txt']);
							$this->f3->set('page_data', $this->model->page_data('expiration_date_error'));
							return;
						}
					}

					if($mark!='' && $this->sets['check_double_mark']>0 && (!$this->f3->get('GET.not_check_double_mark') || $this->sets['check_double_mark']==2)) {
						// Проверяем повтор марки
						$mark_res=$this->receiptlines->check_double_mark(urldecode($mark_code));
						if($mark_res['success']===false) {
							$this->f3->set('mark_code', $mark_code);
							$this->f3->set('txt', $this->messages->message($mark_res['txt'])['txt']);
							$this->f3->set('page_data', $this->model->page_data('marking_double_error'));
							return;
						}
					}
				}
				$res[0]['mark']=$mark;
			}
			else {
				if(in_array('receipts/freesales', $this->f3->get('authorization_user.module')) || $parent_id>0) {
					if(!$count) $count=1;
					$free_title=$this->f3->get('GET.free_title');
					if(!$free_title) {
						$free_title=$this->model->fr->sets['free_title'];
					}
					if(!$free_title) {
						$free_title='Свободная продажа';
					}
					$free_vat=0;
					$free_vat_type=0;
					if(isset($this->model->fr->sets['free_vat'])) {
						$freevat=$this->model->fr->sets['free_vat'];
						if($freevat!=-1) {
							$free_vat=abs($freevat);
							if($freevat==0) {
								$free_vat_type=-1;
							}
							else {
								$free_vat_type=$freevat/$free_vat;
							}
						}
					}
					$res[0]=array(
						'title'=>$free_title,
						'id'=>$product_id,
						'price'=>$this->f3->get('GET.price'),
						'vat'=>$free_vat,
						'vat_type'=>$free_vat_type
					);
				}
				else {
					$this->f3->set('page_data', $this->messages->message('free_sales_not_access'));
					return;
				}
			}
			if(!empty($res)) { // Если есть что добавлять в чек
				if($open_receipt['success']) {
					if($open_receipt['receipt']['slip']!='') {
						$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
						return;
					}
					$receipt=$open_receipt['receipt'];
					$result=$this->receiptlines->add_line($receipt['id'], $res[0], $count, $parent_id);
					if($result['success']) {
						$this->cd->print_line($result['line'], $count);
						if($result['line']['related']!='' && (int) $this->sets['modifiers_window']==1)  {
							$result['close_all_window']=false;
							$result['next_step']='/receipts/modifiers?line_id='.$result['id'];
						}
					}
					// Применяем акции
					$this->loyalty($receipt, $res[0]);
				}
				$result['txt']=$this->messages->message($result['txt'])['txt'];
			}
		}
		if($this->sets['line_merge']) {
			$this->receiptlines->linesmerge($result['id']);
		}

		if($price==0 && $product_id!=0 && $result['id']>0) {
			$result['next_step']='/receipts/change_price?line_id='.$result['id'].'&price='.$mrc;
		}
		elseif($count==0 && $product_id!=0 && $result['id']>0) {
			$result['next_step']='/receipts/change_count?line_id='.$result['id'];
		}
		echo json_encode($result);
		exit();
	}

	// Меняем строку в чеке
	function change_line($exit=true) {
		if(!is_bool($exit)) $exit=true;
		$line_id=$this->f3->get('REQUEST.line_id');
		$count=$this->f3->get('REQUEST.count');
		$price=$this->f3->get('REQUEST.price');
		$discount=$this->f3->get('REQUEST.discount_line');
		$description=$this->f3->get('REQUEST.description');
		if(!isset($description) || is_null($description)) $description=false;
		$loyalty=$this->f3->get('REQUEST.loyalty');
		$writeoff_bonus=$this->f3->get('REQUEST.writeoff_bonus');
		if(!$loyalty)$loyalty=0;
		$return_receipt=$this->f3->get('COOKIE.return');
		$line=$this->receiptlines->select_lines(array('id=?', $line_id), array('limit'=>1));
		if($line[0]['loyalty']>0) {
			$loyalty=$line[0]['loyalty'];
		}

		$receipt=$this->model->find(array('id=?', $line[0]['receipt_id']), array('limit'=>1));
		$receipt_print=$this->f3->get('receipt_print');

		if($line[0]['stop'] && $count>$line[0]['count'] && !$return_receipt && $receipt[0]['type']!=$receipt_print) {
			$this->f3->set('page_data', $this->messages->message('product_stoped'));
			return;
		}

		if($this->sets['control_stock']>0 && $line[0]['product_id']>0 && $line[0]['stock']<$count && $count>$line[0]['count'] && !$return_receipt) {
			$this->f3->set('page_data', $this->messages->message('no_required_amount'));
			return;
		}

		if($line[0]['combo_id']>0) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('its_combo')['txt']
			);
		}
		else{
			if($receipt[0]['slip']!='') {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('dont_change_payed_receipt')['txt']
				);
				echo json_encode($res);
				exit();
			}
			if($receipt[0]['time']>0) {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('document_is_closed')['txt']
				);
			}
			elseif($line_id>=0 && ($count>=0 || $price>=0)) {
				$res=$this->receiptlines->change_line($line_id, $count, $price, $discount, $description, $loyalty, $writeoff_bonus);
				if($res['success']) {
					$this->cd->print_line($res['line'], $res['line']['count']);
					// Если было изменено кол-во, то надо пересчитать акции
					if($count && $receipt[0]['type']!=$receipt_print) {
						// Товар, к которому применяется скидка
						$product=$this->products->select_product(array('p.id=?', $res['line']['product_id']), array('limit'=>1));
						if($product[0]['stop']) {
							$this->f3->set('page_data', $this->messages->message('product_stoped'));
							return;
						}
						// Чтобы корректно применить акции, придется вернуть все как было до акций
						$this->cancel_loyalty($receipt[0], $product[0]);
						// А теперь применим акции
						$this->loyalty($receipt[0], $product[0]);
					}

				}
				$res['txt']=$this->messages->message($res['txt'])['txt'];

			}
			else {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('not_enough_data')['txt']
				);
			}
		}

		if($this->sets['line_merge']) {
			$this->receiptlines->linesmerge($line_id);
		}
		
		if($exit) {
			echo json_encode($res);
			exit();
		}
		else {
			return $res;
		}
	}

	// Редактируем цену в чеке
	function change_price() {
		$line_id=$this->f3->get('GET.line_id');
		$lines=$this->receiptlines->select_lines(array('id=?', $line_id), array('limit'=>1));
		if($lines[0]['combo_id']>0) {
			$this->f3->set('page_data', $this->messages->message('its_combo'));
			return;
		}
		$this->model->load(array('id=?', $lines[0]['receipt_id']), array('limit'=>1));
		if($this->model->dry()) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			return;
		}
		$receipt=$this->model->cast();
		if($receipt['slip']!='') {
			$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
			return;
		}
		if($lines[0]) {
			if($receipt['partner_id']>0) {
				$p=new \Models\Partners($this->db, $this->f3);
				$partner=$p->select_partner(array('partner_id=?', $receipt['partner_id']), array('limit'=>1));
				$receipt['partner']=$partner[0];
			}
			$product=$this->products->select_product(array('p.id=?', $lines[0]['product_id']), array('limit'=>1));
			$lines[0]['product_price']=$product[0]['price'];
			$lines[0]['buy_price']=$product[0]['buy_price'];
			$lines[0]['max_discount']=$product[0]['max_discount'];
			$this->f3->set('line', $lines[0]);
			$this->f3->set('receipt', $receipt);
			$this->f3->set('page_data', $this->model->page_data('change_price'));
		}
		else {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
		}
	}

	// Сохраняем новую цену продажи
	function post_change_price() {
		$price=$this->f3->get('POST.price'); // Установленная цена
		$price_db=$this->f3->get('POST.price_db'); // Цена из справочника
		$writeoff_bonus=$this->f3->get('POST.writeoff_bonus');
		$writeoff_bonus0=$this->f3->get('POST.writeoff_bonus0');
		$loyalty=0;
		if($price!=$price_db) {
			if($writeoff_bonus>0) {
				$loyalty=1;
				$description='Списание баллов кассиром '.$this->f3->get('authorization_user.short_name');
			}
			else {
				$loyalty=2;
				$description='Изменение цены кассиром '.$this->f3->get('authorization_user.short_name');
			}
			$this->f3->set('POST.description', $description);
		}
		$this->f3->set('POST.loyalty', $loyalty);
		$res=$this->change_line(false);

		if($res['success'] && ($writeoff_bonus>0 || $writeoff_bonus0>0)) {
			$p=new \Models\Partners($this->db, $this->f3);
			$partner=$p->select_partner(array('partner_id=?', $this->f3->get('POST.partner_id')), array('limit'=>1));
			$partner[0]['bonus']-=($writeoff_bonus-$writeoff_bonus0);
			$p->save_partner($partner[0]);
		}

		echo json_encode($res);
		exit();
	}

	function change_count() {
		$line_id=$this->f3->get('GET.line_id');
		$lines=$this->receiptlines->select_lines(array('id=?', $line_id), array('limit'=>1));
		if($lines[0]['combo_id']>0) {
			$this->f3->set('page_data', $this->messages->message('its_combo'));
			return;
		}
		$this->model->load(array('id=?', $lines[0]['receipt_id']), array('limit'=>1));
		if($this->model->dry()) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			return;
		}
		$receipt=$this->model->cast();
		if($receipt['slip']!='') {
			$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
			return;
		}
		if($lines[0]) {
			$product=$this->products->select_product(array('p.id=?', $lines[0]['product_id']), array('limit'=>1));
			$this->f3->set('line', $lines[0]);
			$this->f3->set('receipt', $receipt);
			$this->f3->set('page_data', $this->model->page_data('change_count'));
		}
		else {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
		}
	}

	function post_change_count() {
		$count=$this->f3->get('POST.count');
		$res=$this->change_line(false);

		echo json_encode($res);
		exit();
	}

	// Удаляем строки
	function delete_line() {
		$this->cd->clear_cd();
		$line_id=$this->f3->get('GET.line_id');
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		//$receipt=$this->model->select_receipts(array('r.id=?', $receipt_id), array('limit'=>1));
		$this->model->reset();
		$this->model->load(array('id=?', $receipt_id), array('limit'=>1));
		$receipt=$this->model->cast();
		if($receipt['slip']!='') {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('dont_change_payed_receipt')['txt']
			);
			echo json_encode($res);
			exit();
		}
		if($receipt['time']>0) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('document_is_closed')['txt']
			);
		}
		elseif($line_id>=0 || $line_id=='all') {
			$res=$this->receiptlines->delete_line($line_id, $receipt);
			if($res['success'] && $line_id!='all') {
				// Применяем акции
				// Товар, к которому применяется скидка
				$product=$this->products->select_product(array('p.id=?', $res['line']['product_id']), array('limit'=>1));
				// Чтобы корректно применить акции, придется вернуть все как было до акций
				$this->cancel_loyalty($receipt, $product[0]);
				// А теперь применим акции
				$this->loyalty($receipt, $product[0]);
			}
			$res['txt']=$this->messages->message($res['txt'])['txt'];
			if($line_id=='all') {
				$res['ticket_reset']=true;
				//$this->model->remove_partner($this->f3->get('COOKIE.receipt_id'));
				//$this->model->set_discount(0);
				$this->model->receipt_clear($receipt_id);
			}
			if($this->f3->get('GET.reload')) {
				$res['function']='location.replace("/")';
			}
		}
		else {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('not_enough_data')['txt']
			);
		}

		if($this->f3->get('AJAX')) {
			echo json_encode($res);
			exit();
		}
	}

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

	// выбор оплаты
	function pay() {
		$epays=new \Models\Epays($this->db, $this->f3);
		$this->f3->set('epays', $epays->select_epays('active=1'));
		$sno_select=$this->f3->get('GET.sno');
		$sum=$this->f3->get('GET.sum');
		$pay=$this->f3->get('GET.pay');
		if($sum && $pay) {
			$this->cd->total_price($sum, $pay);
			exit();
		}
		$receipt=$this->model->get_open_receipt($this->receipt_sets, false, (int) $this->sets['view_all_receipts']);
		if(!$receipt['success']) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			return;
		}
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']));

		if(empty($lines)) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			return;
		}
		if($this->f3->get('authorization_user.kiosk')==1 && file_exists($this->f3->get('ROOT').'/ui/kiosk/'.$this->sets['kiosk_type'].'/config.ini')) {
			$config=parse_ini_file($this->f3->get('ROOT').'/ui/kiosk/'.$this->sets['kiosk_type'].'/config.ini');

			$products=array();
			$mods=array();
			foreach($lines as $l) {
				if($l['parent_id']>0) {
					$mods[$l['parent_id']][]=$l;
				}
			}
			foreach($lines as $l) {
				if(!isset($mods[$l['id']]) && $l['parent_id']==0 && $l['combo_id']==0) {
					$l['count']+=$products[$l['product_id']]['count'];
					$products[$l['product_id']]=$l;
				}
				else {
					$l['count']=(float)$l['count'];
					$products[-$l['id']]=$l;
				}
			}
			$this->f3->set('mods', $mods);
			$this->f3->set('products', $products);
		}
		$this->f3->set('lines', $lines);

		if(!$sno_select && $receipt['receipt']['sno']) {
			$sno_select=$receipt['receipt']['sno'];
		}

		$control_sno=$this->receiptlines->control_sno($lines, $this->model->fr->sets['sno']);
		if(!$control_sno['status'] && !$sno_select) {
			$this->f3->set('sno_lines', $control_sno['sno']);
			$this->f3->set('page_data', $this->model->page_data('snoerror'));
			return;
		}

		$discount=$receipt['receipt']['discount'];
		$sum=$this->receiptlines->get_sum($lines, $discount, $this->sets['round_kop'], $receipt['receipt']['bonus_pay'], $receipt['receipt']['partner']['ignore_max_discount'])['sum'];
		//$sum-=$receipt['receipt']['bonus_pay'];
		$this->f3->set('sum', $sum);
		$p=new \Models\Paymentmethods($this->db, $this->f3);
		$paymentmethods=$p->select_method();
		$type=$this->f3->get('GET.type');
		if(!in_array($type, $this->receipts_types)) $type=$this->receipts_types['sales'];
		if($type==$this->receipts_types['sales']) {
			$this->cd->total_price($sum, $sum);
		}
		if($this->sets['executor']) {
			$this->f3->set('users', $this->users->select_users(array('date_delete=0 AND type<>1'), array('order'=>'name'))); // Список пользователей
		}
		$this->f3->set('fr', $this->model->fr->sets['active']);
		if($control_sno['status'] && !$sno_select) {
			$sno_select=$control_sno['sno'][0];
		}
		$this->model->fr->sets['sno_types']=array_unique(array_merge($this->model->fr->sets['sno_types'], $control_sno['sno']));
		if(!$sno_select) {
			$sno_select=$this->model->fr->sets['sno'];
		}
		$this->f3->set('sno_select', $sno_select);
		$this->f3->set('fr_settings', $this->model->fr->sets);
		$this->f3->set('type', $type);
		$this->f3->set('paymentmethods', $paymentmethods);
		if($receipt['receipt']['payment']) {
			$receipt['receipt']['pays']=json_decode($receipt['receipt']['payment'], true);
		}
		else {
			$receipt['receipt']['pays']=array();
		}
		$this->f3->set('receipt', $receipt['receipt']);
		$this->f3->set('page_data', $this->model->page_data('paymentmethods'));
	}

	// Пробиваем чек
	function ready() {
		$paymentmethod=$this->f3->get('REQUEST.paymentmethod');
		$client_sum=$this->f3->get('REQUEST.client_sum');
		$client=$this->f3->get('REQUEST.client');
		$executor=$this->f3->get('REQUEST.executor');
		$sales_receipts=$this->f3->get('REQUEST.sales_receipts');
		$epay=$this->f3->get('REQUEST.epay');
		$sno=$this->f3->get('REQUEST.sno');
		$fpd=$this->f3->get('REQUEST.fpd');
		if(!$sno) $sno=$this->model->fr->sets['sno'];
		$receipt=$this->model->get_open_receipt($this->receipt_sets, false, (int) $this->sets['view_all_receipts']);
		if(!$receipt['success']) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('receipts_is_ready')['txt']
			);
		}
		else {
			$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']));
			if($lines && $paymentmethod && $client_sum) {
				$discount=$this->f3->get('POST.discount');
				if(!isset($discount)) $discount=$receipt['receipt']['discount'];
				$type=$this->f3->get('REQUEST.type');
				if(!$type) $type=$this->receipts_types['sales']; // Продажа
				$partner_id=$this->f3->get('POST.partner_id');
				$lines_sum=$this->receiptlines->get_sum($lines, $discount, $this->sets['round_kop'], $receipt['receipt']['bonus_pay'], $receipt['receipt']['partner']['ignore_max_discount']);
				$sum=$lines_sum['sum'];
				//$sum-=$receipt['receipt']['bonus_pay'];
				// Узнаем смену
				$change=$this->changes->get_change();

				if(!empty($change)) {
					// Создаем чек
					$partner_bonus=0;
					$partner_bonus_sum=0;
					$partners_model=new \Models\Partners($this->db, $this->f3);
					if($receipt['receipt']['partner']['loyalty_type']==2) {
						if($receipt['receipt']['bonus_pay']==0 || $receipt['receipt']['partner']['bonus_add_sets']==1) {
							$partner_bonus=$partners_model->partners_bonus($receipt['receipt']['partner'], $lines, $sum);
							if($type!=1) { // Возврат
								$partner_bonus=-$partner_bonus;
							}
						}
						$partner_bonus_sum=$receipt['receipt']['partner']['bonus']+$partner_bonus;
					}
					if($receipt['receipt']['slip']) {
						$receipt['receipt']['slip']=str_replace("\n", '', $receipt['receipt']['slip']);
						$receipt['receipt']['slip']=str_replace("\r", '', $receipt['receipt']['slip']);
						$this->model->fr->send_ajax('p;'.preg_replace('/\<br(\s*)?\/?\>/i', "#kkm_br#", $receipt['receipt']['slip']).";\n");
						$pays=json_decode($receipt['receipt']['payment'], true);
						$paymentmethod=array();
						$client_sum=array();
						foreach($pays as $p) {
							$paymentmethod[]=$p['method'];
							$client_sum[$p['method']]=$p['sum'];
						}
						$epay=$receipt['receipt']['epay'];
					}
					$print=$this->f3->get('REQUEST.fr_print');
					if(!$print && !$client) {
						$client=$this->f3->get('agorta_email');
					}
					$writeoff_bonus=array_sum(array_column($lines_sum['lines'], 'writeoff_bonus'));
					$res=$this->model->add_ticket($receipt['receipt']['id'], $change, $type, $paymentmethod, $client_sum, $sum, $lines_sum['lines'], $client, $discount, $partner_id, $sales_receipts, $print, $partner_bonus, $partner_bonus_sum, (float)($receipt['receipt']['bonus_pay']+$writeoff_bonus), $executor, $receipt['receipt']['correct_type'], $receipt['receipt']['osn_number'], $receipt['receipt']['osn_date'], $receipt['receipt']['slip'], $partner_bonus, $epay, $receipt['receipt']['partner']['ignore_max_discount'], $sno, $fpd);
					// Записываем скидку в товары
					if($res['success']) {
						$receipt['receipt']['fd']=$res['receipt']['fd'];
						$receipt['receipt']['fp']=$res['receipt']['fp'];
						$receipt['receipt']['time']=$res['receipt']['time'];
						$receipt['receipt']['sum']=$res['receipt']['sum'];
						$this->f3->set('fr_error_ignore', 1);
						if($res['show_qr']) {
							echo json_encode($res);
							exit();
						}
						if((int)$this->sets['cafe_mode']==0) {
							$create_order=microtime(true);
							$complite_order=microtime(true);
							$issued_order=microtime(true);
						}
						elseif((int)$this->sets['send_orders']==0) {
							$create_order=microtime(true);
							if((int)$this->sets['orders_device']==1) {
								$complite_order=microtime(true);
								$issued_order=microtime(true);
							}
							else {
								$complite_order=0;
								$issued_order=0;
							}
						}
						else {
							$create_order=microtime(true);
							$complite_order=0;
							$issued_order=0;
							/*if((int)$this->sets['orders_device']==1) {
								$complite_order=time();
								$issued_order=time();
							}
							else {
								$complite_order=0;
								$issued_order=0;
							}*/
						}
						if((float)$receipt['receipt']['bonus_pay']>0) {
							$this->receiptlines->lines_bonus_pay($lines, (float)$receipt['receipt']['bonus_pay'], $receipt['receipt']['partner']['ignore_max_discount']);
						}
						$res=$this->receiptlines->save_lines($receipt['receipt'], $discount, $create_order, $complite_order, $issued_order);
						if($type==1) {
							$this->cd->seller_txt();
						}
						if($this->sets['cafe_mode']==1 && $this->f3->get('authorization_user.kiosk')!=1) {
							$this->f3->clear('COOKIE.table_id');
							$this->f3->clear('COOKIE.receipt_id');
							unset($res['reload'], $res['reload_menu']);
							if($type==$this->receipts_types['sales']) {
								$url='/';
							}
							else {
								$url='/receipts/return';
							}
							$res['function']='$("#screen").load("'.$url.'?room_id='.$receipt['receipt']['table']['room'].' #screen_window", function(){receiptlines_div_resize(); synchronization();});';
						}
						else {
							$t=$this->model->get_empty($this->api_data['rm_id'], $this->api_data['store_id']);
							if($t>0) {
								$this->f3->set('COOKIE.receipt_id', $t);
							}
							else {
								$this->model->open_new($this->receipt_sets);
							}
						}
						if($sales_receipts==1) {
							$this->model->print($receipt['receipt']['id']);
						}
						if($partner_bonus!=0 || $receipt['receipt']['bonus_pay']>0) {
							$receipt['receipt']['partner']['bonus']=$partner_bonus_sum;
							if($receipt['receipt']['bonus_pay']>0) {
								$receipt['receipt']['partner']['bonus']-=$receipt['receipt']['bonus_pay'];
							}
							$partners_model->save_partner($receipt['receipt']['partner']);
						}
					}
					$res['txt']=$this->messages->message($res['txt'])['txt'];
				}
				else {
					$res=array(
						'success'=>false,
						'txt'=>$this->messages->message('change_not_open')['txt']
					);
				}
			}
			else {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('receipts_is_ready')['txt']
				);
			}
		}
		$res['ticket_reset']=true;
		if($receipt['receipt']['type']==$this->receipts_types['correct_sales'] || $receipt['receipt']['type']==$this->receipts_types['correct_return']) {
			$res['reroute']='/receipts/search';
		}
		$res=$this->model->control_fn($res);
		if($this->f3->get('REQUEST.show_message')==1) {
			unset($res['close_all_window']);
			$res['show_message']='/receipts/success_pay?receipt='.json_encode($receipt['receipt']);
		}

		if((int)$this->sets['cafe_mode']==1 && $type==$this->receipts_types['sales']) {
			if((int)$this->sets['send_orders']==0) {
				unset($this->model);
				$kitchen=new \Models\Receipts($this->db, $this->f3, 'kitchen');
				$kit_res=$kitchen->print($receipt['receipt']['id'], 'all', (int)$this->sets['orders_device']);
				if(is_array($kit_res) && $kit_res['success']===false) {
					$res['success']=false;
					$res['function'].=" close_window('.paymentmethods')";
					$res['txt']=$this->messages->message('kitchen_printer_error')['txt'].' '.$kit_res['error'];
					unset($res['close_all_window']);
				}
				unset($kitchen);
				$bar=new \Models\Receipts($this->db, $this->f3, 'bar');
				$bar_res=$bar->print($receipt['receipt']['id'], 'all', (int)$this->sets['orders_device']);
				if(is_array($bar_res) && $bar_res['success']===false) {
					$res['success']=false;
					$res['function'].=" close_window('.paymentmethods')";
					$res['txt']=$this->messages->message('bar_printer_error')['txt'].' '.$bar_res['error'];
					unset($res['close_all_window']);
				}
				unset($bar);
			}
			// Выдадим то что не надо печатать на кухне и в баре
			$this->receiptlines->issued_receipt($receipt['receipt']['id'], $this->sets['orders_device']);
		}
		
		if(file_exists($this->f3->get('UI').'/receiptlines_html.htm')) {
			unlink($this->f3->get('UI').'/receiptlines_html.htm');
		}
		$this->f3->write($this->f3->get('UI').'/receiptlines_html.htm', '');
		echo json_encode($res);
		exit();
	}

	// Создаем чек продажи
	function post_sales() {
		$hold=$this->f3->get('POST.hold');
		if($hold==1) {
			$this->f3->set('hold', 1);
		}
		$this->ready();
	}

	// Создаем возвратный чек
	function post_return() {
		// Создаем чек совсеми данными
		$post=$this->f3->get('REQUEST');
		if($post['hold']==1) {
			$this->f3->set('hold', 1);
		}
		// Узнаем смену
		$change=$this->changes->get_change();
		// Узнаем сумму строк

		foreach ($post['receiptlines'] as $line_n=>$line) {
			if(isset($line['mark']) && $line['mark']!='') {
				if($this->sets['gs1_symbols']!='') {
        			$line['mark']=str_replace($this->sets['gs1_symbols'], '', $line['mark']);
        		}
				$line['mark']=json_encode(array($line['mark']));
				$post['receiptlines'][$line_n]['mark']=$line['mark'];
			}
		}

		$lines_sum=$this->receiptlines->get_sum($post['receiptlines'], $post['discount'], 0);
		$post['sum']=$lines_sum['sum'];
		//$post['receiptlines']=$lines_sum['lines'];

		$res=$this->model->ticket_return($this->api_data['rm_id'], $this->api_data['store_id'], $change, $post, $lines_sum['lines']);
		if($res['success']) {
			// Добавляем строки
			foreach ($post['receiptlines'] as $line_n=>$line) {
				$time=str_replace(',', '.', microtime(true));
				$result=$this->receiptlines->add_line($res['id'], $line, $line['count'], 0, $time, $time, $time);
				if(!$result['success']) {
					$this->model->delete_receipt($res['id']);
					$res=$result;
					break;
				}
			}
			$res=$this->model->ticket_ready($res['receipt'], $post, $lines_sum['lines']);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		$res=$this->model->control_fn($res);
		echo json_encode($res);
		exit();
	}

	// Внесение денег в кассу
	function cashin() {
		$this->f3->set('auto_cashout', $this->model->fr->sets['auto_incassation']);
		$this->f3->set('page_data', $this->model->page_data('cashin'));
		$this->cd->close_txt();
	}

	// Изъятие денег из кассы
	function cashout() {
		$this->f3->set('auto_cashout', $this->model->fr->sets['auto_incassation']);
		$this->f3->set('page_data', $this->model->page_data('cashout'));
		$this->cd->close_txt();
	}

	// Пытаемся внести деньги в кассу
	function post_cashin() {
		$hold=$this->f3->get('POST.hold');
		if($hold==1) {
			$this->f3->set('hold', 1);
		}
		$sum=$this->f3->get('POST.sum');
		$description=$this->f3->get('POST.description');
		$create_receipt=$this->f3->get('POST.create_receipt');
		if($sum) {
			if($sum>0)$type=$this->receipts_types['cashin'];
			else $type=$this->receipts_types['cashout'];
			$change=$this->changes->get_change();
			if($change) {
				$p=new \Models\Paymentmethods($this->db, $this->f3);
				$pay=$p->select_method('cash=1');
				$res=$this->model->cashin($this->api_data, $change, $pay[0]['id'],  $sum, $type, $create_receipt, $description);
				$res['txt']=$this->messages->message($res['txt'])['txt'];
			}
			else {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('change_not_open')['txt']
				);
			}
		}
		else {
			$res=array(
				'success'=>false,
				'txt'=>$res=$this->messages->message('not_enough_data')['txt']
			);
		}

		echo json_encode($res);
		exit();
	}

	// Изымаем деньги из кассы
	function post_cashout() {
		$sum=$this->f3->get('POST.sum');
		if(!is_numeric($sum)) $sum=0;
		$this->f3->set('POST.sum', -$sum);
		$this->post_cashin();
	}

	// Принудительное пробитие чека, при ошибке ФР
	function post_hold() {
		$this->f3->set('hold', 1);
		$this->f3->set('no_egais', true);
		$type=$this->f3->get('GET.type');
		$method='post_'.$type;
		$this->$method();
	}

	// Страница смены и отчеты
	function reports() {
		$ch=$this->f3->get('GET.change');
		if(!$ch) {
			$change=$this->changes->get_change(false);
		}
		else {
			$ch=$this->changes->load(array('id=?', $ch));
			if(!$ch->dry()) {
				$change=$ch->cast();
			}
			else {
				$this->f3->set('error', $this->messages->message('not_found')['txt']);
			}
		}
		if($change) {
			$report=$this->model->change_statistic($change['id']);
			$p=new \Models\Paymentmethods($this->db, $this->f3);
			$paymentmethods=$p->select_method();
			foreach ($paymentmethods as $p) {
				$pays[$p['id']]=array('title'=>$p['title'], 'cash'=>$p['cash']);
			}
			$this->f3->set('paymentmethods', $pays);
			$receipts_epays=$this->model->change_epays($change['id']);
			$ep=new \Models\Epays($this->db, $this->f3);
			if($receipts_epays) {
				$epays_id=' OR id IN ('.implode(',', array_column($receipts_epays, 'epay')).') ';
			}
			else {
				$epays_id='';
			}
			$epays=$ep->select_epays(array('active=1'.$epays_id));
			$this->f3->set('epays', $epays);
		}
		$report=$this->model->change_statistic($change['id']);
		$this->f3->set('report', $report);
		$this->f3->set('change', $change);
		$this->f3->set('page_data', $this->model->page_data('reports'));
		$this->cd->close_txt();
	}

	// Применение программ лояльности ко всему чеку
	function loyalty_receipt($cancel=false, $receipt_id=null) {
		if(!is_bool($cancel)) $cancel=false;
		if($receipt_id>0) {
			$this->model->reset();
			$this->model->load(array('id=?', $receipt_id), array('limit'=>1));
			if(!$this->model->dry()) {
				$receipt=$this->model->cast();
			}
		}
		else {
			$receipt=$this->model->get_open_receipt($this->receipt_sets)['receipt'];
		}
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['id']));
		if($lines) {
			$in='';
			$val=array();
			foreach ($lines as $l) {
				if($in!='')$in.=', ';
				$in.='?';
				$val[]=$l['product_id'];
			}
			$products=$this->products->select_product(array('p.id IN ('.$in.')', $val));
			if($products) {
				foreach ($products as $p) {
					// Если сначала нужно сбросить акции
					if($cancel===true) {
						$this->cancel_loyalty($receipt, $p);
					}
					$this->loyalty($receipt, $p);
				}
			}
		}
	}

	// Убрать клиента из чека
	function remove_partner($receipt_id=null, $exit=true) {
		if(!$receipt_id || !is_numeric($receipt_id)) $receipt_id=$this->f3->get('COOKIE.receipt_id');
		if(!is_bool($exit)) $exit=true;
		$res=$this->model->remove_partner($receipt_id);
		$this->loyalty_receipt(true, $receipt_id);
		if(!$exit) {
			return $res;
		}
		echo json_encode($res);
		exit();
	}

	// Добавление клиента в чек
	function add_partner() {
		$get=$this->f3->get('GET');
		$partner_id=$get['partner_id'];
		if(!$partner_id)$partner_id=-1;
		$p=new \Models\Partners($this->db, $this->f3);
		$partner=$p->select_partner(array('partner_id=?', $partner_id), array('limit'=>1));
		if(empty($partner) && !$this->f3->get('new_partner')) {
			$this->f3->set('page_data', $p->page_data('not_found'));
			return;
		}
		if(empty($partner)) {
			$card='';
			$phone='';
			if($get['type']) {
				if($get['type']=='card') {
					$card=$get['client_value'];
				}
				else {
					$phone=$get['client_value'];
				}
			}
			$partner[0]=array(
				'partner_id'=>-1,
				'card'=>$card,
				'discount'=>0,
				'email'=>'',
				'phone'=>$phone
			);
		}
		$res=$this->model->add_partner($this->f3->get('COOKIE.receipt_id'), $partner[0]);
		$this->loyalty_receipt(true);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Отчет по секциям
	function rep_sections() {
		$res=$this->model->rep_sections();
		$this->f3->set('page_data', $this->messages->message($res['txt']));
	}

	// Печать копии последнего чека
	function print_last() {
		$res=$this->model->print_last();
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Открытие нового пустого чека
	function new() {
		$res=$this->model->open_new($this->receipt_sets);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Переключение на другой чек
	function switch() {
		$id=$this->f3->get('GET.id');
		$res=$this->model->switch_receipt($id);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Страница со списком всех открытых чеков на кассе
	function all_open() {
		$res=$this->model->all_open();
		$receipts=$res['receipts'];
		if($this->sets['multikassa']==1) {
			$res=$this->multi_curl($this->sets['other_cashboxes_ip'], '/multikassa/all_open', $this->sets['ip_port']);
			$receipts=$this->model->other_all_open($res, $receipts);
		}
		$this->f3->set('receipts', $receipts);
		$this->f3->set('page_data', $this->model->page_data('all_open'));
	}

	// Перехват чека
	function intercept() {
		$id=$this->f3->get('GET.id');
		$ip=explode('-', $id);
		if(count($ip)==2) {
			$res=$this->model->other_intercept($this->api_data['rm_id'], $this->api_data['store_id'], $ip[1], $ip[0]);
			$id=$res['receipt']['id'];
			if($res['success']) {
				$this->model->other_delete_receipt($ip[1], $ip[0]);
			}
		}
		else {
			$res=$this->model->intercept($this->api_data['rm_id'], $this->api_data['store_id'], $id);
		}
		if($res['success']) {
			$this->f3->set('COOKIE.receipt_id', $id);
			$this->f3->set('COOKIE.table_id', $res['receipt']['table_id']);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Окно перемещения чека на другой стол
	function move() {
		if($this->f3->get('GET.table_id')) {
			$this->move_receipt();
			return;
		}
		$receipt=$this->model->get_open_receipt($this->receipt_sets, true);
		if(!$receipt['success']) {
			$this->f3->set('page_data', $this->messages->message($res['txt']));
			return;
		}
		$r=new \Models\Rooms($this->db, $this->f3);
		$rooms=$r->select_rooms();
		$room=$rooms[0];
		$room_id=$this->f3->get('GET.room_id');
		if(!$room_id) {
			$room_id=$receipt['receipt']['table']['room'];
		}

		foreach ($rooms as $v) {
			if($v['id']==$room_id) {
				$room=$v;
				break;
			}
		}

		if(!empty($room)) {
			// Если зал выбран, то находим столы
			$t=new \Models\Tables($this->db, $this->f3);
			$tables=$t->tables_from_room($room_id, true);
		}
		$this->f3->set('move', true);
		$this->f3->set('rooms', $rooms);
		$this->f3->set('room', $room);
		$this->f3->set('tables', $tables);
		$this->f3->set('receipt', $receipt['receipt']);
		$this->f3->set('page_data', $this->model->page_data('move'));
	}

	// Перемещение чека на другой стол
	function move_receipt() {
		$table_id=$this->f3->get('GET.table_id');
		$res=$this->model->move_receipt($this->f3->get('COOKIE.receipt_id'), $table_id);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Форма для поиска заказов из интернет-магазина
	function online_order() {
		$this->f3->set('GET.dates', date('d.m.Y').' - '.date('d.m.Y'));
		return $this->search_online_order();
	}

	// Ищем интернет-заказы
	function search_online_order() {
		$data=$this->f3->get('GET');
		$page=$data['page'];
		if(!$page)$page=1;
		$lines_of_page=$this->f3->get('lines_of_page');
		$data['offset']=($page-1)*$lines_of_page;
		$data['limit']=$lines_of_page;
		$this->f3->set('COOKIE.online_order_type_id', $data['type_id']);
		$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->online_order($data);
		if($res['success']) {
			// Показываем результат поиска
			$this->f3->set('pagination', $this->pagination($res['all'], $page));
			$this->f3->set('receipts', $res['receipts']);
		}
		else { // Выводим ошибку
			$error='';
			foreach ($res['error'] as $er) {
				$error.=$this->messages->message($er)['txt'].'<br>';
			}
			$this->f3->set('error', $error);
		}
		$this->f3->set('page_data', $this->model->page_data('online_order'));
	}

	// Просмотр интернет-заказа
	function post_show_online_order() {
		$order=json_decode(urldecode($this->f3->get('POST.order')), true);
		$this->f3->set('order', $order);
		$p=new \Models\Paymentmethods($this->db, $this->f3);
		$paymentmethods=$p->select_method(null);
		foreach ($paymentmethods as $n => $p) {
			$pays[$p['id']]=$p['title'];
		}
		$this->f3->set('paymentmethods', $pays);
		$this->f3->set('page_data', $this->model->page_data('show_online_order'));
	}

	// Добавляем заказ к чеку
	function post_search_online_order() {
		$order=json_decode(urldecode($this->f3->get('POST.order')), true);
		// Узнаем открытый чек
		$receipt=$this->model->get_open_receipt($this->receipt_sets, false);
		// Если чек пустой, то добавим заказ в него
		$this->receiptlines->reset();
		$lines=$this->receiptlines->count(array('receipt_id=?', $receipt['receipt']['id']));
		if($lines>0) {
			// Если чек не пустой, создадим новый чек
			$this->model->open_new($this->receipt_sets);
		}
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$res=$this->model->push_order($receipt_id, $order);

		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function add_from_agorta() {
		$data=$this->f3->get('GET');
		if(!$data['id']) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			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->online_order($data);
		if(!$res['success']) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		if(count($res['receipts'])==0) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		elseif(count($res['receipts'])>1) {
			$n=array_search($data['id'], array_column($res['receipts'], 'id'));
			if($n===false) {
				$this->f3->set('page_data', $this->messages->message('not_found'));
				return;
			}
			$order=$res['receipts'][$n];
		}
		else {
			$order=$res['receipts'][0];
		}

		$receipt=$this->model->get_open_receipt($this->receipt_sets, true);
		$this->receiptlines->reset();
		$lines=$this->receiptlines->count(array('receipt_id=?', $receipt['receipt']['id']));
		if($lines>0) {
			// Если чек не пустой, создадим новый чек
			if($this->sets['cafe_mode']==1) {
				$tables=new \Models\Tables($this->db, $this->f3);
				$table=$tables->select_tables();
				if($table) {
					$this->f3->set('COOKIE.table_id', $table[rand(0, count($table)-1)]['id']);
				}
			}
			$this->model->open_new($this->receipt_sets);
		}
		else {
			$this->f3->set('COOKIE.receipt_id', $receipt['receipt']['id']);
		}

		$order['remote']=$order['id'];
		$res=$this->model->push_order($this->f3->get('COOKIE.receipt_id'), $order);
		$this->f3->reroute('/receipts/sales');
	}

	function print_turn() {
		$id=$this->f3->get('GET.id');
		if(!is_numeric($id)) {
			$id=$this->f3->get('COOKIE.receipt_id');
		}
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $id), array('order'=>'turn'));
		$turns=array_unique(array_column($lines, 'turn'));
		if(count($turns)<=1) {
			$turn=$this->f3->set('GET.print', (int)$this->sets['orders_device']);
			$turn=$this->f3->set('GET.turn', 'all');
			return $this->print();
		}
		$this->f3->set('turns', $turns);
		$this->f3->set('page_data', $this->model->page_data('print_turns'));
	}

	// Печать пречека или товарного чека
	function print() {
		$id=$this->f3->get('GET.id');
		if(!is_numeric($id)) {
			$id=$this->f3->get('COOKIE.receipt_id');
		}
		$turn=$this->f3->get('GET.turn');
		$print=$this->f3->get('GET.print');
		if(!is_numeric($print)) {
			$print=1;
		}
		if(!is_numeric($turn)) {
			$turn='all';
		}
		$res=$this->model->print($id, $turn, $print);
		if($res['success']) {
			$this->f3->set('device', $this->device);
			$this->f3->set('page_data', $this->model->page_data('print'));
		}
		else {
			$this->f3->set('page_data', $this->messages->message($res['txt']));
		}
	}

	// Фискализация удаленных документов
	function fiscalization($n) {
		$this->f3->set('POST.nobt', 1);
		if($n>=10) {
			return array(
				'success'=>false,
				'txt'=>$this->messages->message('error')['txt']
			);
		}
		$receipts=$this->model->find(array('remote>0 AND time<0'), array('order'=>'remote'));
		if(!$receipts) {
			$res=array(
				'success'=>true,
				'txt'=>'not_remote_fiscalization'
			);
		}
		else {
			// Узнаем смену и если что откроем ее
			$change=$this->changes->get_change();
			// Узнаем состояние смены на ФР
			$fr=new \Models\Fr($this->db, $this->f3);
			// closed - закрыта
        	// opened - открыта
        	// expired - истекла
			$change_status=$fr->change_status();
			if($change_status=='closed') { // Смена закрыта, хотя в программе мы ее открыли
				// Надо открыть смену на ФР
				$fr->open_session(0);
			}
			elseif($change_status=='expired') { // Смена истекла
				// Надо закрыть смену и начать заново
				$ch=new \Models\Changes($this->db, $this->f3);
				$z=$ch->z($change);
				if(!$z['success']) {
					return $z;
				}
				return $this->fiscalization($n+1);
			}
			
			foreach ($receipts as $receipt) {
				// Узнаем товары
				$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['id']));
				$sum=$receipt['sum'];
				// Оплата
				$pay=$this->f3->get('e_paymethod');
				$paymentmethods=array(
					$pay
				);
				$client_sum=array(
					$pay=>$sum
				);
				// Проводим документ
				$res=$this->model->add_ticket($receipt['id'], $change, $this->receipts_types['sales'], $paymentmethods, $client_sum, $sum, $lines, $receipt['client'], 0, $receipt['partner_id'], 0, 0);
				if($res['success']) {

					if((int)$this->sets['cafe_mode']==0) {
						$create_order=microtime(true);
						$complite_order=microtime(true);
						$issued_order=microtime(true);
					}
					elseif((int)$this->sets['send_orders']==0) {
						$create_order=microtime(true);
						if((int)$this->sets['orders_device']==1) {
							$complite_order=microtime(true);
							$issued_order=microtime(true);
						}
						else {
							$complite_order=0;
							$issued_order=0;
						}
					}
					else {
						$create_order=microtime(true);
						$complite_order=0;
						$issued_order=0;
					}

					$res=$this->receiptlines->save_lines($receipt, 0, $create_order, $complite_order, $issued_order);
					if($res['success']) {

						if((int)$this->sets['cafe_mode']==1) {
							if((int)$this->sets['send_orders']==0) {
								$kitchen=new \Models\Receipts($this->db, $this->f3, 'kitchen');
								$bar=new \Models\Receipts($this->db, $this->f3, 'bar');
								$this->f3->set('fr_error_ignore', 1);
								$kitchen->print($receipt['id'], 'all', (int)$this->sets['orders_device']);
								$bar->print($receipt['id'], 'all', (int)$this->sets['orders_device']);
							}
							$this->receiptlines->issued_receipt($receipt['id']);
						}

						$res['txt']='fiscalization_successful';
					}
					else {
						break;
					}
				}
				else {
					break;
				}
			}
		}
		$this->model->reset();
		$res['remote_receipts']=$this->model->count(array('remote>0 AND time<0'));
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		if($this->f3->get('GET.close')) {
			$res['close_all_window']=true;
		}
		echo json_encode($res);
		exit();
	}

	// Окно для отметки прохода сотрудника
	function walk() {
		$this->f3->set('page_data', $this->model->page_data('walk'));
	}
	function walk_add_card() {
		$barcode=$this->f3->get('POST.barcode');
		if(!$barcode) {
			$barcode=$this->f3->get('GET.barcode');
		}
		$this->f3->set('barcode', $barcode);
		$this->f3->set('page_data', $this->model->page_data('walk_add_card'));
	}

	// Отмечаем сотрудника
	function post_walk() {
		$data=$this->f3->get('POST');
		$data['type']=$this->f3->get('receipt_walk');
		$data['rm']=$this->api_data['rm_id'];
		$data['store']=$this->api_data['store_id'];
		$res=$this->model->validate_walk($data);
		if($res['success']) {
			$res=$this->model->add_walk($res['data']);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Окно вкрытия бутылки
	function chpok() {
		$barcode=$this->f3->get('GET.barcode');
		$product_id=$this->f3->get('GET.product_id');
		$products=array();
		if($barcode && !$product_id) {
			$prods=$this->products->search($barcode, 0, null, false);
			if($prods['success']) {
				$prod_id=array_column($prods['products'], 'id');
				$prods=$this->products->select_product(array('p.id IN ('.implode(', ', $prod_id).') AND p.date_delete=0 AND p.egais>0'));
				if(count($prods)>0) {
					$products=array(
						'success'=>true,
						'count'=>count($prods),
						'products'=>$prods
					);
				}
				else {
					$products=array(
						'success'=>false,
						'count'=>0,
						'products'=>array()
					);
				}
			}
			else {
				$products=$prods;
			}
		}
		if($product_id) {
			$prods=$this->products->select_product(array('p.id=?', $product_id), array('limit'=>1));
			if(count($prods)>0) {
				$products=array(
					'success'=>true,
					'count'=>count($prods),
					'products'=>$prods
				);
			}
			else {
				$products=array(
					'success'=>false,
					'count'=>0,
					'products'=>array()
				);
			}
		}
		if($products && $products['count']==1) {
			if((float)$products['products'][0]['price']>0) {
				$products['products'][0]['price']=round($products['products'][0]['price']+($products['products'][0]['price']*($products['products'][0]['vat']/100))*max(0, $products['products'][0]['vat_type']), 2);
			}
			$this->f3->set('page_data', $this->model->page_data('chpok_end'));
		}
		else {
			$this->f3->set('page_data', $this->model->page_data('chpok'));
		}
		$this->f3->set('products', $products);
	}

	// Вскрытие бутылки
	function post_chpok() {
		$post=$this->f3->get('POST');
		$product=$this->products->select_product(array('p.id=?', $post['product_id']), array('limit'=>1));
		if(!$product) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('not_found')['txt']
			);
			echo json_encode($res);
			exit();
		}

		if($post['price']<=$product[0]['buy_price']) {
			$this->f3->set('page_data', $this->messages->message('incorrect_price_with_buy_price'));
			return;
		}

		if($this->sets['check_egais']>0 && $this->sets['egais']==1 && $product[0]['egais']==1 && (!$post['not_check_mark'] || $this->sets['check_egais']==2)) {
			// Проверяем товар ЕГАИС
			$egais_res=$this->model->check_egais($post['code']);
			if($egais_res['success']===false) {
				$this->f3->set('mark_code', $post['code']);
				$this->f3->set('txt', $this->messages->message($egais_res['txt'])['txt']);
				$this->f3->set('page_data', $this->model->page_data('chpok_egais_error'));
				return;
			}
		}
		
		// Добавляем бутылку к чеку
		// Узнаем смену
		$change=$this->changes->get_change();
		// Узнаем сумму строк
		$sum=$post['price'];
		//$sum=round($product[0]['price']+($product[0]['price']*($product[0]['vat']/100))*max(0, $product[0]['vat_type']), 2);
		$res=$this->model->ticket_chpok($this->api_data['rm_id'], $this->api_data['store_id'], $change, $sum);
		$receipt_id=$res['id'];
		$receipt=$res['receipt'];
		if($res['success']) {
			// Добавляем строки
			$product[0]['barcode']=$post['barcode'];
			$product[0]['mark']=json_encode(array($post['code']));
			$product[0]['description']='Вскрытие тары';
			$product[0]['price']=$post['price'];
			if($product[0]['vat_type']>0) {
				$product[0]['price']=$post['price']/(100+$product[0]['vat'])*100;
			}
			if(!in_array($post['barcode'], array_column($product[0]['barcodes'], 'barcode'))) {
				$product[0]['other_info']=json_encode(array('barcode'=>$post['barcode']));
			}
			$res=$this->receiptlines->add_line($receipt_id, $product[0], 1);
			if($res['success']) {
				$res=$this->model->ticket_chpok_ready($receipt, $product);
				if($res['success']) {
					$issued_time=microtime(true);
					$this->receiptlines->save_lines($receipt, 0, $issued_time, $issued_time, $issued_time);
				}
			}
			else {
				$this->model->delete_receipt($receipt_id);
			}
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Добавить номер новой карты в чек
	function new_card() {
		$this->f3->set('new_partner', true);
		$this->add_partner();
	}

	// Окно для выбора модификатора для товара
	function modifiers() {
		$products=array();
		$line_id=$this->f3->get('GET.line_id');
		$line=$this->receiptlines->select_lines(array('id=?', $line_id), array('limit'=>1));
		if($line[0]['parent_id']>0) {
			$line=$this->receiptlines->select_lines(array('id=?', $line[0]['parent_id']), array('limit'=>1));
		}
		if($line) {
			$this->f3->set('line', $line[0]);
			$products=$this->products->modifiers($line[0]['product_id']);
			if($products) {
				foreach($products as $key=>$p) {
					$products[$key]['img']=json_decode($p['img'], true);
				}
				$this->f3->set('products', $products);
				$modifiers=$this->receiptlines->select_lines(array('parent_id=?', $line[0]['id']));
				if($modifiers) {
					$modifiers=array_combine(array_column($modifiers, 'product_id'), array_column($modifiers, 'count'));
				}
				$this->f3->set('modifiers', $modifiers);
			}
			$page_data=$this->model->page_data('modifiers');
		}
		else {
			$page_data=$this->messages->message('not_found');
		}
		$this->f3->set('page_data', $page_data);
	}

	function bonus_pay() {
		$result=$this->model->get_open_receipt($this->receipt_sets, false, (int) $this->sets['view_all_receipts']);
		if($result['success']===true) {
			$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $result['receipt']['id']));
			$summ=$this->receiptlines->get_sum($receiptlines, 0, $this->sets['round_kop'])['sum'];
			$result['receipt']['sum']=$summ;
			$max_bonus_pay=$this->receiptlines->max_bonus_pay($summ, $result['receipt']['partner'], $receiptlines);
			$result['receipt']['max_bonus_pay']=$max_bonus_pay;
			$result=$this->model->bonus_pay($result['receipt']);
		}
		$result['txt']=$this->messages->message($result['txt'])['txt'];
		echo json_encode($result);
		exit();
	}

	function correct1() {
		$id=$this->f3->get('GET.id');
		$receipt_sales=$this->f3->get('receipt_sales');
		$receipt_return=$this->f3->get('receipt_return');
		$receipt_correct_sales=$this->f3->get('receipt_correct_sales');
		$receipt_correct_return=$this->f3->get('receipt_correct_return');
		$receipt=$this->model->select_receipts(array('r.id=? AND r.time>0 AND r.type IN (?, ?, ?, ?)', array($id, $receipt_sales, $receipt_return, $receipt_correct_sales, $receipt_correct_return)), array('limit'=>1));
		if(!$receipt) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$reverse_receipt=array(
			$receipt_sales=>'чек коррекции/возврат',
			$receipt_return=>'чек коррекции/продажа',
			$receipt_correct_sales=>'чек коррекции/возврат',
			$receipt_correct_return=>'чек коррекции/продажа',
		);
		$receipt_types=array(
			$receipt_sales=>'Чек продажи',
			$receipt_return=>'Чек возврата',
			$receipt_correct_sales=>'Чек продажи',
			$receipt_correct_return=>'Чек возврата',
		);
		$this->f3->set('receipt', $receipt[0]);
		$this->f3->set('reverse_receipt',$reverse_receipt);
		$this->f3->set('receipt_types',$receipt_types);
		$this->f3->set('page_data', $this->model->page_data('correct1'));
		$this->cd->close_txt();
	}

	function post_correct1() {
		$ffd=$this->model->fr->sets['version'];
		$post=$this->f3->get('POST');
		$receipt=$this->model->select_receipts(array('r.id=? AND r.type IN (?, ?, ?, ?)', array($post['id'], $this->receipts_types['sales'], $this->receipts_types['return'], $this->receipts_types['correct_sales'], $this->receipts_types['correct_return'])), array('limit'=>1));
		if(!$receipt) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		if($receipt[0]['type']==$this->receipts_types['sales']) {
			$type=$this->receipts_types['correct_return'];
		}
		elseif($receipt[0]['type']==$this->receipts_types['return']) {
			$type=$this->receipts_types['correct_sales'];
		}
		elseif($receipt[0]['type']==$this->receipts_types['correct_sales']) {
			$type=$this->receipts_types['correct_return'];
		}
		elseif($receipt[0]['type']==$this->receipts_types['correct_return']) {
			$type=$this->receipts_types['correct_sales'];
		}
		if($ffd!='1.05') {
			$receipt[0]['correct_type']=$post['correct_type'];
			$receipt[0]['osn_number']=$post['osn_number'];
			$receipt[0]['osn_date']=$post['osn_date'];
		}
		$receipt[0]['fpd']=$post['fpd'];

		$change=$this->changes->get_change();
		$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt[0]['id']));
		$lines_sum=$this->receiptlines->get_sum($receiptlines);
		$res=$this->model->add_correct($receipt[0], $lines_sum['lines'], $type, $change);
		if(!$res['success']) {
			$this->f3->set('page_data', $this->messages->message($res['txt']));
			return;
		}
		if($receiptlines) {
			foreach($receiptlines as $n=>$l) {
				$l['id']=$l['product_id'];
				$line_res=$this->receiptlines->add_line($res['id'], $l, $l['count'], $l['parent_id']);
				if(!$line_res['success']) {
					$this->model->delete_receipt($res['id']);
					$this->f3->set('page_data', $this->messages->message($res['txt']));
					return;
				}
				//$receiptlines[$n]['loyalty']=0;
				$receiptlines[$n]['discount']=0;
				$receiptlines[$n]['description']='';
			}
		}
		
		// Создаем следующий чек коррекции
		if($type==$this->receipts_types['correct_sales']) {
			$type=$this->receipts_types['correct_return'];
		}
		elseif($type==$this->receipts_types['correct_return']) {
			$type=$this->receipts_types['correct_sales'];
		}
		$res=$this->model->add_correct($receipt[0], $receiptlines, $type, $change, false);
		if($receiptlines) {
			foreach($receiptlines as $n=>$l) {
				$l['id']=$l['product_id'];
				$line_res=$this->receiptlines->add_line($res['id'], $l, $l['count'], $l['parent_id']);
				if(!$line_res['success']) {
					$this->model->delete_receipt($res['id']);
					$this->f3->set('page_data', $this->messages->message($res['txt']));
					return;
				}
			}
		}
		$this->f3->set('COOKIE.receipt_id', $res['id']);
		$this->f3->set('COOKIE.table_id', $receipt[0]['table_id']);

		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function correct2() {
		$id=$this->f3->get('GET.receipt_id');
		$sql='id=? AND time=0 AND type IN (?, ?)';
		$val=array($id, $this->receipts_types['correct_sales'], $this->receipts_types['correct_return']);
		$this->model->load(array($sql, $val), array('limit'=>1));
		if($this->model->dry()) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$receipt=$this->model->cast();
		if($receipt['type']==$this->receipts_types['correct_sales']) {
			$this->f3->set('correct_sales', 1);
		}
		elseif($receipt['type']==$this->receipts_types['correct_return']) {
			$this->f3->set('correct_return', 1);
		}
		$this->sales();
	}

	function turn() {
		$receipt_id=$this->f3->get('GET.receipt_id');
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt_id), array('order'=>'turn, id'));
		$this->f3->set('lines', $lines);
		$this->f3->set('page_data', $this->model->page_data('turn'));
	}

	function post_turn() {
		$turns=$this->f3->get('POST.turn');
		$res=$this->model->set_turn($turns);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function executor_display() {
		$create=$this->f3->get('COOKIE.show_order_create');
		$complite=$this->f3->get('COOKIE.show_order_complite');
		$kitchen=$this->f3->get('COOKIE.show_order_kitchen');
		$id_kitchen=$this->f3->get('COOKIE.id_kitchen');
		$bar=$this->f3->get('COOKIE.show_order_bar');
		$id_bar=$this->f3->get('COOKIE.id_bar');
		$order_line_ok=$this->f3->get('COOKIE.order_line_ok');
		$get=$this->f3->get('GET');
		if(!isset($get['create']) && is_null($create)) {
			$get['create']=1;
		}
		if(!isset($get['complite']) && is_null($complite)) {
			$get['complite']=1;
		}

		if(!isset($get['kitchen']) && is_null($kitchen)) {
			$get['kitchen']=1;
		}
		if(!isset($get['bar']) && is_null($bar)) {
			$get['bar']=1;
		}
		if(!isset($get['id_kitchen']) && is_null($id_kitchen)) {
			$get['id_kitchen']=-1;
		}
		if(!isset($get['id_bar']) && is_null($id_bar)) {
			$get['id_bar']=-1;
		}

		if(!isset($get['create'])) {
			$get['create']=$create;
		}
		if(!isset($get['complite'])) {
			$get['complite']=$complite;
		}
		if(!isset($get['kitchen'])) {
			$get['kitchen']=$kitchen;
		}
		if(!isset($get['id_kitchen'])) {
			$get['id_kitchen']=$id_kitchen;
		}
		if(!isset($get['bar'])) {
			$get['bar']=$bar;
		}
		if(!isset($get['id_bar'])) {
			$get['id_bar']=$id_bar;
		}

		foreach($get as $key=>$value) {
			if($key=='id_bar' || $key=='id_kitchen') {
				$this->f3->set('COOKIE.'.$key, $value, 3600*24*365);
			}
			else {
				$this->f3->set('COOKIE.show_order_'.$key, $value, 3600*24*365);
			}
		}
		$this->f3->set('COOKIE.order_line_ok', $order_line_ok, 3600*24*365);


		if($get['create']==1) {
			$order_create=$this->model->all_order_create($get['kitchen'], $get['bar'], $get['id_kitchen'], $get['id_bar']);
		}
		else {
			$order_create=array();
		}
		if($get['complite']==1) {
			$order_complite=$this->model->all_order_complite($get['kitchen'], $get['bar'], $get['id_kitchen'], $get['id_bar']);
		}
		else {
			$order_complite=array();
		}
		if($this->sets['multikassa']==1) {
			if($get['create']==1) {
				$res=$this->multi_curl($this->sets['other_cashboxes_ip'], '/multikassa/all_order_create?kitchen='.$get['kitchen'].'&id_kitchen='.$get['id_kitchen'].'&bar='.$get['bar'].'&id_bar='.$get['id_bar'], $this->sets['ip_port']);
				$order_create=$this->model->other_all_orders($res, $order_create);
			}
			if($get['complite']==1) {
				$res=$this->multi_curl($this->sets['other_cashboxes_ip'], '/multikassa/all_order_complite?kitchen='.$get['kitchen'].'&id_kitchen='.$get['id_kitchen'].'&bar='.$get['bar'].'&id_bar='.$get['id_bar'], $this->sets['ip_port']);
				$order_complite=$this->model->other_all_orders($res, $order_complite);
			}
		}
		$this->f3->set('create', $get['create']);
		$this->f3->set('complite', $get['complite']);
		$this->f3->set('order_create', $order_create);
		$this->f3->set('order_complite', $order_complite);
		$json=json_encode(
			array(
				'orders_create'=>$order_create,
				'orders_complite'=>$order_complite
			)
		);
		$this->f3->set('json', $json);
		if($this->f3->get('GET.json')) {
			echo $json;
			exit();
		}
		$this->f3->set('page_data', $this->model->page_data('executor_display'));
	}

	function order_complite() {
		$get=$this->f3->get('GET');
		if($ip) {
			$res=$this->model->other_order_complite($get['ip'], $get['id'], $get['turn'], $get['issued'], $get['show_kitchen'], $get['id_kitchen'], $get['show_bar'], $get['id_bar']);
		}
		else {
			$res=$this->model->order_complite($get['id'], $get['turn'], $get['issued'], $get['show_kitchen'], $get['id_kitchen'], $get['show_bar'], $get['id_bar']);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function order_line_complite() {
		$id=$this->f3->get('GET.id');
		$ip=$this->f3->get('GET.ip');
		$issued=(int)$this->f3->get('GET.issued');
		if($ip) {
			$res=$this->model->other_order_line_complite($ip, $id, $issued);
		}
		else {
			$res=$this->model->order_line_complite($id, $issued);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function issued_order() {
		$get=$this->f3->get('GET');
		if($ip) {
			$res=$this->model->other_issued_order($get['ip'], $get['id'], $get['turn'], $get['show_kitchen'], $get['id_kitchen'], $get['show_bar'], $get['id_bar']);
		}
		else {
			$res=$this->model->issued_order($get['id'], $get['turn'], $get['show_kitchen'], $get['id_kitchen'], $get['show_bar'], $get['id_bar']);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function issued_order_line() {
		$id=$this->f3->get('GET.id');
		$ip=$this->f3->get('GET.ip');
		if($ip) {
			$res=$this->model->other_issued_order_line($ip, $id);
		}
		else {
			$res=$this->model->issued_order_line($id);
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function client_display() {
		$get=array(
			'create'=>1,
			'complite'=>1,
			'kitchen'=>1,
			'bar'=>1,
			'id_kitchen'=>-1,
			'id_bar'=>-1
		);
		$this->f3->set('GET', $get);
		$this->executor_display();
		$this->f3->set('page_data', $this->model->page_data('client_display'));
	}

	function online_order_status() {
		$status=new \Models\Ordersstatus($this->db, $this->f3);
		$this->f3->set('status', $status->select_ordersstatus());
		$this->f3->set('page_data', $this->model->page_data('online_order_status'));
	}

	function archive() {
		$get=$this->f3->get('GET');
		if(!$get['time']) {
			$get['time']=time();
			$this->f3->set('GET.time', $get['time']);
		}
		if(!isset($get['kitchen']) || $get['kitchen']=='') {
			$get['kitchen']=1;
		}
		if(!isset($get['bar']) || $get['kitchen']=='') {
			$get['bar']=1;
		}
		$receipts=$this->model->archive($get['time'], $get['kitchen'], $get['bar']);
		$this->f3->set('receipts', $receipts);
		$this->f3->set('page_data', $this->model->page_data('archive'));
	}

	// Сохранение комментария к чеку
	function post_description() {
		$post=$this->f3->get('POST');
		$res=$this->model->save_receipt($post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function pricetags() {
		if((int)$this->sets['product_menu']>0) {
			$c=new \Controllers\Products();
			$c->list();
		}

		$scales=new \Models\Scales($this->db, $this->f3);
		$this->f3->set('scales_settings', $scales->sets);
		$rooms=array();
		$table_id=0;
		$this->cd->close_txt();
		$receiptlines=array();
		$receipttype=$this->f3->get('receipt_print');
		$receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts'], $receipttype);
		if($receipt['success']) {
			$this->f3->set('COOKIE.receipt_id', $receipt['receipt']['id']);
			if(!$this->f3->get('AJAX')) {
				$this->f3->set('GET.line_id', 'all');
				$this->delete_line();
			}
			$linesset_id=$this->f3->get('GET.linesset_id');
			if($linesset_id && !$this->f3->get('AJAX')) {
				$lsm=new \Models\Linesset($this->db, $this->f3);
				$linesset=$lsm->select_linesset(array('id=?', $linesset_id), array('limit'=>1));
				if($linesset) {
					$this->f3->set('GET.line_id', 'all');
					$this->delete_line();
					$receipt['receipt']['description']=$linesset[0]['title'];
					$res=$this->model->save_receipt($receipt['receipt']);
					$json=json_decode($linesset[0]['txt'], true);
					$this->products->add_lineset($json);
				}
			}
			$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']), array('order'=>'turn, id'));
			$turns=array_unique(array_column($receiptlines, 'turn'));
			$this->f3->set('turns', $turns);
			//$this->model->set_discount(0);
			$summ=$this->receiptlines->get_sum($receiptlines, $receipt['receipt']['discount'], $this->sets['round_kop'])['sum'];
			if((int)$this->sets['round_kop']==1) {
				$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['receipt']['id']), array('order'=>'turn, id'));
			}
			$this->f3->set('summ', $summ);
			
			$control_sno=$this->receiptlines->control_sno($receiptlines, $this->model->fr->sets['sno']);
			$this->f3->set('sno_org', $this->model->fr->sets['sno']);
			$this->f3->set('control_sno', $control_sno['status']);

			$this->f3->set('receiptlines', $receiptlines);
			$this->f3->set('receipt', $receipt['receipt']);
			$this->f3->set('open_receipts', $receipt['open']);
			$line_id=$this->f3->get('GET.id');
			if(!$line_id && $receiptlines) {
				foreach (array_reverse($receiptlines) as $l) {
					if($l['parent_id']==0) {
						$line_id=$l['id'];
						break;
					}
				}
			}
			$this->f3->set('s', $line_id);
			$loyalty_models=new \Models\Loyalty($this->db, $this->f3);
			$this->f3->set('discounts', $loyalty_models->select_discounts());
			$this->f3->set('page_data', $this->model->page_data('pricetags'));
			/*$html=\Template::instance()->render('receiptlines.htm');
			if(file_exists($this->f3->get('UI').'receiptlines_html.htm')) {
				@unlink($this->f3->get('UI').'receiptlines_html.htm');
			}
			$this->f3->write($this->f3->get('UI').'receiptlines_html.htm', $html);
			if(file_exists($this->f3->get('UI').'qr_html.htm')) {
				@unlink($this->f3->get('UI').'qr_html.htm');
			}*/
			$this->f3->set('receipttype', $receipttype);
		}
		else {
			$this->f3->set('page_data', $this->messages->message($receipt['txt']));
		}
	}

	// Печать ценников
	function print_pricetags() {
		$get=$this->f3->get('GET');
		$product=$this->products->select_product(array('p.id=?', $get['product_id']), array('limit'=>1));
		if($product) {
			$res=$this->model->pricetags($product[0]);
			$res['txt']=$this->messages->message($res['txt'])['txt'];
		}
		else {
			$res['success']=false;
			$res=$this->messages->message('not_found');
		}
		echo json_encode($res);
		exit();
	}

	function show_qr() {
		$get=$this->f3->get('GET');
		$this->f3->set('page_data', $this->model->page_data('show_qr'));
		$html=\Template::instance()->render('qr.htm');
		$this->f3->write($this->f3->get('UI').'/qr_html.htm', $html);
		$html=\Template::instance()->render('receiptlines_qr.htm');
		$this->f3->write($this->f3->get('UI').'/receiptlines_html.htm', $html.'<div id="show_qr_ok" data-id="'.time().'"></div>');
	}

	function print_qr() {
		$res=$this->model->print_qr($this->f3->get('GET.url'));
		echo json_encode($res);
		exit();
	}

	function post_paycontrol_qr() {
		$res=$this->model->paycontrol_qr($this->f3->get('POST'));
		echo json_encode($res);
		exit();
	}

	function delete_product() {
		$product_id=$this->f3->get('GET.id');
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$res=$this->receiptlines->delete_product($receipt_id, $product_id);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function success_pay() {
		$this->f3->set('receipt', json_decode($this->f3->get('GET.receipt'), true));
		$this->f3->set('page_data', $this->model->page_data('success_pay'));
	}

	function add_combo($product) {
		$product['combo_data']=json_decode($product['combo_data'], true);
		if($this->f3->get('authorization_user.kiosk')==1) {
			$time=time();
			if((strtotime($product['combo_data']['date_start'])>$time || strtotime($product['combo_data']['date_end'])<$time)) {
				$this->f3->set('page_data', $this->messages->message('combo_dont_work'));
				return;
			}
			$h=date('H');
			if($h<10) $h='0'.$h;
			if(!$product['combo_data']['time']['d'.date('N')][$h]) {
				$this->f3->set('page_data', $this->messages->message('combo_dont_work'));
				return;
			}
		}
		$this->f3->set('product', $product);
		$items=$this->model->combo_items($product['combo_data']);
		$this->f3->set('items', $items);
		$this->f3->set('page_data', $this->model->page_data('add_combo'));
	}

	function post_add_combo() {
		$post=$this->f3->get("POST");
		if(!$post['count'])$post['count']=1;
		$combo=$this->products->select_product(array('p.id=? AND p.ppr=?', array($post['combo_id'], $this->f3->get('combo_ppr'))), array('limit'=>1));
		if(!$combo) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('not_found')['txt']
			);
		}
		else {
			$combo_id=time();
			$combo_data=json_decode($combo[0]['combo_data'], true);
			$products=$this->products->select_product(array('p.id IN ('.implode(', ', array_column($post['item'], 'product_id')).')'));
			$products=array_combine(array_column($products, 'id'), $products);
			$receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts']);
			foreach($post['item'] as $n=>$item) {
				$prod=$products[$item['product_id']];
				$prod['price0']=$prod['price'];
				$prod['loyalty']=3;
				$prod['description']=$combo[0]['title'];
				if($prod['vat_type']>0) {
					$prod['price']=$prod['price']-($item['price']/(100+$prod['vat'])*$prod['vat']);
				}
				else {
					$prod['price']=$item['price'];
				}
				$prod['combo_id']=$combo_id;
				$res=$this->receiptlines->add_line($receipt['receipt']['id'], $prod, (float)$post['count']);
				if(!$res) {
					$this->receiptlines->erase('combo_id=?', $combo_id);
					break;
				}
			}
		}
		echo json_encode($res);
		exit();
	}

	function split() {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt_id), array('order'=>'turn, id'));
		$this->f3->set('lines', $lines);
		$this->f3->set('receipt_id', $receipt_id);
		$this->f3->set('page_data', $this->model->page_data('split'));
	}

	function post_split() {
		$post=$this->f3->get('POST');
		$res=$this->model->split($this->receipt_sets, $post['receipt_id'], $post['lines']);
		$res['txt']=$this->messages->message($res['txt'])['txt'];

		if($res['success']===true) {
			foreach($res['receipts'] as $receipt_id) {
				$this->remove_partner($receipt_id, false);
			}
		}
		echo json_encode($res);
		exit();
	}

	function splitsno() {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt_id), array('order'=>'turn, id'));
		if(!$receiptlines) {
			$this->f3->set('page_data', $this->messages->message('not_enough_data'));
			return;
		}
		$lines=array_combine(array_column($receiptlines, 'id'), array_column($receiptlines, 'sno'));
		foreach($lines as $id=>$sno){
			if((string)$sno=='0') {
				$lines[$id]=$this->model->fr->sets['sno'];
			}
		}
		$res=$this->model->split($this->receipt_sets, $receipt_id, $lines);
		$res['txt']=$this->messages->message($res['txt'])['txt'];

		if($res['success']===true) {
			foreach($res['receipts'] as $receipt_id) {
				$this->remove_partner($receipt_id, false);
			}
		}
		echo json_encode($res);
		exit();
	}

	function printpricetags() {
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$this->model->reset();
		$this->model->load(array('id=?', $receipt_id), array('limit'=>1));
		if(!$this->model->dry()) {
			$this->f3->set('receipt', $this->model->cast());
		}
		$this->f3->set('printers', $this->model->fr->get_printers());
		$this->f3->set('page_data', $this->model->page_data('printpricetags'));
	}

	function post_printpricetags() {
		$post=$this->f3->get('POST');
		$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $post['receipt_id']), array('order'=>'turn, id'));
		$receiptlines=$this->receiptlines->get_sum($receiptlines, $post['discount']);
		$res=$this->model->printpricetags($receiptlines, $post);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

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

	function post_correction() {
		$post=$this->f3->get('POST');
		if($post['sum']>0 && $post['description'] && $post['docNum'] && $post['docDate']) {
			$change=$this->changes->get_change();
			if($change) {
				$res=$this->model->correction($post);
				$res['txt']=$this->messages->message($res['txt'])['txt'];
			}
			else {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('change_not_open')['txt']
				);
			}
		}
		else {
			$res=array(
				'success'=>false,
				'txt'=>$res=$this->messages->message('not_enough_data')['txt']
			);
		}

		echo json_encode($res);
		exit();
	}
}
