<?php
namespace Models;

class php_shtrihm2_Fr_php {
  public $f3, $sets, $config, $port, $kkm;
  public $new_smde=true;

  function __construct($f3, $sets, $config) {
    $this->f3=$f3;
    $this->sets=$sets;
    require_once $sets['driver'].'/KKM.ports.php';
    require_once $sets['driver'].'/KKM.class.php';
    $this->config=$config;
    //$this->config=parse_ini_file($sets['driver'].'/server.config'); // Настройки драйвера
    $this->config['PortType']=strtolower($this->config['PortType']);
    if($this->config['PortType']=='remote') {
      $sets['url']=mb_substr($sets['url'], mb_strrpos($sets['url'], '/')+1);
      $url=explode(':', $sets['url']);
      $host = $url[0];
      $port = $url[1];
      $this->port = new \RemotePort($host, $port);
    }
    elseif($this->config['PortType']=='socket') {
      $sets['url']=mb_substr($sets['url'], mb_strrpos($sets['url'], '/')+1);
      $url=explode(':', $sets['url']);
      $host = $url[0];
      $port = $url[1];
      $this->port = new \RemoteSocket($host, $port);
    }
    elseif($this->config['PortType']=='ssh') {
      $u=mb_substr($sets['url'], mb_strrpos($sets['url'], '/'));
      $url=explode(':', $u);
      $host = $url[0];
      $port = $url[1];
      $this->port = new \SshComPort($host, $port);
    }
    else {
      $this->port = new \LocalComPort($sets['url']);
    }
    require_once $this->sets['driver'].'/Shtrih.lang.php';
    require_once $this->sets['driver'].'/ShtrihM_HiLevel.class.php';
    $this->kkm= new \ShtrihM_HiLevel($this->port, false, $sets);
    $this->kkm->paper_width=$this->config['PaperWidth'];
    if($this->config['AlwaysExec']) {
      $this->always_exec($this->config['AlwaysExec']);
    }
    $vat_type=array(
      'vatNo'=>4,
      'vat0'=>3,
      'vat110'=>6,
      'vat10'=>2,
      'vat120'=>5,
      'vat20'=>1
    );
    foreach($vat_type as $type=>$vat){
      if(!isset($this->config['vat_type'][$type])) {
              $this->config['vat_type'][$type]=$vat;
          }
    }
  }

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

  function kkm_init() {
    /*if($this->kkm->kkm_init()) {
      $this->f3->set('SESSION.'.$this->sets['printer'].'_drivers_init', 1);
    }
    else {
      $txt='Ошибка инициализации ККМ';
      echo '<p class="false">'.$txt.'</p>';
      $this->f3->get('logs_model')->save_log($txt);
      exit();
    }*/
  }

  // Узнаем состояние смены
    function change_status() {
      /*if(!$this->f3->get('SESSION.'.$this->sets['printer'].'_drivers_init')) {
        $this->kkm_init();
      }*/
      if(!$this->kkm->openConnection()) {
        $txt='Не возможно установить соединение с кассой';
        echo '<p class="false">'.$txt.'</p>';
        $this->f3->get('logs_model')->save_log($txt);
        exit();
      }
      $counter=30;
      while (!$this->kkm->isReady() && $counter>0) {
        $counter-=1;
        sleep(1);
      }
      $status=false;
      $s=$this->kkm->getKKMState();
      if((int)$s['fr_mode']==3) {
        $status='expired';
      }
      if((int)$s['fr_mode']==2) {
        $status='opened';
      }
      if((int)$s['fr_mode']==4) {
        $status='closed';
      }
      $this->kkm->closeConnection();
      usleep($this->config['WaitTime']);
      $this->kkm->openConnection();
      $fn = $this->kkm->writecmd('ff01');
      $fn=preg_replace('/[^0-9]/', '', $fn);
      $this->f3->set('fn', $fn);
      $this->kkm->closeConnection();
      return $status;
    }

  function check_fnstatus() {
    $res=$this->send_ajax('check_fnstatus;');
    return $res;
  }

  // Отправка запроса
  function send_ajax($data, $timeout=295, $view=false) {
    /*if(!$this->f3->get('SESSION.'.$this->sets['printer'].'_drivers_init')) {
      $this->kkm_init();
    }*/
    $strs=explode("\n", $data);
        if(!$this->kkm->openConnection()) {
          $txt='Не возможно установить соединение с кассой';
          $this->f3->get('logs_model')->save_log($txt);
          if($this->f3->get('fr_error_ignore')) {
            return array(
              'success'=>false,
              'error'=>$txt
            );
          }
          echo '<p class="false">'.$txt.'</p>';
          exit();
        }
      // Проверим состояние ККМ на наличие ошибок, связанных с ошибками печати
      $n=5;
      while($n>5) {
        $fr_submode=$this->kkm->getKKMState();
        if(isset($fr_submode['fr_submode'])) {
          $n=0;
          break;
        }
        else {
          sleep(2);
        }
      }

      if(!isset($fr_submode['fr_submode'])) {
        $txt='Не возможно установить соединение с кассой';
          $this->f3->get('logs_model')->save_log($txt);
          if($this->f3->get('fr_error_ignore')) {
            return array(
              'success'=>false,
              'error'=>$txt
            );
          }
          echo '<p class="false">'.$txt.'</p>';
          exit();
      }
      
      if($fr_submode['fr_submode']=='03') {
        $this->kkm->continue_print();
      }
      
        $counter=30;
        while (!$this->kkm->isReady() && $counter>0) {
            $counter-=1;
            sleep(100);
        }
        $error=false;
        $print_b=0;
        $this->kkm->wtf("set_table;17;1;7;0;\n");

      foreach ($strs as $s) {
        $ss=explode(';', $s);
        if($ss[0]=='b' || $ss[0]=='z' || $ss[0]=='imde' || $ss[0]=='open_session') {
          $print_b=1;
        }
        if(!$s) continue;
        $res=$this->kkm->wtf($s);
            if($res==='nak') {
                $res=$this->kkm->wtf($s);
            }

            if($res==='nak') {
                $error=true;
                $error_txt=$s.' Ошибка интерфейса (Касса)';
            }
            elseif($res===false) {
                $error=true;
                $error_txt='Касса в данный момент недоступна';
            }
            elseif(is_array($res)) {
              if(isset($res['success'])) {
                continue;
              }
              $error=true;
                $error_txt=$s.' '.$res['code'].' '.$res['txt'];
            }

            if($error===true) {
              $this->f3->get('logs_model')->save_log($error_txt);
              if($this->f3->get('fr_error_ignore')) {
                  return array(
                    'success'=>false,
                    'error'=>$error_txt
                  );
              }
                echo '<p class="false">'.$error_txt.'</p>';
                if($print_b==1 || (is_array($res) && $res['code']=='107')) {
                  echo $continue_html= \Template::instance()->render('fr_error_continue_print.htm');
                  exit();
                }
                exit();
            }
            //$receipt_ready=$this->kkm->receipt_ready;
      }
      $this->kkm->closeConnection();
    if($view===true) {
      foreach ($this->kkm->results as $n=>$txt) {
        if($txt[0]===true) {
          echo '<p class="true">'.$txt['txt'].'</p>';
        }
        elseif($txt[0]===false) {
          echo '<p class="false">'.$txt['txt'].'</p>';
          $this->f3->get('logs_model')->save_log($txt['txt'].' (Касса)');
        }
        else {
          echo '<p class="false">'.$txt.'</p>';
          $this->f3->get('logs_model')->save_log($txt.' (Касса)');
        }
      }
    }
    if($this->kkm->fd!=0 || $this->kkm->fp!=0) {
      $res=array(
        'success'=>true,
        'fd'=>$this->kkm->fd,
        'fp'=>$this->kkm->fp
      );
    }
    return $res;
  }
}
