<?php
namespace Models;

class sberbank2 {
	public $f3, $sets;

	function __construct($f3, $sets, $config) {
		$this->f3=$f3;
		$this->sets=$sets;
		$this->config=$config;
	}

	function send_cmd($cmd) {
		if(!file_exists($this->config['SberBankPath'].$this->config['SberBankFile'])) {
			return array (
				'success'=>false,
				'txt'=>'Ошибка. Не найден исполняемый файл'
			);
		}

		if(file_exists($this->config['SberBankPath']."p")) {
			unlink($this->config['SberBankPath']."p");
		}
		if(file_exists($this->config['SberBankPath'].'e')) {
			unlink($this->config['SberBankPath'].'e');
		}
		$res=str_replace("\n", '', $cmd);
		$res=str_replace("\r", '', $cmd);
		exec($this->config['SberBankPath'].$this->config['SberBankFile']." ".$cmd);
		
		if(!file_exists($this->config['SberBankPath'].'e')) {
			return array (
				'success'=>false,
				'txt'=>'Ошибка. Не найден файл результатов.'
			);
		}
		
		$cheq='';
		$success = false;
		$lines=file($this->config['SberBankPath'].'e');
		list($status_code, $status_txt)=explode(',', $lines[0]);
		if((int)$status_code==4353) {
			return $this->send_cmd($cmd.' 0 '.$lines[10]);
		}
		if((int)$status_code==0) {
			$success=true;
		}

		if (!preg_match('//u', $status_txt)) {
			$status_txt=iconv("CP866", "utf-8", $status_txt);
		}
		
		if(file_exists($this->config['SberBankPath']."p")) {
			$cheq=file_get_contents($this->config['SberBankPath']."p");
		}
		$cheq=str_replace('~', '' , $cheq);
		$slips=explode("", $cheq);
		if(!$slips[1]) {
			$slips[1]=$slips[0];
		}
		if (!preg_match('//u', $slips[0])) {
			$slips[0]=iconv("CP866", "utf-8", $slips[0]);
		}
		if (!preg_match('//u', $slips[1])) {
			$slips[1]=iconv("CP866", "utf-8", $slips[1]);
		}
		if($success) {
			return array(
				'success'=>true,
				'txt'=>nl2br($slips[0]),
				'slip'=>nl2br($slips[1])
			);
		}
		
		return array(
			'success'=>false,
			'txt'=>$status_txt.'<br>Код статуса: '.$status_code
		);
	}

	function ticket($type, $sum, $return_bt=null) {
		if($type=='sale') $cmd='1';
		else $cmd='3';
		$cmd.=" ".($sum*100).' 0';
		return $this->send_cmd($cmd);
	}

	function z() {
		$cmd='7';
		return $this->send_cmd($cmd);
	}

	function x() {
		$cmd='9';
		return $this->send_cmd($cmd);
	}

	function testconnection() {
		$cmd='47 2';
		return $this->send_cmd($cmd);
	}
}