<?php
namespace Controllers;
// Контроллер Смены
class Changes extends Controller {

	public function __construct($model=false) {
		parent::__construct();
		if(!$model || !method_exists($model, 'open_fr')) {
			$this->model=new \Models\Changes($this->db, $this->f3); // модель пользовательских групп
		}
		else {
			$this->model=$model;
		}
	}

	// Открываем смену
	function open($exit=true) {
		$res=$this->model->get_change();
		if($res) {
			$result=array(
				'success'=>true,
				'reload'=>'.reports',
				'close_all_window'=>true,
				'txt'=>$this->messages->message('change_is_open')['txt']
			);
			if($res['chz_error']!='') {
				$result['txt']=$this->messages->message($res['chz_error'])['txt'];
				if($res['chz_status']!='') {
					$result['txt']=str_replace('@status', $res['chz_status'], $result['txt']);
				}
				$result['chz_error']=true;
				unset($result['close_all_window']);
			}
		}
		else {
			$result=array(
				'success'=>false,
				'txt'=>$this->messages->message('change_not_open')['txt']
			);
		}
		if(!$exit) {
			return $result;
		}
		echo json_encode($result);
		exit();
	}

	// Открытие смены на ФР
	function open_fr() {
		$res=$this->model->open_fr();
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Открытие смены на Кассе
	function open_db() {
		//$res=$this->model->open_db();
		$res=$this->model->get_change(true, false);
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Закрытие смены на ФР
	function close_fr() {
		$res=$this->model->close_fr();
		$res['txt']=$this->messages->message($res['txt'])['txt'];
		echo json_encode($res);
		exit();
	}

	// Закрытие смены на Кассе
	function close_db() {
		$res=$this->z(false, false);
		/*$change=$this->model->get_change(false);
		if($change) {
			$res=$this->model->z($change, false);
			$res['txt']=$this->messages->message($res['txt'])['txt'];
		}
		else {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('change_not_open')['txt']
			);
			echo json_encode($res);
			exit();
		}*/
		unset($res['close_all_window']);
		echo json_encode($res);
		exit();
	}

	// Поиск смен
	function search() {
		$page=$this->f3->get('GET.page');
		if(!$page)$page=1;
		$dates=$this->f3->get('GET.dates');
		if($dates) {
			$dates=str_replace(' ', '', $dates);
			$dates=explode('-', $dates);
			$dates[0]=strtotime($dates[0]);
			$dates[1]=strtotime($dates[1])+24*3600;
		}
		$limit=$this->f3->get('lines_of_page');
		$changes=$this->model->search($dates, ($page-1)*$limit, $limit);
		if(!empty($changes)) {
			$this->f3->set('changes', $changes['changes']);
			$this->f3->set('pagination', $this->pagination($changes['count'], $page));
			$this->f3->set('page_data', $this->model->page_data('search'));
		}
		else {
			$this->f3->set('page_data', $this->messages->message('not_found'));
		}
	}

	// Закрываем смену
	function z($exit=true, $fr=true, $service=false, $ignore_openpay_tickets=false) {
		if(!is_bool($exit)) $exit=true;
		if(!is_bool($service)) $service=false;
		if(!is_bool($fr)) $fr=true;
		if(!is_bool($ignore_openpay_tickets)) $ignore_openpay_tickets=false;
		$change=$this->model->get_change(false);
		if(!$change) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('change_not_open')['txt']
			);
			if(!$exit) {
				return $res;
			}
			echo json_encode($res);
			exit();
		}

		$r=new \Models\Receipts($this->db, $this->f3, null, $this->model->fr);
		if($ignore_openpay_tickets==false && $r->count(array('time=0 AND slip!="" AND type IN (?, ?, ?, ?)', array($this->f3->get('receipt_sales'), $this->f3->get('receipt_return'), $this->f3->get('receipt_correct_sales'), $this->f3->get('receipt_correct_return'))))) {
			$res=array(
				'success'=>false,
				'txt'=>$this->messages->message('close_all_receipts')['txt']
			);
			if(!$exit) {
				return $res;
			}
			echo json_encode($res);
			exit();
		}
		$close=$this->f3->get('close_all_receipts');
		if(!$exit || $service) {
			$close=1;
		}
		if($close!=1) {
			$open_receitps=$r->get_not_empty($this->api_data['rm_id'], $this->api_data['store_id']);
			if($open_receitps>0) {
				$this->f3->reroute('/changes/close_alert');
				exit();
			}
		}

		if($exit) {
			$res=$r->delete_open($this->api_data['rm_id'], $this->api_data['store_id']);
		}
		else {
			$res['success']=true;
		}
		if($res['success']) {
			$deleted=$res['deleted']; // Удаленные строки в удаляемых чеках
			$p=new \Models\Paymentmethods($this->db, $this->f3);
			$report=$r->change_statistic($change['id']); // Отчет по чекам за смену
			$cash=$p->cash_in_box($report); // Узнаем наличность по чекам
			$cash+=$change['cash_start'];
			// Если включена автоинкассация, то сначала нужно изъять деньги из кассы и в кассе есть деньги
			if($this->model->fr->sets['auto_incassation']>0 && $cash>0) {
				if($this->model->fr->sets['auto_incassation']==2) {
					$print_type=0;
				}
				else {
					$print_type=1;
				}
				$pay=$p->select_method('cash=1');
				$res=$r->cashin($this->api_data, $change, $pay[0]['id'], -$cash, $this->f3->get('receipt_cashout'), $this->f3->get('receipt_pko'), 'Закрытие смены '.$change['id'].' '.date("d.m.Y H:i"), $print_type);
				if(!$res['success']) {
					$res['txt']=$this->messages->message($res['txt'])['txt'];
					if(!$exit) {
						return $res;
					}
					echo json_encode($res);
					exit();
				}
				$change['cash_end']=0;
				$report[$this->f3->get('receipt_cashout')]['sum']-=$cash;
				$report[$this->f3->get('receipt_cashout')]['pay'][1]-=$cash;
				$report[$this->f3->get('receipt_cashout')]['count']+=1;
			}
			else {
				$change['cash_end']=$cash;
			}

			$paymentmethod=$p->select_method('cash=1')[0]['id'];
			$change['change_end']=time();
			$change['report']=$report;
			$change['time']=0;
			$res=$r->ticket_change($this->api_data, $change, $this->f3->get('receipt_change_close'), $paymentmethod, 0, '', $deleted);
			if(!$res['success']) {
				$res['txt']=$this->messages->message($res['txt'])['txt'];
				echo json_encode($res);
				exit();
			}
			$change['receipt_id']=$res['id'];
			$change['slip']=$res['slip'];

			if($service) $bt=false;
			else $bt=true;
			$res=$this->model->z($change, $fr, $bt);
			if($res['success']) {
				$res['reload']='.reports';
				$res['close_all_window']=true;
				$res['change']['time']=microtime(true);
				$r->ticket_change($this->api_data, $res['change'], $this->f3->get('receipt_change_close'), $paymentmethod, 0);
			}
		}
		$res['txt']=$this->messages->message($res['txt'])['txt'];

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

	// Запрос на закрытие при открытых не пустых чеках
	function close_alert() {
		$close=$this->f3->get('GET.close');
		// Если запрос на закрытие получен
		if($close==1) {
			$this->f3->set('close_all_receipts', 1);
			$this->z();
		}
		else {
			$this->f3->set('page_data', $this->model->page_data('close_alert'));
		}
	}

	// X-отчет
	function x() {
		$res=$this->model->x();
		$this->f3->set('page_data', $this->messages->message($res['txt']));
	}
}
