<?php
namespace Models;

class Linesset extends \DB\SQL\Mapper {
	public $db, $f3;

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

	function page_data($page='sales') {
		$pages=array(
			'list'=>array(
				'title'=>'Готовые наборы',
				'inc'=>'linesset_list.htm'
			),
			'show'=>array(
				'title'=>'Просмотр набора',
				'inc'=>'linesset_show.htm'
			),
		);
		$pages[$page]['page']=$page;
		return $pages[$page];
	}

	function lines_sum($lines) {
		$sum=0;
	}

	function select_linesset($query=null, $options=null) {
		$linesset=array();
		$this->load($query, $options);
		if($this->dry()) {
			return $linesset;
		}
		do {
			$l=$this->cast();
			$l['lines']=json_decode($l['txt'], true);
			$linesset[]=$l;
		}
		while($this->skip());
		$this->reset();
		return $linesset;
	}

	function get_control($code) {
		$n=mb_strlen($code);
		$sum[0]=0;
		$sum[1]=0;
		for($i=0; $i<$n; $i++) {
			$sum[$i%2]+=$code[$i];
		}
		$sum[1]*=3;
		$summ=$sum[0]+$sum[1];
		$control=10-($summ-floor($summ/10)*10);
		if($control==10) $control=0;
		return $control;
	}

	function save_linesset($txt, $id=0, $title='') {
		$this->reset();
		if($id>0) {
			$this->load(array('id=?', $id), array('limit'=>1));
		}
		else {
			$this->load(array('txt=?', $txt), array('limit'=>1));
		}

		$this->txt=$txt;
		$this->title=$title;
		if($this->save()===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}

		if(!$id) {
			$id=$this->get('_id');
			$barcode=$this->f3->get('linesset_pr').sprintf("%'010d", $id);
			$barcode.=$this->get_control($barcode);
			$this->barcode=$barcode;
			if($this->update()===false) {
				return array(
					'success'=>false,
					'txt'=>'db_error'
				);
			}
		}

		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'id'=>$id,
			'reload'=>array('.receiptlines'),
			'barcode'=>$this->barcode
		);
	}

	function delete($id) {
		$this->reset();
		if(!$id) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$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'
			);
		}
		return array(
			'success'=>true,
			'txt'=>'delete_successful',
			'close_all_window'=>true,
			'reload'=>array('.linelist'),
		);
	}
}
