<?php
namespace Models;

// Модель для работы с весами
class Scales extends \DB\SQL\Mapper{
	public $scales, $db, $f3, $sets, $method='POST', $messages, $api_data;

	public function __construct($db, $f3) {
		$this->api_data=$f3->get('api_data');
		if($f3->get('GET.scales_unset')) {
			$sql="UPDATE scales_settings SET value='0' WHERE name='active' AND rm=?";
			$db->exec($sql, $this->api_data['rm_id']);
			return;
		}
		parent::__construct($db, 'scales_settings' ); // подключаемся к таблице с настройками
		$this->f3=$f3;
		$this->db=$db;
		$this->messages=new \Models\Messages();
		$this->sets=$this->get_scales();
		if(!$this->sets['active']) return;
		if($this->sets['driver']!='') {
			if(file_exists($this->sets['driver'].'/server.php')) {
				$s=new \Models\Settings($this->f3, $this->db);
				$config=$s->get_driver_config($this->sets['driver'], 'scale', 0);
				$config=$config['config'];

				require_once($this->sets['driver'].'/server.php');
				$this->scales=new Scales_php($f3, $this->sets, $config);
			}
			else {
				echo 'Ошибка';
			}
		}
	}

	// Узнаем настройки весов
	function get_scales() {
		$settings=array();
		$this->reset();
		$this->load(array('rm=?', $this->api_data['rm_id']));
		if($this->dry()) {
			$settings=array(
				'active'=>0,
				'drive'=>'',
				'url'=>''
			);
		}
		else {
			do {
				$settings[$this->name]=$this->value;
			}
			while($this->skip());
		}
		return $settings;
	}

	// Сохраняем настройки весов
	function save_scales($post) {
		if(isset($post['active']) && $post['url']=='') {
			return array(
				'success'=>false,
				'txt'=>'incorrect_scales_url'
			);
		}
		$sql="INSERT OR REPLACE INTO `scales_settings` (`name`, `value`, `rm`) VALUES ";
		$val=array();
		foreach ($post as $key => $value) {
			if(!empty($val)) {
				$sql.=", ";
			}
			$sql.="(?, ?, ?)";
			$val[]=$key;
			$val[]=$value;
			$val[]=$this->api_data['rm_id'];
		}
		$res=$this->db->exec($sql, $val);
		if($res!==false) {
			return array(
				'success'=>true,
				'txt'=>'save_successful'
			);
		}
		return array(
			'success'=>false,
			'txt'=>'db_error'
		);
	}

	// Список драйверов
	function get_drivers() {
		$drivers=array();
		$scales_dir=$this->f3->get('scales_dir');
		$dirs=scandir($scales_dir); // Ищем все драйвера
		if($dirs) {
			foreach ($dirs as $d) {
				$folder=$scales_dir.$d;
				$file=$folder.'/driver.config';
				if(is_dir($folder) && file_exists($file)) {
					$config=parse_ini_file($file);
					if($config) {
						$drivers[$folder]=array(
							'title'=>$config['ServerName'],
							'path'=>$folder,
							'url'=>$config['ScalesUrl']['default']?$config['ScalesUrl']['default']:''
						);
					}
				}
			}
			foreach ($dirs as $d) {
				$folder=$scales_dir.$d;
				$file=$folder.'/server.config';
				if(is_dir($folder) && file_exists($file)) {
					$config=parse_ini_file($file);
					if($config) {
						$drivers[$folder]=array(
							'title'=>$config['ServerName'],
							'url'=>$config['ScalesUrl'],
							'path'=>$folder
						);
					}
				}
			}
		}

		return $drivers;
	}

	// Узнаем вес
	function weight($line_id) {
		if(!$line_id) {
			return array(
				'success'=>false,
				'txt'=>'not_enough_data'
			);
		}
		$res=$this->scales->weight();
		if(!$res['success']) {
			return $res;
		}

		$lines=new \Models\Receiptlines($this->db, $this->f3);
		$line=$lines->select_lines(array('id=?', $line_id), array('limit'=>1));
		$res['weight']=(float)str_replace(',', '.', $res['weight']);
		if($line[0]['unit_okei']==163) $res['weight']*=1000;
		$res['txt']='success';
		$res['next_step']='/receipts/change_line?line_id='.$line_id.'&count='.$res['weight'];
		return $res;
	}
}
