<?php
namespace Models;

// Модель кранов
class Taps extends \DB\SQL\Mapper {
	public $db, $f3, $products;

	public function __construct($db, $f3) {
		parent::__construct($db, 'taps' ); // подключаемся к таблице
		$this->db=$db;
		$this->f3=$f3;
		$this->sets=$this->f3->get('base_settings');
	}

	// Информация об открываемой странице
	function page_data($page='list') {
		$pages=array(
			'list'=>array(
				'title'=>'Краны',
				'inc'=>'taps_list.htm'
			),
			'add'=>array(
				'title'=>'Добавить кран',
				'inc'=>'taps_form.htm'
			),
			'change'=>array(
				'title'=>'Редактировать кран',
				'inc'=>'taps_form.htm'
			),
			'tap'=>array(
				'title'=>'Кран',
				'inc'=>'taps_tap.htm'
			),
			'connection'=>array(
				'title'=>'Подключение к крану',
				'inc'=>'taps_connection.htm'
			),
			'move'=>array(
				'title'=>'Перемещение на другой кран',
				'inc'=>'taps_move.htm'
			),
			'tap_marking_error'=>array(
				'title'=>'Ошибка проверки марки',
				'inc'=>'taps_marking_error.htm'
			),
			'product_add'=>array(
				'title'=>'Добавить номенклатуру',
				'inc'=>'taps_product_add.htm'
			),
			'connection_select_product'=>array(
				'title'=>'Выбрать номенклатуру',
				'inc'=>'taps_connection_select_product.htm'
			),
		);
		$pages[$page]['page']=$page;
		return $pages[$page];
	}

	// Выбор из базы
	function select_taps($query=null, $options=null) {
		$this->reset();
		if(!isset($options['order'])) {
			$options['order']='title';
		}
		$this->load($query, $options);
		$taps=array();
		if(!$this->dry()) {
			do {
				$t=$this->cast();
				$t['products']=$this->db->exec("SELECT p.* FROM products AS p JOIN tapsproducts AS tp ON tp.tap_id=? AND tp.product_id=p.id WHERE p.date_delete=0", $t['id']);
				$t['expiration_date']=$t['connection_time']+3600*24*$t['expiration'];
				$t['current_volume_with_lines']=$t['current_volume'];
				$lines_volume=$this->db->exec("SELECT SUM(count) AS count FROM receiptlines WHERE create_order=0 AND mark=?", json_encode(array($t['mark'])));
				if($lines_volume) {
					$t['current_volume_with_lines']-=$lines_volume[0]['count'];
				}
				$taps[]=$t;
			}
			while ($this->skip());
		}
		return $taps;
	}

	// Ищем кран для товара
	function get_tap($product_id, $mark='') {
		$mark=str_replace('', '\u001d', $mark);
		$mark=str_replace($this->sets['gs1_symbols'], '\u001d', $mark);
		$sql="SELECT t.* FROM taps AS t JOIN tapsproducts AS tp ON tp.product_id=? AND tp.tap_id=t.id WHERE t.connection=1 ";
		$val=array($product_id);
		if($mark!='') {
			$sql.=" AND t.mark=?";
			$val[]=$mark;
		}
		$sql.=" ORDER BY id";
		$taps=array();
		$res=$this->db->exec($sql, $val);
		if($res) {
			foreach($res as $t) {
				$taps[]=$this->select_taps(array('id=?', $t['id']), array('limit'=>1))[0];
			}
		}
		return $taps;
	}

	// Сохранение крана
	function save_tap($data) {
		$this->reset();
		if(!isset($data['title']) || $data['title']=='') {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$data['mark']=str_replace('', '\u001d', $data['mark']);
		$data['mark']=str_replace($this->sets['gs1_symbols'], '\u001d', $data['mark']);
		if(isset($data['id']) && $data['id']>0) {
			$this->load(array('id=?', $data['id']), array('limit'=>1));
			if($this->dry()) {
				return array(
					'success'=>false,
					'txt'=>'not_found'
				);
			}
			if($this->count(array('mark=? AND id!=?', array($data['mark'], $data['id'])))>0) {
				return array(
					'success'=>false,
					'txt'=>'keg_is_connection'
				);
			}
		}
		else {
			if($this->count(array('title=?', $data['title']))>0) {
				return array(
					'success'=>false,
					'txt'=>'tap_is_exists'
				);
			}
		}
		$this->copyFrom($data);
		if($this->save()===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'reload'=>array('.taps_list', '.tap_'.($data['id']??0)),
			'close_window'=>array('form[name="taps_form"]', 'form[name="tap_connection_form"]', '#tap_error_page', '#message')
		);
	}

	// Удаление крана
	function delete_tap($id) {
		$this->reset();
		$this->load(array('id=?', $id), array('limit'=>1));
		if($this->dry()) {
			return array(
				'success'=>false,
				'txt'=>'not_found'
			);
		}

		if($this->erase()===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}
		$this->db->exec("DELETE FROM tapsproducts WHERE tap_id=?", $id);
		return array(
			'success'=>true,
			'txt'=>'delete_successful',
			'reload'=>array('.taps_list'),
			'close_window'=>array('.tap_'.$id, '#message')
		);
	}

	// Добавляем товар к крану
	function product_add($data) {
		$res=$this->db->exec("INSERT OR REPLACE INTO tapsproducts (tap_id, product_id) VALUES (?, ?)", array($data['tap_id'], $data['product_id']));
		if($res===false) {
			return array(
				'success'=>false,
				'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'reload'=>array('.taps_list', '.tap_'.($data['tap_id']??0)),
			'close_window'=>array('form[name="tap_product_add_form"]', '#message')
		);
	}

	function product_delete($data) {
		if(!$data['tap_id'] || !$data['product_id']) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$res=$this->db->exec("DELETE FROM tapsproducts WHERE tap_id=? AND product_id=?", array($data['tap_id'], $data['product_id']));
		if($res===false) {
			return array(
				'success'=>false,
				'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'delete_successful',
			'reload'=>array('.taps_list', '.tap_'.($data['tap_id']??0)),
			'close_window'=>array('#message')
		);
	}

	function unconnection($data) {
		$this->reset();
		$this->load(array('id=?', $data['id']), array('limit'=>1));
		if($this->dry()) {
			return array(
				'success'=>false,
				'txt'=>'not_found'
			);
		}
		$this->connection=0;
		$this->mark=mb_substr($this->mark, 0, 16);
		if($this->update()===false) {
			return array(
				'success'=>false,
				'db_error'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'reload'=>array('.taps_list', '.tap_'.($data['id']??0)),
			'close_window'=>array('#message')
		);
	}

	function change_current_volume($mark, $count) {
		$mark=str_replace('', '\u001d', $mark);
		$mark=str_replace($this->sets['gs1_symbols'], '\u001d', $mark);
		$this->reset();
		$this->load(array('mark=?', $mark), array('limit'=>1));
		if($this->dry()) return;
		$this->current_volume-=$count;
		$this->update();
	}

	function move($data) {
		$this->reset();
		$this->load(array('id=?', $data['from']), array('limit'=>1));
		if($this->dry()) {
			return array(
				'success'=>false,
				'txt'=>'not_found'
			);
		}
		$from=$this->cast();
		unset($from['id'], $from['title']);
		$this->reset();
		$this->load(array('id=?', $data['to']), array('limit'=>1));
		if($this->dry()) {
			return array(
				'success'=>false,
				'txt'=>'not_found'
			);
		}
		$this->copyFrom($from);
		if($this->update()===false) {
			return array(
				'success'=>false,
				'db_error'
			);
		}
		$products=$this->db->exec("SELECT * FROM tapsproducts WHERE tap_id=?", $data['from']);
		if($products) {
			foreach($products as $product) {
				$this->product_add(array('tap_id'=>$data['to'], 'product_id'=>$product['product_id']));
			}
		}

		$this->unconnection(array('id'=>$data['from']));
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'reload'=>array('.taps_list', '.tap_'.($data['tap_id']??0)),
			'close_window'=>array('#message', '.tap_'.$data['from'], 'form[name="taps_move_form"]')
		);
	}

	function check_mark_connection($mark) {
		$lines=$this->db->exec("SELECT id FROM receiptlines WHERE mark=? LIMIT 1", json_encode(array($mark)));
		if(empty($lines)) {
			return true;
		}
		return false;
	}
}
