<?php
namespace Models;

class ingenico {
	public $f3, $sets, $config;

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

	function send_cmd($cmd) {
		if(file_exists($this->config['ArcusPath']."cheq.out")) {
			unlink($this->config['ArcusPath']."cheq.out");
		}
		if(file_exists($this->config['ArcusPath']."chek.out")) {
			unlink($this->config['ArcusPath']."chek.out");
		}
		if(file_exists($this->config['ArcusPath']."rc.out")) {
			unlink($this->config['ArcusPath']."rc.out");
		}
		$res=str_replace("\n", '', $cmd);
		$res=str_replace("\r", '', $cmd);
		exec($this->config['ArcusPath']."CommandLineTool/bin/".$this->config['ArcusFile']." ".$cmd);
		$res=file_get_contents($this->config['ArcusPath']."rc.out");
		$res=str_replace("\n", '', $res);
		$res=str_replace("\r", '', $res);
		$res=trim($res);
		$cheq=file_get_contents($this->config['ArcusPath']."cheq.out");
		if (!preg_match('//u', $cheq)) {
			$cheq=iconv("windows-1251","utf-8",$cheq);
		}
		$cheq=str_replace('~', '' , $cheq);
		if($res!='000') {
			return array(
				'success'=>false,
				'txt'=>nl2br($cheq)
			);
		}
		$chek=file($this->config['ArcusPath']."chek.out", FILE_IGNORE_NEW_LINES);
		if($chek) {
			$pan=mb_substr(trim($chek[1]), -4, 4);
			$transid=trim($chek[8]);
			$authcode=trim($chek[3]);
		}
		return array(
			'success'=>true,
			'txt'=>nl2br($cheq),
			'slip'=>nl2br($cheq),
			'pan'=>$pan,
			'transid'=>$transid,
			'authcode'=>$authcode
		);
	}

	function ticket($type, $sum, $return_bt=null) {
		if($type=='sale') {
			$cmd='/o'.$this->config['Sale'];
		}
		elseif($type=='return') {
			$cmd='/o'.$this->config['Return'];
		}
		else {
			$cmd='/o'.$this->config['Cancel'];
		}
		$cmd.=" /a".($sum*100)." /c643";
		if($type=='return') {
			$cmd.=" /v".str_replace(' ', '_', $return_bt['authcode'])." /x".$return_bt['transid'];
		}
		return $this->send_cmd($cmd);
	}

	function z($change) {
		$cmd='/o'.$this->config['Close'];
		return $this->send_cmd($cmd);
	}

	function x($change) {
		$cmd='/o'.$this->config['X'];
		return $this->send_cmd($cmd);
	}

	function cashermenu() {
		$cmd='/o'.$this->config['CasherMenu'];
		return $this->send_cmd($cmd);
	}

	function adminmenu() {
		$cmd='/o'.$this->config['AdminMenu'];
		return $this->send_cmd($cmd);
	}

	function testconnection() {
		$cmd='/o'.$this->config['Test'];
		return $this->send_cmd($cmd);
	}
}
