<?php
namespace Models;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\Printer;

class Cd_php {
	public $f3, $sets, $config, $connector, $printer;
	
	function __construct($f3, $sets) {
		$this->f3=$f3;
		$this->sets=$sets;
		$this->config=parse_ini_file($sets['driver'].'/server.config'); // Настройки драйвера
		spl_autoload_register(function ($class_name) {
    		require_once('src/'.str_replace('\\', '/', $class_name).'.php');
		});
		if($this->config['AlwaysExec']) {
			$this->always_exec($this->config['AlwaysExec']);
		}
	}

	function always_exec($exec) {
		foreach ($exec as $cmd) {
			if($cmd!='') {
				exec($cmd);
			}
		}
	}

	function printer_connect() {
		$this->config['PortType']=mb_strtolower($this->config['PortType']);
		if($this->config['PortType']=='local') {
			return $connector = new FilePrintConnector($this->sets['url']);
		}
		elseif($this->config['PortType']=='remote') {
			$u=mb_substr($this->sets['url'], mb_strrpos($this->sets['url'], '/')+1);
			$url=explode(':', $u);
			$host = $url[0];
			$port = $url[1];
			return $connector = new NetworkPrintConnector($host, $port);
		}
		elseif($this->config['PortType']=='windowsusb') {
			return $connector = new WindowsPrintConnector($this->sets['url']);
		}
		echo $error_txt='<p class="false">Невозможно установить соединение</p>';
		$this->f3->get('logs_model')->save_log($error_txt.' (Дисплей покупателя)');
		exit();
	}

	function cd_init() {
		if(isset($this->config['Exec'])) {
            foreach ($this->config['Exec'] as $cmd) {
                if($cmd!='') {
                    exec($cmd);
                }
            }
        }
        if(isset($this->config['Send'])) {
        	$this->connector = $this->printer_connect();
			$this->printer = new Printer($this->connector);
            foreach ($this->config['Send'] as $cmd) {
                if(!$cmd) continue;
                $p=explode(';', $cmd);
                if(count($p)>1) {
                	$this->wtf($cmd);
                }
                else {
                	$this->connector->write(pack('H*', $cmd));
                }
            }
            $this->printer->close();
        }
        $this->f3->set('COOKIE.drivers_cd_init', 1);
	}

	// Форматирование текста
	function text_format($s, $w=20, $charset='cp855') {
		$s=mb_substr($s, 0, $w);
		if($charset!='utf-8' && $charset!='utf8') {
			$s=iconv('utf-8', $charset, $s);
		}
        return $s;
    }

	// Что нужно выполнить
	function wtf($s) {
		$s=trim($s);
        $p=explode(';', $s);
        $n=count($p);
        $cmd=$p[0];
        unset($p[0]);
        if($p[$n-1]=='') {
            unset($p[$n-1]);
            $n-=1;
        }
		if($cmd=='p') { // Печать строки или строк
			$this->p($p);
		}
	}

	// Печать строки
	function p($strs) {
		$txt='';
		$n=0;
		foreach ($strs as $s) {
			$w=$this->config['DisplayWidth1'];
			if($n>0) $w=$this->config['DisplayWidth2'];
			if(($txt || $s=='') && mb_strlen($s)<$w)  {
				$txt.="\n\r";
			}
			$txt.=$this->text_format($s, $w, $this->config['Charset']);
			$n++;
		}
		$this->connector->write($txt);
	}


	// Отправка запроса
	function print($data, $timeout=295, $view=false) {
		if(!$this->f3->get('COOKIE.drivers_cd_init')) {
			$this->cd_init();
		}
		$strs=explode("\n", $data);

		$this->connector = $this->printer_connect();
		if(!$this->connector->fp) {
			if($view) {
				echo $error_txt="Невозможно установить соединение";
				$this->f3->get('logs_model')->save_log($error_txt.' (Дисплей покупателя)');
			}
			return;
		}
		$this->printer = new Printer($this->connector);
		foreach ($strs as $s) {
			$this->wtf($s);
		}
		$this->printer -> close();
		if($view) {
			echo $error_txt="Запросы отправлены";
			$this->f3->get('logs_model')->save_log($error_txt.' (Дисплей покупателя)');
		}
	}

}
