<?php
namespace Models;

// Модель для работы с електронными методами оплаты
class Epays extends \DB\SQL\Mapper{
	public $db, $f3, $sets, $nobt, $epay;

	public function __construct($db, $f3, $method_id=0) {
		parent::__construct($db, 'epays_settings'); // подключаемся к таблице с настройками
		$this->f3=$f3;
		$this->db=$db;
		$this->sets=$this->get_sets($method_id);
		if($this->sets['active'] && $this->sets['driver']!='' && file_exists($this->sets['driver'].'/server.php')) {
			$class=explode('/', $this->sets['driver']);
			$class=array_reverse($class);
			$model='\Models\\'.$class[0];
			if(!class_exists($model, false)) {
				require_once($this->sets['driver'].'/server.php');
			}
			/*$config=array();
			if($this->sets['driver_config']) {
				$config=parse_ini_string($this->sets['driver_config']);
			}
			$default=parse_ini_file($this->sets['driver'].'/server.config');
			$config=array_merge($default, $config);*/
			$s=new \Models\Settings($this->f3, $this->db);
			$config=$s->get_driver_config($this->sets['driver'], 'epay', $this->sets['driver_config']);
			$config=$config['config'];
			$this->epay=new $model($f3, $this->sets, $config);
		}
		else {
			$this->sets['active']=0;
		}
	}

	function startwithconfig($path, $config) {
		$class=explode('/', $path);
		$class=array_reverse($class);
		$model='\Models\\'.$class[0];
		require_once($path.'/server.php');
		$this->sets=array(
			'title'=>$config['PayName'],
			'driver'=>$path,
			'active'=>1
		);
		$this->epay=new $model($this->f3, $this->sets, $config);
	}

	function select_epays($query=null, $options=null) {
		$epays=array();
		$this->load($query, $options);
		if(!$this->dry()) {
			do {
				$epays[]=$this->cast();
			}
			while($this->skip());
		}
		return $epays;
	}

	function delete_epay($id) {
		$epay=$this->select_epays(array('id=?', $id), array('limit'=>1));
		if(empty($epay)) {
			return array(
				'success'=>false,
				'txt'=>'epay_not_found'
			);
		}
		if($this->db->exec("DELETE FROM epays_settings WHERE id=?", $id)===false) {
			return array(
				'success'=>false,
				'txt'=>'db_error'
			);
		}
		$this->db->exec("DELETE FROM driver_settings WHERE path=? AND print_group_id=? AND device='epay'", array($epay[0]['driver'], $epay[0]['driver_config']));
		return array(
			'success'=>true,
			'txt'=>'delete_successful',
			'reload'=>array('.epays_list'),
		);
	}

	function get_sets($method_id) {
		$sets=array(
			'id'=>0,
			'active'=>0,
			'driver'=>'',
			'title'=>'',
			'driver_config'=>'',
			'selected'=>0
		);
		$this->reset();
		$this->load(array('id=?', $method_id), array('limit'=>1));
		if($this->dry()) {
			return $sets;
		}
		return $this->cast();
	}

	// Список драйверов
	function get_drivers() {
		$drivers=array();
		$epays_dir=$this->f3->get('epays_dir');
		$dirs=scandir($epays_dir); // Ищем все драйвера
		if($dirs) {
			foreach ($dirs as $d) {
				$folder=$epays_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'],
							'method_title'=>$config['PayName'],
							'path'=>$folder
						);
					}
				}
			}

			foreach ($dirs as $d) {
				$folder=$epays_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'],
							'method_title'=>$config['PayName'],
							'path'=>$folder
						);
					}
				}
			}
		}
		return $drivers;
	}

	// Сохраняем настройки
	function save_epays($data) {
		$selected=array_column($data, 'selected');
		if($selected && array_sum($selected)>1) {
			return array(
				'success'=>false,
				'txt'=>'selected_only_one'
			);
		}
		if($data) {
			foreach($data['id'] as $n=>$id) {
				$this->reset();
				$this->load(array('title=?', $data[$n]['title']), array('limit'=>1));
				if(!$this->dry() && $this->id!=$id) {
					return array(
						'success'=>false,
						'txt'=>'epay_is_exists'
					);
				}
				$this->reset();
				if($id>0) {
					$this->load(array('id=?', $id), array('limit'=>1));
				}
				$epay=array(
					'driver'=>$data['driver'][$n],
					'title'=>$data['title'][$n],
					'active'=>$data['active'][$n],
					'driver_config'=>$data['driver_config'][$n],
					'selected'=>$data['selected'][$n]?$data['selected'][$n]:0
				);
				$this->copyFrom($epay);
				if($this->save()===false) {
					return array(
						'success'=>true,
						'txt'=>'db_error'
					);
				}
			}
		}
		return array(
			'success'=>true,
			'txt'=>'save_successful',
			'reload'=>array('.epays_list'),
		);
	}

	function ticket($type, $sum, $return_epay=null, $lines=array()) {
		if(!$this->sets['active']) {
			return array(
				'success'=>false,
				'txt'=>'Способ электронной оплаты неактивен'
			);
		}
		return $this->epay->ticket($type, $sum, $return_epay, $lines);
	}

	function cancel_qr($data) {
		if(method_exists($this->epay, 'cancel_qr')) {
			return $this->epay->cancel_qr($data);
		}
		return array(
			'success'=>true
		);
	}

	function z($change) {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		return $this->epay->z($change);
	}

	function x($change) {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		return $this->epay->x($change);
	}

	function cashermenu() {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		$res=$this->epay->cashermenu();
		if($res['success']) {
			$res['close_all_window']=true;
		}
		return $res;
	}

	function adminmenu() {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		$res=$this->epay->adminmenu();
		if($res['success']) {
			$res['close_all_window']=true;
		}
		return $res;
	}

	function testconnection() {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		$res=$this->epay->testconnection();
		if($res['success']) {
			$res['close_all_window']=true;
		}
		return $res;
	}

	function paycontrol_qr($data) {
		if(!$this->sets['active']) {
			return array('success'=>true);
		}
		return $this->epay->paycontrol_qr($data);
	}
}