<?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'),
			'writeoff'=>$this->f3->get('receipt_writeoff'),
			'print'=>$this->f3->get('receipt_print'),
		);
		$this->receipt_sets=array(
			'rm'=>$this->api_data['rm_id'],
			'store'=>$this->api_data['store_id'],
			'prefix'=>$this->sets['orders_prefix'],
			'orders_type'=>$this->sets['orders_type']
		);
		if(!$this->cd) {
			$this->cd=new \Models\Cd($this->db, $this->f3);
		}
	}

	function product_search() {
		$product_model=$this->products;
		$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 && !$this->f3->get('writeoff')) {
			$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();
		if($this->f3->get('writeoff')==true) {
			$receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts'], $this->receipts_types['writeoff']);
		}
		else {
			$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']==2) {
				$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;
				}
			}

			$partner_bonus=0;
			if($receipt['receipt']['partner']['loyalty_type']==2) {
				if($receipt['receipt']['bonus_pay']==0 || $receipt['receipt']['partner']['bonus_add_sets']==1) {
					$partners_model=new \Models\Partners($this->db, $this->f3);
					$partner_bonus=$partners_model->partners_bonus($receipt['receipt']['partner'], $receiptlines, $summ);
				}
			}
			$this->f3->set('partner_bonus', $partner_bonus);

			$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());

			$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);
			
			$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');
			}
		}
		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 writeoff() {
		$this->f3->set('writeoff', true);
		$this->sales();
		$this->f3->set('receipttype', $this->receipts_types['writeoff']);
		$this->f3->set('page_data', $this->model->page_data('writeoff'));
	}

	// Раздел возрата
	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 IN (?, ?)', array($receipt_id, $this->receipts_types['sales'], $this->receipts_types['correct_sales'])), 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]);	
				}
				$products=new \Models\Products($this->db, $this->f3);
				$units=$products->units;
				$units_fr=array_column($units, 'number');
				$units_key=array_keys($units);
				$units=array_combine($units_fr, $units_key);
				foreach($receipt[0]['receiptlines'] as $n=>$line) {
					if($line['mark']!='') $receipt[0]['receiptlines'][$n]['mark_code']=str_replace('\u001d', '\\u001d', json_decode($line['mark'], true)[0]);
					$receipt[0]['receiptlines'][$n]['unit_okei']=$units[$line['units_fr']]??796;
				}

				$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');
		$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) {
		if($receipt['type']==$this->receipts_types['writeoff']) return;
		//$с=new \Models\Productcategories($this->db, $this->f3);
		//$parents=$с->get_parents($product['category_id']); // Родительские категории
		// Получаем программы лояльности
		if($receipt['type']==$this->receipts_types['print']) return;
		$l=new \Models\Loyalty($this->db, $this->f3);
		if(!isset($receipt['certificates'])) {
			$c=new \Models\Certificates($this->db, $this->f3);
			$receipt['certificates']=$c->receipt_certificates($receipt['id']);
		}
		$partner_data=json_decode($receipt['other_data'], true);
		if(is_array($partner_data) && isset($partner_data['partner'])) {
			$partner_data=$partner_data['partner'];
		}
		else {
			$partner_data=array(
				'id'=>-1,
				'group_id'=>$this->f3->get('default_partnergroup') // Розничный покупатель
			);
		}
		$loyalty=$l->get_loyalty($partner_data, $product, $receipt['certificates']);
		if(count($loyalty)>0) {
			$this->receiptlines->apply_loyalty($receipt, $product, $loyalty);
		}

		// Проверим акции на сумму чека
		$this->receipt_sum_loyalty($receipt);
		$this->auto_add_loyalty($receipt);
	}

	function receipt_sum_loyalty($receipt) {
		$receipt['sum']=0;
		$lines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt['id']));
		if($lines) {
			$lines_sum=$this->receiptlines->get_sum0($lines);
			$receipt['sum']=$lines_sum['sum'];
		}

		$l=new \Models\Loyalty($this->db, $this->f3);
		$loyalty=$l->get_receipt_sum_loyalty($receipt);
		if($loyalty && $lines) {
			$this->receiptlines->cancel_receipt_sum_loyalty($receipt, $loyalty);	
			foreach($lines as $line) {
				$line['id']=$line['product_id'];
				$line['price']=$line['price0'];
				$this->receiptlines->apply_loyalty($receipt, $line, $loyalty, true);
			}
		}
	}

	// Отмена акций
	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][0]=str_replace($this->sets['gs1_symbols'], '', $post['mark'][$p][0]);
        	}

			$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 post_add_line() {
		$post=$this->f3->get('POST');
		if($post) {
			foreach($post as $key=>$value) {
				$this->f3->set('GET.'.$key, $value);
			}
		}
		return $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');
		if(!$product_id) {
			$line_id=$this->f3->get('GET.line_id');
			if($line_id) {
				$line=$this->receiptlines->select_lines(array('id=?', array($line_id)), array('limit'=>1));
				if($line) {
					$product_id=$line[0]['product_id'];
				}
			}
		}
		$count=(float)$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');
		$reqId=$this->f3->get('GET.mark_reqId');
		$reqTimestamp=$this->f3->get('GET.reqTimestamp');
		$smp=$this->f3->get('GET.smp');
		$mrp=$this->f3->get('GET.mrp');
		$set_price=$this->f3->get('GET.set_price');
		$spill_line=$this->f3->get('REQUEST.spill_line');
		$certificate=$this->f3->get('REQUEST.certificate');
		$combo_id=$this->f3->get('REQUEST.combo_id');
		$combo_step=$this->f3->get('REQUEST.combo_step');

		if($product_id>0 && $parent_id>0 && $count==0) {
			$line=$this->receiptlines->select_lines(array('product_id=? AND parent_id=?', array($product_id, $parent_id)), array('limit'=>1));
			if($line) {
				$this->f3->set('GET.line_id', $line[0]['id']);
				return $this->delete_line();
			}
		}
		
		if(is_array($mark)) {
			$mark=json_encode($mark);
		}

		$receipt_print=$this->receipts_types['print'];
		$receipt_writeoff=$this->receipts_types['writeoff'];

		$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($this->f3->get('authorization_user.id')!=$open_receipt['receipt']['user_id']) {
			$page_data=$this->messages->message('receipts_is_ready');
			$this->f3->set('page_data', $page_data);
			return;
		}

		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));

				if($res[0]['cocktail']!='' && $res[0]['egais']==0) {
					$this->f3->set('product', $res[0]);
					$this->f3->set('bottles', $this->receiptlines->open_bottles($res[0]['components']));
					$this->f3->set('page_data', $this->model->page_data('add_cocktail_line'));
					return;
				}
				if($open_receipt['receipt']['type']==$receipt_writeoff && $res[0]['buy_price']>0) {
					$res[0]['price']=$res[0]['buy_price'];
				}

				$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($res[0]['quantity']==0) $res[0]['multiple_sale']=0;
				if((int)$res[0]['multiple_sale']>0 && ($count<(float)$res[0]['quantity'] || ($count*1000)%($res[0]['quantity']*1000)>0) && $receipttype!=$this->receipts_types['writeoff']) {
					$page_data=$this->messages->message('error_multiple_sale');
					$page_data['txt']=str_replace('@n', $res[0]['quantity'], $page_data['txt']);
					$this->f3->set('page_data', $page_data);
					return;
				}

				if($mark=='[""]')$mark='';
				$mark_code=json_decode($mark)[0];
				if(!$this->f3->get('POST.mark') && $mark_code) {
					$mark_code=base64_decode($mark_code);
					$mark=json_encode(array($mark_code));
				}

				if((int)$res[0]['ppr']==13 && !$certificate) {
					$this->f3->set('products', $res);
					$this->f3->set('page_data', $this->model->page_data('add_certificate'));
					return;
				}
				if((int)$res[0]['ppr']==13 && $certificate) {
					$res[0]['certificate']=$certificate;

					if(!$this->receiptlines->check_double_certificate($res[0])) {
						$this->f3->set('txt', $this->messages->message('double_certificate')['txt']);
						$this->f3->set('products', $res);
						$this->f3->set('page_data', $this->model->page_data('add_certificate'));
						return;
					}
				}

				if((int)$this->sets['spill']==1 && (int)$res[0]['marking_group']==16 && $receipttype!=$receipt_print) {
					$taps=new \Models\Taps($this->db, $this->f3);
					$tap=$taps->get_tap($product_id, $mark_code);
					if(empty($tap)) {
						$this->f3->set('page_data', $this->messages->message('tap_not_found'));
						return;
					}
					if(count($tap)==1) {
						if(!$mark_code) {
							$mark_code=$tap[0]['mark'];
							$mark_code=str_replace('\u001d', $this->sets['gs1_symbols'], $mark_code);
							$mark=json_encode(array($mark_code));
							$this->f3->set('POST.mark', $mark);
							//$this->f3->set('GET.not_check_mark', 1);
						}
						$expiration_date=$tap[0]['expiration_date'];
						if($expiration_date<time() && $expiration_date>0 && $this->sets['check_expiration_date']>0 && (!$this->f3->get('GET.not_check_expiration_date') || $this->sets['check_expiration_date']==2)) {
							$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($tap[0]['current_volume_with_lines']<$count && !$this->f3->get('GET.not_check_current_volume')) {
							$this->f3->set('mark_code', $mark_code);
							$this->f3->set('action', 'add_line');
							$this->f3->set('tap', $tap[0]);
							$this->f3->set('txt', $this->messages->message('no_required_amount')['txt']);
							$this->f3->set('page_data', $this->model->page_data('current_volume_error'));
							return;
						}
					}
					else {
						$this->f3->set('taps', $tap);
						$this->f3->set('page_data', $this->model->page_data('select_tap'));
						return;
					}
				}

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

				if($count!=1 && (int)$res[0]['ppr']==13) {
					$this->f3->set('page_data', $this->messages->message('quantity_goods_may_not_exceed_1'));
					return;
				}

				if($count!=1 && $res[0]['marking']>0 && $res[0]['units_fr']==0 && !$mark_code) {
					$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') && $receipttype!=$receipt_print && !$combo_id) {
					$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_code) || ($res[0]['marking']==1 && $mark=='[""]')) && $receipttype!=$receipt_print) {
					if($mark=='[""]') {
						$this->f3->set('page_data', $this->messages->message('incorrect_data'));
						return;
					}
					if(!$this->f3->get('POST.mark') || ($res[0]['marking']==1)) {
						$this->f3->set('products', $res);
						$this->f3->set('page_data', $this->model->page_data('add_marking'));
						return;
					}
				}
				if((int)$this->sets['egais']>=0 && (($res[0]['egais']==1 && !$mark_code) || ($res[0]['egais']==1 && $mark=='[""]' && (int)$this->sets['check_egais']==2)) && $receipttype!=$receipt_print) {
					if(!$this->sets['fsrar_id']) {
						$this->f3->set('page_data', $this->messages->message('add_fsrar_id'));
						return;
					}
					if($mark=='[""]') {
						$this->f3->set('page_data', $this->messages->message('incorrect_data'));
						return;
					}
					$this->f3->set('products', $res);
					$this->f3->set('bottles', $this->receiptlines->open_bottles(array(array('product_id'=>$res[0]['id']))));
					$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($this->sets['gs1_symbols']!='') {
        			$mark_code=str_replace($this->sets['gs1_symbols'], '', $mark_code);
        			$mark=str_replace($this->sets['gs1_symbols'], '\\u001d', $mark);
        		}
        		$mark_code=str_replace('%2B', '+', $mark_code);
        		if(preg_match("/[А-Яа-я]/", $mark_code) && !$this->f3->get('GET.not_check_mark')) {
        			$this->f3->set('base_settings.check_mark', 0);
        			$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($res[0]['marking_group']=='11' && !$this->f3->get('GET.not_check_mark') && $receipttype!=$receipt_print) {
        			preg_match("/=[A-Z0-9]{2}-[A-Z0-9]{6}-[A-Z0-9]{10}\b$/i", $mark_code, $kiz);
        			if(!$kiz) {
        				preg_match("/^[A-Z0-9]{2}-[A-Z0-9]{6}-[A-Z0-9]{10}\b$/i", $mark_code, $kiz);
        			}
	        		if($kiz) {
	        			$mark_code=$kiz[0];
	        			$mark_code=str_replace('=', '', $mark_code);
	        			$mark=json_encode(array($mark_code));
	        		}
	        		else {
	        			$this->f3->set('base_settings.check_mark', 0);
	        			$this->f3->set('mark_code', $mark_code);
						$this->f3->set('txt', $this->messages->message('incorrect_data')['txt']);
						$this->f3->set('page_data', $this->model->page_data('marking_error'));
						return;
	        		}
	        	}
				if($receipttype==1) {
					if($res[0]['marking_group']=='')$res[0]['marking_group']=0;
					$required_check=$this->sets['required_check_'.$res[0]['marking_group']]??0;
					if($mark_code!='' && (int)$this->sets['check_mark']>0 && ($res[0]['egais']==0 || $res[0]['egais']==2) && (!$this->f3->get('GET.not_check_mark') || $this->sets['check_mark']==2) && $res[0]['marking_group']!='11') {
						// Проверяем маркировку товара
						$change=$this->changes->get_change();
						if((int)$required_check>0) {
							$this->sets['check_expiration_date']=0;
							$mark_res=$this->model->check_mark_chz($this->sets, $res[0], $mark_code);
							if($this->model->fr->sets['driver']=='drivers/printers/php_mspos') {
								$this->f3->set('fr_error_ignore', true);
								$this->model->check_mark($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('check_result', $mark_res['check_result']);
								$this->f3->set('mark_res', $mark_res);
								$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;
							}
							$res[0]['reqId']=$mark_res['reqId'];
							$res[0]['reqTimestamp']=$mark_res['reqTimestamp'];
							$res[0]['inst']=$mark_res['inst'];
							$res[0]['version']=$mark_res['version'];
							if(isset($mark_res['result']['smp'])) {
								$res[0]['smp']=$mark_res['result']['smp'];
							}
							if(isset($mark_res['result']['mrp'])) {
								$res[0]['mrp']=$mark_res['result']['mrp'];
							}
							if(isset($mark_res['result']['innerUnitCount']) && $res[0]['marking_group']==8) {
								$count=$mark_res['result']['innerUnitCount'];
								if((int)$res[0]['units']==166) $count/=1000;
							}
							if(isset($mark_res['result']['set_price'])) {
								$res[0]['price']=$mark_res['result']['set_price'];
								$res[0]['description']='МРЦ/ЕРЦ из кода маркировки';
								$res[0]['loyalty']=2;
							}
						}
						else {
							$mark_res=$this->model->check_mark($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;
							}
							if($mark_res['count']>0) {
								$count=$mark_res['count'];
							}
							$expiration_date=$mark_res['expiration_date'];
						}
					}
					if($mark_code!='' && $res[0]['egais']==1 && (int)$res[0]['units']==796 && (!isset($res[0]['barcodes'][0]['barcode']) || (mb_strlen($res[0]['barcodes'][0]['barcode'])!=8 && mb_strlen($res[0]['barcodes'][0]['barcode'])!=12 && mb_strlen($res[0]['barcodes'][0]['barcode'])!=13))) {
						$this->f3->set('page_data', $this->messages->message('barcode_not_correct'));
						return;
					}
					if($mark_code!='' && $res[0]['egais']==1 && mb_strlen($mark_code)<150 && !$this->f3->get('GET.not_check_mark')) {
						$this->f3->set('mark_code', $mark_code);
						$txt=$this->messages->message('incorrect_mark_code')['txt'];
						$this->logs->save_log("ЕГАИС\n\n".$mark_code."\n\n".$txt);
						$this->f3->set('txt', $txt);
						$this->f3->set('page_data', $this->model->page_data('egais_error'));
						return;
					}

					if($mark_code!='' && $this->sets['check_egais']>=0 && $this->sets['autonomous']==0 && $res[0]['egais']==1 && !$this->f3->get('GET.not_check_mark')) {
						// Проверяем марки в БД
						$egais_res=$this->receiptlines->check_egais_mark($mark_code, $count, $res[0]);
						if($egais_res['success']===false) {
							$this->f3->set('mark_code', $mark_code);

							if($egais_res['txt']=='no_required_amount' && $egais_res['spill']==true) {
								$spill_line[$mark_code]=array(
									'mark'=>$mark_code,
									'count'=>$egais_res['current_volume']
								);
								$res[0]['count']-=$egais_res['current_volume'];
								$this->f3->set('spill_line', $spill_line);
								$this->f3->set('products', $res);
								$open_bottles=$this->receiptlines->open_bottles(array(array('product_id'=>$res[0]['id'])));
								if($open_bottles) {
									foreach($open_bottles as $pn=>$product_bottle) {
										foreach($product_bottle['bottles'] as $bn=>$bottle) {
											if(isset($spill_line[$bottle['mark']])) $open_bottles[$pn]['bottles'][$bn]['current_volume']-=$spill_line[$bottle['mark']]['count'];
											if($open_bottles[$pn]['bottles'][$bn]['current_volume']<=0) {
												unset($open_bottles[$pn]['bottles'][$bn]);
											}
										}
									}
								}
								$this->f3->set('bottles', $open_bottles);
								$this->f3->set('page_data', $this->model->page_data('add_marking'));
								return;
							}

							$txt=$this->messages->message($egais_res['txt'])['txt'];
							$this->logs->save_log("ЕГАИС\n\n".$mark_code."\n\n".$txt);
							$this->f3->set('txt', $txt);
							$this->f3->set('page_data', $this->model->page_data('egais_error'));
							return;
						}
					}

					if($mark_code!='' && $res[0]['units']==796 && $parent_id==0 && $this->sets['check_egais']>0 && $this->sets['egais']==1 && $res[0]['egais']==1 && (!$this->f3->get('GET.not_check_mark_2') || $this->sets['check_egais']==2)) {
						// Проверяем товар ЕГАИС
						$egais_res=$this->model->check_egais($mark_code, $res[0]);
						if($egais_res['success']===false) {
							$this->f3->set('mark_code', $mark_code);
							$txt=$this->messages->message($egais_res['txt'])['txt'];
							$this->logs->save_log("ЕГАИС\n\n".$mark_code."\n\n".$txt);
							$this->f3->set('txt', $txt);
							$this->f3->set('page_data', $this->model->page_data('egais_error_2'));
							return;
						}
					}
					if($mark_code!='' && !isset($mark_res['result']['set_price']) && $res[0]['egais']==0 && !$this->f3->get('GET.not_check_mrc')) {
						$price=$res[0]['price']+($res[0]['price']*($res[0]['vat']/100))*max(0, $res[0]['vat_type']);
						$mrc=$this->model->mark_for_chz($mark_code)['mrc'];
						if($mrc>0) {
							if($res[0]['vat_type']>0) {
								$mrc=$mrc/(100+$res[0]['vat'])*100;
							}
							$res[0]['price']=$mrc;
							$res[0]['description']='МРЦ из кода маркировки';
							$res[0]['loyalty']=1;
						}
					}

					if($mark_code!='' && $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($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(($this->sets['check_egais']>0 && $res[0]['egais']>0) || ($this->sets['check_double_mark']==0 && $res[0]['egais']==0)) {
						$this->sets['check_double_mark']=0;
						$this->f3->set('GET.not_check_double_mark', 1);
					}
					if($mark_code!='' && $res[0]['units_fr']==0 && (!$this->f3->get('GET.not_check_double_mark') || $this->sets['check_double_mark']==2) && $res[0]['marking_group']!='16') {
						// Проверяем повтор марки
						$mark_res=$this->receiptlines->check_double_mark($mark_code, $open_receipt['receipt']['id']);
						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;
				if($res[0]['id']<0) {
					$res[0]['other_info']=json_encode($res[0]);
				}
			}
			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']!='' || $open_receipt['receipt']['egais_sign']!='') {
						$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
						return;
					}
					$receipt=$open_receipt['receipt'];

					if($reqId) $res[0]['reqId']=$reqId;
					if($reqTimestamp)$res[0]['reqTimestamp']=$reqTimestamp;
					if($smp) {
						$res[0]['smp']=$smp;
					}
					if($mrp) {
						$res[0]['mrp']=$mrp;
					}
					if($set_price) {
						$res[0]['price']=$set_price;
						$res[0]['description']='МРЦ/ЕРЦ из кода маркировки';
						$res[0]['loyalty']=2;
					}
					if($spill_line) {
						foreach($spill_line as $line) {
							$spil_product=$res[0];
							$spil_product['mark']='["'.$line['mark'].'"]';
							$result=$this->receiptlines->add_line($receipt['id'], $spil_product, $line['count'], $parent_id);
						}
					}

					if($combo_id>0) {
						if($this->f3->get('combo_return')===true) return $result;
						$item=$this->f3->get('POST.item');
						$item[$combo_step]['mark_data']=array(
							'mark'=>$mark_code,
							'mark_reqId'=>$reqId,
							'reqTimestamp'=>$reqTimestamp
						);
						$this->f3->set('POST.item', $item);
						$this->f3->set('POST.combo_step', $combo_step+1);
						return $this->post_add_combo();
					}
					$result=$this->receiptlines->add_line($receipt['id'], $res[0], $count, $parent_id);
					if($result['success']) {
						if($mark_code) {
							$line=$this->receiptlines->select_lines(array('id=?', $result['id']), array('limit'=>1));
							if(!json_encode($line)) {
								$this->f3->set('mark_code', $mark_code);
								$this->f3->set('txt', $this->messages->message('invalid_mark')['txt']);
								$this->f3->set('page_data', $this->model->page_data('marking_invalid_error'));
								return;
							}
						}

						$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'] && $count>0) {
			$this->receiptlines->linesmerge($result['id']);
		}

		if($price==0 && $product_id!=0 && $result['id']>0 && !$parent_id) {
			$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=(float)str_replace(',', '.', $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']==4) {

			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('line_not_change')['txt']
			);

			if($exit) {
				echo json_encode($res);
				exit();
			}
			return $res;
		}

		if($loyalty==0 && $line[0]['loyalty']!=0) $loyalty=$line[0]['loyalty'];
		if($description===false && $line[0]['description']!='') $description=$line[0]['description'];

		if($line[0]['mrp']>0 && $line[0]['mrp']/100<$price) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('mrc_error')['txt']
			);
			if($exit) {
				echo json_encode($res);
				exit();
			}
			return $res;
		}

		if($line['smp'][0]/100>$price) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('smp_error')['txt']
			);
			if($exit) {
				echo json_encode($res);
				exit();
			}
			return $res;
		}
		$receipt=$this->model->find(array('id=?', $line[0]['receipt_id']), array('limit'=>1));
		if($this->f3->get('authorization_user.id')!=$receipt[0]['user_id']) {
			$page_data=$this->messages->message('receipts_is_ready');
			$this->f3->set('page_data', $page_data);
			return;
		}

		$mark=json_decode($line[0]['mark'], true)[0];
		if((int)$this->sets['spill']==1 && $line[0]['pg']=='draftbeer') {
			$taps=new \Models\Taps($this->db, $this->f3);
			$tap=$taps->get_tap($line[0]['product_id'], $mark);
			if(empty($tap)) {
				$page_data=$this->messages->message('keg_disconnection');
				if(!$exit) {
					return array(
						'success'=>false,
						'txt'=>$page_data['txt']
					);
				}

				$this->f3->set('page_data', $page_data);
				return;
			}
			if($tap[0]['current_volume_with_lines']<$count-$line[0]['count'] && !$this->f3->get('POST.not_check_current_volume') && $receipt[0]['type']!=$this->receipts_types['writeoff']) {
				$txt=$this->messages->message('no_required_amount')['txt'];
				if(!$exit) {
					return array(
						'success'=>false,
						'txt'=>$txt
					);
				}
				$this->f3->set('mark_code', $mark);
				$this->f3->set('action', 'change_count');
				$this->f3->set('GET.product_id', $line[0]['product_id']);
				$this->f3->set('line_id', $line[0]['id']);
				$this->f3->set('tap', $tap[0]);
				$this->f3->set('txt', $txt);
				$this->f3->set('page_data', $this->model->page_data('current_volume_error'));
				return;
			}
		}
		if($mark!='' && $this->sets['check_egais']==0 && $this->sets['autonomous']==0 && $line[0]['egais']==1 && !$this->f3->get('GET.not_check_mark')) {
			// Проверяем марки в БД
			$egais_res=$this->receiptlines->check_egais_mark($mark, $count-$line[0]['count'], $line[0]);
			if($egais_res['success']===false) {
				$this->f3->set('mark_code', $mark);
				$txt=$this->messages->message($egais_res['txt'])['txt'];
				$this->logs->save_log("ЕГАИС\n\n".$mark."\n\n".$txt);
				$this->f3->set('txt', $txt);
				$this->f3->set('page_data', $this->model->page_data('egais_error'));
				return;
			}
		}
		if($line[0]['quantity']==0) $line[0]['multiple_sale']=0;
		if((int)$line[0]['multiple_sale']>0 && ($count<(float)$line[0]['quantity'] || ($count*1000)%($line[0]['quantity']*1000)>0) && $receipt[0]['type']!=$this->receipts_types['writeoff']) {
			$page_data=$this->messages->message('error_multiple_sale');
			$page_data['txt']=str_replace('@n', $line[0]['quantity'], $page_data['txt']);
			if(!$exit) {
				return array(
					'success'=>false,
					'txt'=>$page_data['txt']
				);
			}
			$this->f3->set('page_data', $page_data);
			return;
		}
		if($line[0]['loyalty']>0) {
			$loyalty=$line[0]['loyalty'];
		}

		$receipt_print=$this->receipts_types['print'];

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

		$components=$this->receiptlines->select_lines(array('parent_id=? AND mark!=""', $line_id), array('limit'=>1));
		if($components) {
			$page_data=$this->messages->message('quantity_goods_may_not_exceed_1');
			if(!$exit) {
				return array(
					'success'=>false,
					'txt'=>$page_data['txt']
				);
			}
			$this->f3->set('page_data', $page_data);
			return;
		}

		if($line[0]['product_id']==0 && $line[0]['parent_id']!=0) {
			$page_data=$this->messages->message('error_change_modifikation');
			if(!$exit) {
				return array(
					'success'=>false,
					'txt'=>$page_data['txt']
				);
			}
			$this->f3->set('page_data', $page_data);
			return;
		}

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

		if($line[0]['combo_id']>0) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('its_combo')['txt']
			);
		}
		else{
			if($receipt[0]['slip']!='' || $receipt[0]['egais_sign']!='') {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('dont_change_payed_receipt')['txt']
				);
				if(!$exit) {
					return $res;
				}
				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) {
						$components=$this->receiptlines->select_lines(array('parent_id=?', $line_id));
						if($components) {
							if($line[0]['quantity']==0)$line[0]['quantity']=1;
							$quantity=$count/$line[0]['quantity'];
							foreach($components as $c){
								$c['count']=round($c['quantity']*$quantity, 3);
								if($c['multiple_sale']>0) {
									$c['count']=ceil($c['count']/$c['quantity'])*$c['quantity'];
								}
								$rr=$this->receiptlines->change_line($c['id'], $c['count'], $c['price'], $c['discount']);
							}
						}


						// Товар, к которому применяется скидка
						$product=$this->products->select_product(array('p.id=?', $res['line']['product_id']), array('limit'=>1));

						if($count!=1 && (int)$product[0]['ppr']==13) {
							$this->f3->set('page_data', $this->messages->message('quantity_goods_may_not_exceed_1'));
							return;
						}

						if($product[0]['stop']) {
							$page_data=$this->messages->message('product_stoped');
							if(!$exit) {
								return array(
									'success'=>false,
									'txt'=>$page_data['txt']
								);
							}
							$this->f3->set('page_data', $page_data);
							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($res['success'] && $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']!='' || $receipt['egais_sign']!='') {
			$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
			return;
		}

		if($lines[0]['product_id']==0 && $lines[0]['parent_id']!=0) {
			$this->f3->set('page_data', $this->messages->message('error_change_modifikation'));
			return;
		}

		if($lines[0]['mrp']>0 || $lines[0]['smp']>0) {
			$this->f3->set('page_data', $this->messages->message('price_from_mark'));
			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'];
			$lines[0]['quantity']=$product[0]['quantity'];
			$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');
		if(!$writeoff_bonus) $writeoff_bonus=0;
		if(!$writeoff_bonus0) $writeoff_bonus0=0;
		$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']!='' || $receipt['egais_sign']!='') {
			$this->f3->set('page_data', $this->messages->message('dont_change_payed_receipt'));
			return;
		}

		if($lines[0]['product_id']==0 && $lines[0]['parent_id']!=0) {
			$this->f3->set('page_data', $this->messages->message('error_change_modifikation'));
			return;
		}

		if($lines[0]) {
			$product=$this->products->select_product(array('p.id=?', $lines[0]['product_id']), array('limit'=>1));
			$scales=new \Models\Scales($this->db, $this->f3);
			$this->f3->set('scales_settings', $scales->sets);
			$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() {
		$res=$this->change_line(false);

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

	// Удаляем строки
	function delete_line() {
		$this->cd->clear_cd();
		$select_id=0;
		$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=?", array($receipt_id)), array('limit'=>1));
		$receipt=$this->model->cast();
		if($this->f3->get('authorization_user.id')!=$receipt['user_id']) {
			$page_data=$this->messages->message('receipts_is_ready');
			$this->f3->set('page_data', $page_data);
			return;
		}

		if($receipt['slip']!='' || $receipt['egais_sign']!='') {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('dont_change_payed_receipt')['txt']
			);
			if(!$this->f3->get('AJAX')) return $res;
			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') {
			if($line_id>0 && $line_id!='all') {
				// Определим какуб строку надо выделить после удаления
				$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt_id), array('order'=>'turn, id'));
				if($receiptlines && count($receiptlines)>1) {
					$s_line_id=array_search($line_id, array_column($receiptlines, 'id'));
					if(isset($receiptlines[$s_line_id+1])) $s_line_id+=1;
					else $s_line_id-=1;
					$select_id=$receiptlines[$s_line_id]['id'];
				}
			}
			$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);
				$c=new \Models\Certificates($this->db, $this->f3);
				$certificates=$c->receipt_certificates($receipt_id);
				if($certificates) {
					$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
					foreach($certificates as $certificate) {
						$c->remove_certificate($certificate);
						$api->removecertificate($certificate);
					}
				}
			}
			if($this->f3->get('GET.reload')) {
				$res['function']='location.replace("/")';
			}
			if($select_id>0) {
				$res['id']=$select_id;
				$res['scroll']='.receiptlines_div';
				$res['scrollto']='#line_'.$select_id;
			}
		}
		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');
		$psr_select=4;
		$sum=$this->f3->get('GET.sum');
		$pay=$this->f3->get('GET.pay');
		$type=$this->f3->get('GET.type');
		if($sum && $pay) {
			$this->cd->total_price($sum, $pay);
			exit();
		}
		if($type==$this->receipts_types['writeoff']) {
			$receipt=$this->model->get_open_receipt($this->receipt_sets, false, (int) $this->sets['view_all_receipts'], $type);
		}
		else {
			$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;
		}

		foreach($lines as $line){
			if($line['count']<=0) {
				if($line['product_id']==0 && $line['parent_id']!=0) continue;
				$this->f3->set('page_data', $this->messages->message('lines_with_count_0'));
				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'];
		}

		if($receipt['receipt']['psr']) {
			$psr_select=$receipt['receipt']['psr'];
		}

		if($psr_select>0) {
			$psr_types=$this->f3->get('psr');
			if(!isset($psr_types[$psr_select])) $psr_select=4;
			if(!in_array($psr_select, $this->model->fr->sets['psr'])) $psr_select=$this->model->fr->sets['psr'][0];
		}
		else {
			$psr_select=4;
		}

		$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'];
		$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'];
		$receipt['receipt']['bonus_pay']=array_sum(array_column($lines_sum['lines'], 'bonus_pay'));
		//$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'];
		}

		$partner_bonus=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==$this->receipts_types['return'] || $type==$this->receipts_types['correct_return']) { // Возврат
					$partner_bonus=-$partner_bonus;
				}
			}
		}
		$this->f3->set('partner_bonus', $partner_bonus);

		$this->f3->set('sno_select', $sno_select);
		$this->f3->set('psr_select', $psr_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');
		$psr=$this->f3->get('REQUEST.psr');
		$fpd=$this->f3->get('REQUEST.fpd');
		$writeoff=$this->f3->get('REQUEST.writeoff');
		$type=$this->f3->get('REQUEST.type');
		if($this->f3->get('REQUEST.no_egais')==1) {
			$this->f3->set('no_egais', true);
		}
		if(!$sno) $sno=$this->model->fr->sets['sno'];
		if(!$psr) $psr=4;
		if($type==$this->receipts_types['writeoff']) {
			$receipt=$this->model->get_open_receipt($this->receipt_sets, false, (int) $this->sets['view_all_receipts'], $type);
		}
		else {
			$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==$this->receipts_types['return'] || $type==$this->receipts_types['correct_return']) { // Возврат
								$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();
						if(is_array($pays)) {
							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'));
					$receipt['receipt']['bonus_pay']=array_sum(array_column($lines_sum['lines'], 'bonus_pay'));
					$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, $psr);
					// Записываем скидку в товары
					if($res['success']) {
						if(isset($res['sales_receipts']) && $res['sales_receipts']==1)  {
							$sales_receipts=$res['sales_receipts'];
						}

						// Проверяем наличия разливного пива в чеке, чтобы изменить объем кега
						if((int)$this->sets['spill']==1) {
							$taps=new \Models\Taps($this->db, $this->f3);
							foreach($lines_sum['lines'] as $line){
								if($line['pg']=='draftbeer') {
									$mark=json_decode($line['mark'], true)[0];
									if($type==2 || $type==130) $line['count']=-$line['count'];
									$taps->change_current_volume($mark, $line['count']);
								}
							}
						}

						// Проверяем наличие алкоголя, чтобы изменить объем в бутылках
						foreach($lines_sum['lines'] as $line) {
							if($line['mark']!='') {
								$lr=$this->receiptlines->change_mark_volume($line, $type);
								if($lr['success'] && $lr['chpok']) {
									$this->auto_chpok($line['mark'], $change);
								}
							}
						}

						$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='/';
							}
							elseif($type==$this->receipts_types['return']) {
								$url='/receipts/return';
							}
							elseif($type==$this->receipts_types['writeoff']) {
								$url='/receipts/writeoff';
							}
							else {
								$url='';
							}
							$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'];

					if(isset($res['egais_xml'])) {
						$this->f3->set('txt', $res['error']);
						$this->f3->set('page_data', $this->model->page_data('egais_ticket_error'));
						return;
					}
				}
				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($type==$this->receipts_types['correct_sales'] || $type==$this->receipts_types['correct_return'] && $this->f3->get('GET.correct2')==1) {
			$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', '');
		if($res['success']==true && $type==$this->f3->get('receipt_correct_sales') || $type==$this->f3->get('receipt_correct_return')) {
			$res['reroute']='/receipts/search';
		}
		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);
		}
		if($post['no_egais']==1) {
			$this->f3->set('no_egais', true);
		}
		// Узнаем смену
		$change=$this->changes->get_change();
		// Узнаем сумму строк

		// Если была оплата баллами, то надо их вернуть
		$bonus_add=$post['bonus_add'];
		$post['bonus_add']=0;
		foreach ($post['receiptlines'] as $line_n=>$line) {
			if($line['bonus_pay']>0) {
				$post['bonus_add']+=$line['bonus_pay'];
				$post['receiptlines'][$line_n]['description']='Возвращено баллов: '.$line['bonus_pay'];
			}
			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['bonus_pay']=0;
		if($bonus_add>0) {
			$partners_model=new \Models\Partners($this->db, $this->f3);
			$partner=$partners_model->select_partner(array('partner_id=?', $post['partner_id']), array('limit'=>1));
			if($partner) {
				$partner_bonus=$partners_model->partners_bonus($partner[0], $lines_sum['lines'], $post['sum']);
				$post['bonus_pay']=$partner_bonus;
			}
		}
		//$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']) {
			// Добавляем строки
			if((int)$this->sets['spill']==1) {
				$taps=new \Models\Taps($this->db, $this->f3);
			}
			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;
				}

				// Проверяем наличие модификаторов
				/*$components=$this->receiptlines->select_lines(array('parent_id=?', $line['line_id']));
				if($components) {
					foreach($components as $component) {
						$lines_sum['lines'][]=$component;
						$this->receiptlines->add_line($res['id'], $component, $component['count'], $result['id'], $time, $time, $time);
						$lr=$this->receiptlines->change_mark_volume($component, 2);
					}
				}*/

				// Проверяем наличия разливного пива в чеке, чтобы изменить объем кега
				if((int)$this->sets['spill']==1) {
					if($line['pg']=='draftbeer') {
						$mark=json_decode($line['mark'], true)[0];
						$taps->change_current_volume($mark, -$line['count']);
					}
				}

				if($line['mark']!='') {
					$lr=$this->receiptlines->change_mark_volume($line, 2);
					/*if($lr['success'] && $lr['chpok']) {
						$this->auto_chpok($line['mark'], $change);
					}*/
				}
			}
			$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'];
		}
		if(!isset($receipt['certificates'])) {
			$c=new \Models\Certificates($this->db, $this->f3);
			$receipt['certificates']=$c->receipt_certificates($receipt['id']);
		}
		$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);
				}
			}
		}

		if($cancel===true) {
			$this->receiptlines->cancel_auto_add_loyalty($receipt);
		}

		$this->auto_add_loyalty($receipt);
	}

	function auto_add_loyalty($receipt) {
		$l=new \Models\Loyalty($this->db, $this->f3);
		$loyalty=$l->get_auto_add_loyalty($receipt);
		if($loyalty) $this->receiptlines->apply_auto_add_loyalty($receipt, $loyalty);
	}

	// Убрать клиента из чека
	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,
				'group_id'=>$this->sets['default_partnergroup'],
				'name'=>$get['client_name']==''?'Новый клиент':$get['client_name'],
				'card'=>$card,
				'discount'=>0,
				'email'=>'',
				'phone'=>$phone
			);
		}
		$receipt_id=$this->f3->get('COOKIE.receipt_id');
		$res=$this->model->add_partner($receipt_id, $partner[0]);
		$this->loyalty_receipt(true, $receipt_id);
		$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() {
		$get=$this->f3->get('GET');
		if($get['table_id']) {
			$this->f3->set('COOKIE.table_id', $get['table_id']);
		}
		$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() {
		$get=$this->f3->get('GET');
		$res=$this->model->all_open($get['table_id']);
		$receipts=$res['receipts'];
		if($this->sets['multikassa']==1) {
			$res=$this->multi_curl($this->sets['other_cashboxes_ip'], '/multikassa/all_open?table_id='.$get['table_id'], $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', time()-3600*24*$this->sets['orders_day']).' - '.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, id'));
		$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';
		}
		if((int)$this->f3->get('GET.copy')==1) {
			$res=$this->model->print_copy_receipt($id);
		}
		else {
			$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 auto_chpok($mark, $change) {
		// Найдем товар по марке
		$mark=json_decode($mark, true)[0];
		$product=$this->receiptlines->search_mark($mark);
		if(!$product['success']) {
			return $product;
		}
		$sum=$product['data']['price'];
		if($product['data']['vat_type']==1) {
			$sum+=$product['data']['price']/100*$product['data']['vat'];
		}
		$res=$this->model->ticket_chpok($this->api_data['rm_id'], $this->api_data['store_id'], $change, $sum);
		if($res['success']) {
			$receipt=$res['receipt'];
			$receipt_id=$res['id'];
			// Добавляем строки
			$product['data']['mark']=json_encode(array($mark));
			$product['data']['description']='Вскрытие тары';
			$product['data']['price']=$sum;
			$res=$this->receiptlines->add_line($receipt_id, $product['data'], 1);
			if($res['success']) {
				$res=$this->model->ticket_chpok_ready($receipt, $product['data']);
				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);
			}
		}
		return $res;
	}

	// Окно вкрытия бутылки
	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 {
					// пытаемся найти по марке
					/*$mark=$this->receiptlines->search_mark($barcode);
					if($mark['success']===true) {
						$product_id=$mark['data']['id'];
						$this->f3->set('mark', $mark['data']['mark']);
					}*/
					$products=array(
						'success'=>false,
						'count'=>0,
						'products'=>array()
					);
				}
			}
			else {
				// пытаемся найти по марке
				/*$mark=$this->receiptlines->search_mark($barcode);
				if($mark['success']===true) {
					$product_id=$mark['data']['id'];
					$this->f3->set('mark', $mark['data']['mark']);
				}*/
				$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('bottles', $this->receiptlines->close_bottles($products['products'][0]['id']));
			$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');
		if(!$this->products->barcode_validate($post['barcode'])) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('barcode_not_correct')['txt']
			);
			echo json_encode($res);
			exit();
		}
		$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'] && (int)$this->sets['egais_chpok_mode']==2) {
			$this->f3->set('page_data', $this->messages->message('incorrect_price_with_buy_price'));
			return;
		}

		$mark=$this->receiptlines->search_mark($post['code']);

		if(!$mark['success'] && !$post['not_check_mark']) {
			$this->f3->set('mark_code', $post['code']);
			$this->f3->set('txt', $this->messages->message($mark['txt'])['txt']);
			$this->f3->set('page_data', $this->model->page_data('chpok_egais_error'));
			return;
		}

		if(((int)$mark['data']['chpok']==1 || $mark['data']['current_volume']<$mark['data']['capacity']*1000) && !$post['not_check_mark']) {
			$this->f3->set('mark_code', $post['code']);
			$this->f3->set('txt', $this->messages->message('bottle_open')['txt']);
			$this->f3->set('page_data', $this->model->page_data('chpok_egais_error'));
			return;
		}

		if($mark['data']['id']!=$post['product_id'] && !$post['not_check_mark']) {
			$this->f3->set('mark_code', $post['code']);
			$this->f3->set('txt', $this->messages->message('mark_from_other_product')['txt']);
			$this->f3->set('page_data', $this->model->page_data('chpok_egais_error'));
			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($mark['data']['mark']);
			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($mark['data']['mark']));
			$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'] || $receipt[0]['type']==$this->receipts_types['correct_sales']) {
			$type=$this->receipts_types['correct_return'];
		}
		elseif($receipt[0]['type']==$this->receipts_types['return'] || $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'];
		$receipt[0]['synch']=0;

		$change=$this->changes->get_change();
		$receiptlines=$this->receiptlines->select_lines(array('receipt_id=?', $receipt[0]['id']));
		$lines_sum=$this->receiptlines->get_sum($receiptlines);
		$lines2=$lines_sum['lines'];

		$bonus_add=$receipt[0]['bonus_add'];
		$bonus_pay=$receipt[0]['bonus_pay'];
		$receipt[0]['bonus_add']=$bonus_pay;
		$receipt[0]['bonus_pay']=$bonus_add;
		foreach ($lines_sum['lines'] as $line_n=>$line) {
			if($line['writeoff_bonus']>0) {
				$receipt[0]['writeoff_bonus']=0;
				$lines_sum['lines'][$line_n]['description']='Возвращено баллов: '.$line['bonus_pay'];
				$lines2[$line_n]['price']=$lines2[$line_n]['price0'];
				$lines2[$line_n]['description']='';
				$lines2[$line_n]['writeoff_bonus']=0;
			}
		}

		$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) {
			$parent_id=0;
			foreach($receiptlines as $n=>$l) {
				$l['id']=$l['product_id'];
				if($l['parent_id']>0) $l['parent_id']=$parent_id;
				else $l['parent_id']=0;
				$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;
				}
				if($l['parent_id']==0) $parent_id=$line_res['id'];
				//$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'];
		}
		$receipt[0]['synch']=0;
		$receipt[0]['bonus_pay']=$bonus_pay;
		$receipt[0]['bonus_add']=0;
		$res=$this->model->add_correct($receipt[0], $lines2, $type, $change, false);
		if($lines2) {
			$parent_id=0;
			foreach($lines2 as $n=>$l) {
				$l['id']=$l['product_id'];
				if($l['parent_id']>0) $l['parent_id']=$parent_id;
				else $l['parent_id']=0;
				$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;
				}
				if($l['parent_id']==0) $parent_id=$line_res['id'];
			}
		}
		$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';
		$val=array($id);
		$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->f3->set('correct2', 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($get['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() {
		$get=$this->f3->get('GET');
		$id=$get['id'];
		if(!$id && isset($get['line_id'])) {
			$id=$get['line_id'];
		}
		$ip=$get['ip'];
		$issued=(int)$get['issued'];
		if(isset($get['order_display']) && $get['order_display']==0) {
			$line=$this->receiptlines->select_lines(array('id=?', $id), array('limit'=>1));
			if($line[0]['complite_order']>0) {
				// Если уже выдано, значит отменяем выдачу
				if($ip) {
					$res=$this->model->other_order_line_cancel_complite($ip, $id, $issued);
				}
				else {
					$res=$this->model->order_line_cancel_complite($id, $issued);
				}
				$res['txt']=$this->messages->message($res['txt'])['txt'];
				echo json_encode($res);
				exit();
			}
			if($line[0]['create_order']==0) {
				if($line[0]['print_group']) {
					$this->receiptlines->print_ok($id, $line[0]['print_group']);
				}
				else {
					$this->receiptlines->load(array('id=?', $id), array('limit'=>1));
					if($this->receiptlines->create_order==0) {
						$this->receiptlines->create_order=microtime(true);
						$this->receiptlines->update();
					}
				}
			}
		}
		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'];
		if(isset($get['order_display']) && $get['order_display']==0) {
			unset($res['function']);
			$res['reload']=array('.receiptlines', '#receipts_buttons');
			$res['id']=$id;
			$res['scroll']=".receiptlines_div";
			$res['scrollto']="#line_".$id;
		}
		echo json_encode($res);
		exit();
	}

	function issued_order() {
		$get=$this->f3->get('GET');
		if($get['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->receipts_types['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 cancel_qr() {
		$res=$this->model->cancel_qr($this->f3->get('GET'));
		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;
		if(!$post['combo_step'])$post['combo_step']=0;
		$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) {
				if($n!=$post['combo_step']) continue;
				$prod=$products[$item['product_id']];
				if($prod['marking']==1 && (!isset($item['mark']) || $item['mark']=='')) {
					$this->f3->set('GET.product_id', $prod['id']);
					$this->f3->set('REQUEST.combo_step', $n);
					$this->f3->set('combo_return', true);
					$this->f3->clear('GET.mark');
					$res=$this->add_line();
					if(!is_array($res)) return;
				}
				$post['combo_step']=$n;
			}
			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']=$item['price']-($item['price']/(100+$prod['vat'])*$prod['vat']);
				}
				else {
					$prod['price']=$item['price'];
				}
				$prod['combo_id']=$combo_id;
				if(isset($item['mark_data'])) {
					$prod['reqTimestamp']=$item['mark_data']['reqTimestamp'];
					$prod['mark']=json_encode(array($item['mark_data']['mark']));
					$prod['reqId']=$item['mark_data']['mark_reqId'];
				}
				$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'));

		if($post['print_type']=='linesset') {
			$marking=array_column($receiptlines, 'marking');
			$marking=array_sum($marking);
		}
		else {
			$marking=0;
		}
		if($marking>0) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('not_marking_in_lineset')['txt']
			);
			foreach($receiptlines as $line) {
				if($line['marking']==0) continue;
				$res['txt'].='<br>'.$line['product_title'];
			}
		}
		else {
			$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'=>$this->messages->message('not_enough_data')['txt']
			);
		}

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

	function salesreport() {
		$get=$this->f3->get('GET');
		if(!$get['change_id']) {
			$change=$this->changes->select_changes(null, array('limit'=>1, 'order'=>'id DESC'));
		}
		else {
			$change=$this->changes->select_changes(array('id=?', array($get['change_id'])), array('limit'=>1));
		}
		if(empty($change)) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		$this->f3->set('change', $change[0]);

		$lines=$this->model->salesreport($change[0]['id']);
		$this->f3->set('lines', $lines);
		$this->f3->set('page_data', $this->model->page_data('salesreport'));
		if($get['print']) {
			$res=$this->model->salesreport_print($lines);
			echo json_encode($res);
			exit();
		}
	}

	// Добавление марки в коктейль
	function post_add_cocktail_line() {
		$post=$this->f3->get('POST');
		$new_line=array(
			'product_id'=>0,
			'count'=>0,
			'mark'=>$post['mark'],
			'title'=>''
		);

		// Находим коктейль, который надо приготовить
		$product=$this->products->select_product(array('p.id=? AND p.cocktail!=""', $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($product[0]['stop'] && !$post['receipttype']!=$this->receipts_types['print'] && !$post['receipttype']!=$this->receipts_types['return'] && !$post['receipttype']!=$this->receipts_types['correct_sales'] && !$post['receipttype']!=$this->receipts_types['correct_return'] && !$post['receipttype']!=$this->receipts_types['writeoff']) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('product_stoped')['txt']
			);
			echo json_encode($res);
			exit();
		}

		// Узнаем сколько уже добавили
		$add_product=array();
		$count=0; // Кол-во по добавляемой марке, на случай если данной продукции не хватало, а марку добавляют повторно

		if($post['positions']) {
			foreach($post['positions'] as $position) {
				$add_product[$position['product_id']]+=$position['count'];
				if($position['mark']==$post['mark']) {
					$count+=$position['count'];
				}
			}
		}
		else {
			$post['positions']=array();
		}

		if($post['mark']) {
			// Находим продукции по марке
			$mark_data=$this->receiptlines->search_mark($post['mark']);
			if(!$mark_data['success']) {
				$mark_data['txt']=$this->messages->message($mark_data['txt'])['txt'];
				echo json_encode($mark_data);
				exit();
			}
			if($mark_data['data']['cocktail'] && (int)$mark_data['data']['egais']==1) {
				$components=json_decode($mark_data['data']['cocktail'], true);
				$new_line['product_id']=$components[0]['product_id'];
				$new_product=$mark_data['data'];
			}
			else {
				$new_line['product_id']=$mark_data['data']['id'];
				$new_product=$this->products->select_product(array('p.id=?', $new_line['product_id']), array('limit'=>1));
				if(!$new_product) {
					$res=array(
						'success'=>false,
						'txt'=>$this->messages->message('not_found')['txt']
					);
					echo json_encode($res);
					exit();
				}
				$new_product=$new_product[0];
			}
		}

		// Узнаем сколько и чего надо для коктейля
		$components=$product[0]['components'];
		$components=array_combine(array_column($components, 'product_id'), $components);
		if($post['mark'] && !$components[$new_line['product_id']]) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('mark_not_use')['txt']
			);
			echo json_encode($res);
			exit();
		}

		if($post['mark']) {
			// Необходимый объем (сколько надо - сколько добавили)
			$need_volume=$components[$new_line['product_id']]['quantity']-($add_product[$new_line['product_id']]??0);

			if($need_volume<=0) {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('no_longer_required')['txt']
				);
				echo json_encode($res);
				exit();
			}

			// Узнаем текущий объем марки с учетом открытых чеков
			$current=$this->receiptlines->check_egais_mark($post['mark'], $count, $new_product, 1);
			if(!$current['success']) {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message($current['txt'])['txt']
				);
				echo json_encode($res);
				exit();
			}
			$current_volume=$current['current_volume'];

			// Проверяем сколько в наличии и добавляем сколько надо или можем
			if($current_volume<$need_volume) {
				$new_line['count']=$current_volume;
			}
			else {
				$new_line['count']=$need_volume;
			}

			if($new_line['count']<=0) {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('no_required_amount')['txt']
				);
				echo json_encode($res);
				exit();
			}

			$post['positions'][]=$new_line;

			// Проверяем надо ли еще что-то добавлять
			$add_product[$new_line['product_id']]+=$new_line['count'];
			foreach($components as $component) {
				if($component['quantity']==$add_product[$component['product_id']]) {
					unset($components[$component['product_id']]);
				}
			}

			if(count($components)==0) {
				//$open_receipt=$this->model->get_open_receipt($this->receipt_sets, true, (int) $this->sets['view_all_receipts']);
				$receipt_id=$this->f3->get('COOKIE.receipt_id');
				$open_receipt=$this->model->select_receipts(array('r.id=?', $receipt_id), array('limit'=>1));
				// Если все добавлено, нужно добавить все в чек
				// Сначала нужно добавит сам коктейль, а затем ингридиенты, как модификаторы
				$result=$this->receiptlines->add_line($receipt_id, $product[0], 1, 0);
				if($result['success']) {
					$this->cd->print_line($result['line'], 1);
					$this->loyalty($open_receipt[0], $product[0]);
					foreach($post['positions'] as $position) {
						$product=$this->products->select_product(array('p.id=?', $position['product_id']), array('limit'=>1));
						$product[0]['mark']=json_encode(array($position['mark']));
						$product[0]['price']=0;
						$this->receiptlines->add_line($receipt_id, $product[0], $position['count'], $result['id']);
					}
				}

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

		$add_product=array();
		foreach($post['positions'] as $position) {
			$add_product[$position['product_id']]['count']+=$position['count'];
			$add_product[$position['product_id']]['marks'][]=$position;
		}

		$this->f3->set('add_product', $add_product);
		$this->f3->set('product', $product[0]);
		$this->f3->set('add_marks', array_column($post['positions'], 'mark'));
		$this->f3->set('bottles', $this->receiptlines->open_bottles($components));
		$this->f3->set('positions', $post['positions']);
		$this->f3->set('page_data', $this->model->page_data('add_cocktail_line'));
	}

	function certificates() {
		$receipt=$this->model->get_open_receipt($this->receipt_sets, false);
		$this->f3->set('receipt', $receipt['receipt']);
		$this->f3->set('page_data', $this->model->page_data('certificates'));
	}

	// Форма добавления сертификата в чек
	function add_certificate() {
		$this->f3->set('page_data', $this->model->page_data('add_certificate2receipt'));
	}

	// Добавление сертификата в чек
	function post_add_certificate() {
		$post=$this->f3->get('POST');
		$receipt=$this->model->get_open_receipt($this->receipt_sets, false);

		// Если указано только номер, то ищем сертификаты в Агорте, чтобы узнать что за сертификат
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);

		if(!isset($post['product_id'])) {
			$res=$api->getcertificate($post['certificate']);
			if(!$res['success']) {
				$res['txt']=$this->messages->message($res['txt'])['txt'];
				echo json_encode($res);
				exit();
			}

			if(empty($res['certificates'])) {
				$res=array(
					'success'=>false,
					'txt'=>$this->messages->message('certificate_not_found')['txt']
				);
				echo json_encode($res);
				exit();
			}
			if(count($res['certificates'])>1) {
				$product_id=array_column($res['certificates'], 'product_id');
				$products=$this->products->select_product(array('p.id IN ('.implode(', ', $product_id).')'));
				$products=array_combine(array_column($products, 'id'), $products);
				$this->f3->set('products', $products);
				$this->f3->set('certificates', $res['certificates']);
				$this->f3->set('page_data', $this->model->page_data('select_certificate'));
				return;
			}

			$post['product_id']=$res['certificates'][0]['product_id'];
		}

		if(!$this->model->check_double_certificate($post)) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('double_certificate_receipt')['txt']
			);
			echo json_encode($res);
			exit();
		}

		// Если указан что за сертификат, или был найден только один, то добавляем его в чек и указываем Агорте об этом
		$res=$api->addcertificate($post);
		if(!$res['success']) {
			echo json_encode($res);
			exit();
		}
		$data=array(
			'receipt_id'=>$receipt['receipt']['id'],
			'certificate'=>$post['certificate'],
			'product_id'=>$post['product_id']
		);
		$res=$this->model->addcertificate($data);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		if($res['success']==true) {
			$this->loyalty_receipt(true, $receipt['receipt']['id']);
			$res['reload']=array('.receiptlines', '#receipts_buttons');
			$res['reload_menu']=true;
			$res['close_all_window']=true;
		}
		echo json_encode($res);
		exit();
	}

	function remove_certificate() {
		$get=$this->f3->get('GET');
		$res=$this->model->remove_certificate($get);
		$this->loyalty_receipt(true, $receipt['receipt']['id']);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		$res['reload']=array('.receiptlines', '#receipts_buttons', '.certificates_list');
		$res['function']='close_window("#message")';

		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		$api->removecertificate($get);
		
		echo json_encode($res);
		exit();
	}

	// Объединение чеков
	function post_merge() {
		$post=$this->f3->get('POST');
		$res=$this->model->merge($post['receipt']);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	function printdoc() {
		$get=$this->f3->get('GET');
		$receipt=$this->model->select_receipts(array('r.id=?', $get['id']), array('limit'=>1));
		if(!$receipt) {
			$this->f3->set('page_data', $this->messages->message('not_found'));
			return;
		}
		if($receipt[0]['synch']!=1) {
			$this->f3->set('page_data', $this->messages->message('receipt_not_synch'));
			return;
		}
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		$tmp=$api->getprinttempaletes($receipt[0]);
		if(!$tmp['success']) {
			$this->f3->set('error', $tmp['txt'][0]);
			$this->f3->set('page_data', $this->model->page_data('printdoc'));
			return;
		}
		$this->f3->set('receipt_type', $tmp['receipt_type']);
		$this->f3->set('tmps', $tmp['data']);
		$this->f3->set('page_data', $this->model->page_data('printdoc'));
	}

	function pdf() {
		$api=new \Models\Api($this->f3, $this->api_data['domen'], $this->api_data['pass'], $this->api_data['store_id'], $this->api_data['count']);
		header('Content-Type: application/pdf');
		echo $api->pdf($this->f3->get('GET.url'));
		exit();
	}

	function checkepay() {
		$this->model->reset();
		$this->model->load(array('id=?', $this->f3->get('COOKIE.receipt_id')), array('limit'=>1));
		if($this->model->dry() || $this->model->slip=='') {
			$res=array(
				'success'=>false
			);
		}
		else {
			$res=array(
				'success'=>true,
				'slip'=>$this->model->slip
			);
		}
		echo json_encode($res);
		exit();
	}
}
