<?php
/* Demonstration of available options on the qrCode() command */
// require __DIR__ . '/../autoload.php';
require 'api/Mike42/autoload.php';

use Mike42\Escpos\Printer;

class NfcCodePrint extends Printer{
  private $p_chars_line = 64;
  private $p_xml_string = '';

  // métodos mágicos get e set
  public function __set($atrib, $value){
    $this->$atrib = $value;
  }

  public function __get($atrib){
    return $this->$atrib;
  }

  // faz a montagem para o cupom
  function montarCupom($p_string){
    $xml = simplexml_load_string($p_string);

    // $this->setCenterText("TESTE DE IMPRESSAO DIRETA NA IMPRESSORA");

    // $this->setCenterText($xml->CFeCanc->infCFe->emit->xFant);
    $this->setCenterText($xml->infCFe->emit->xFant);
    $this->setCenterText($xml->infCFe->emit->xNome);
    $this->setCenterText($xml->infCFe->emit->enderEmit->xLgr . "," . $xml->infCFe->emit->enderEmit->nro);
    $this->setCenterText($xml->infCFe->emit->enderEmit->xMun . ' - SP');

    $info_emissor = 'CNPJ ' . $xml->infCFe->emit->CNPJ . ' IE ' . $xml->infCFe->emit->IE . ' IM ' . $xml->infCFe->emit->IM;
    $this->setCenterText($info_emissor);
    $this->setLinhaTracejada();

    $this->nr_cupom_venda = $xml->infCFe->ide->nCFe;
    $ds_extrato_venda = 'Extrato Nro. ' . $this->nr_cupom_venda;
    $this->setCenterTextBold($ds_extrato_venda, 1, 1);
    $this->setCenterTextBold("DADOS DO CUPOM FISCAL ELETRÔNICO CANCELADO - SAT", 1, 2);
    $this->setLinhaTracejada();


      $originalDate= $xml->infCFe->ide->dEmi . " " . $xml->infCFe->ide->hEmi;
      $dt_hora_completa= date("d-m-Y H:i:s", strtotime($originalDate));
      $this->ts_cfe = $dt_hora_completa;

      $this->setCenterTextBold("SAT No." . $xml->infCFe->ide->nserieSAT, 1, 1);
      $this->setCenterText($this->ts_cfe);

      // Valor Total CANCELADO
      $this->vl_total_cfe = $xml->infCFe->total->vCFe;
      $this->setCenterTextBold("R$ TOTAL CANCELADO " . $this->vl_total_cfe, 1, 1);

      // rodapé do Cfe, informações de Versão do SW
      $this->setLinhaTracejada();

      /* Código de Barras de Acordo com a chave Cancelada */
      $this->ds_chave = $xml->infCFe['Id'];
      // $this->ds_chave = $xml->infCFe['chCanc'];
      $this->setCodigoBarras();

      /* QrCode do Cancelamento do Cupom */
      $this->ds_qrcode = $xml->infCFe->ide->assinaturaQRCODE;

      $qrcodeDate  = $xml->infCFe->ide->dEmi . $xml->infCFe->ide->hEmi;
      // $qrcodeVlCfe = preg_replace("/[^0-9]/", "", $this->vl_total_cfe);

      if(!isset($this->ds_dest_doc)){
        $this->ds_dest_doc = '';
      }

      $p_qr_code = $this->ds_chave . "|" . $qrcodeDate . "|" . $this->vl_total_cfe . "|" . $this->ds_dest_doc . "|" . $this->ds_qrcode;
      $this->setQrCode($p_qr_code);

      // rodapé do Cfe, informações de Versão do SW
      $this->setLinhaTracejada();
      $info_loja = "PDV: 001" .
                   " LJ:0001" .
                   " COO:" . $this->nr_cupom_venda .
                   " Operador:" . $this->id_operador . " " . $this->ds_nome_operador;
      $info_loja = $this->setStringCharsLine($info_loja,"");
      $this->setLeftText($info_loja);
      $this->setLeftText($this->ds_versao_sw);
	  $this->setPulaLinha();

  }

  // retorna o objecto como texto
  public function toString(){
    $st_ret = $this->getPrintBuffer();
    return $st_ret;
  }

  // imprime diretamente para impressora
  public function imprimir(){
    global $caminho;
    try {
      // $this->montarCupom();
      $this->cut();
      $this->close();
  	} catch (Exception $e) {
  		$msg_erro = "Couldn't print to this printer: " . $caminho . " - " . $e -> getMessage() . "\n";
  		// addError($msg_erro);
  		echo $msg_erro;
  	}
      return true;
  }

  public function setInformacaoSW($p_id_operador, $p_nm_operador, $p_sw_code){
    $this->id_operador     = $p_id_operador;
    $this->ds_nome_operador= $p_nm_operador;
    $this->ds_versao_sw    = $p_sw_code;
  }


  function getDescricaoMP($cd_mp){
    $ds_ret = 'Dinheiro';
    switch ($cd_mp) {
        case '01':
            $ds_ret = 'Dinheiro';
            break;
        case '02':
            $ds_ret = 'Cheque';
            break;
        case '03':
            $ds_ret = 'Cartão de Crédito';
            break;
        case '04':
            $ds_ret = 'Cartão de Débito';
            break;
        case '05':
            $ds_ret = 'Crédito Loja';
            break;
        case '10':
            $ds_ret = 'Vale Alimentação';
            break;
        case '11':
            $ds_ret = 'Vale Refeição';
            break;
        case '12':
            $ds_ret = 'Vale Presente';
            break;
        case '13':
            $ds_ret = 'Vale Combustível';
            break;
        case '99':
            $ds_ret = 'Vale Combustível';
            break;
        }
    return $ds_ret;
  }

  // linha tracejada para divisão de sessões
  function setLinhaTracejada(){
    $texto = "-";
    $ds_print = str_pad($texto, $this->p_chars_line, "-");
    $this->setLeftText($ds_print);
  }
  
  // linha em branco
  function setPulaLinha(){
    $texto = " ";
    $ds_print = str_pad($texto, $this->p_chars_line, " ");
    $this->setLeftText($ds_print);
  }

  // acrescenta espacos para justificar o texto
  function setStringCharsLine($texto1, $texto2){
    $nr_char = $this->p_chars_line - strlen($texto2);

    $ds_ret = str_pad($texto1, $nr_char);
    $ds_ret.= $texto2;
    return $ds_ret;
  }

  function setCodigoBarras(){

    /*
    $this->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
    $this->selectPrintMode(Printer::BARCODE_CODE128);
    $this->text($standard ["title"] . "\n");
    $this->setEmphasis(true);
    $this->text("Content: " . $barcode ["content"] . "\n");
    $this->barcode($barcode ["content"], $type);
    $this->barcode($barcode ["content"]);
    $this->feed();*/
    $chave_clear = substr($this->ds_chave, -44);

    $this->setEmphasis(false);

    // $content = "{C" . chr(21) . chr(32) . chr(43);
    $content1 = "{B" . substr($chave_clear, 0, 22);
    $content2 = "{B" . substr($chave_clear, -22);

    $this->setEmphasis(true);
    $this->setBarcodeHeight(64);

    $this->setJustification(1);
    $this-> text("\n$chave_clear\n");

    $this->setBarcodeWidth(2);
    $this->barcode($content1, Printer::BARCODE_CODE128);
    $this->feed();
    $this->barcode($content2, Printer::BARCODE_CODE128);

    $this->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
    // $this->barcode($content, Printer::BARCODE_CODE128);

    /*
    $widths = array(1, 2, 3, 4, 5, 6, 7, 8);
    foreach($widths as $width) {
        $this -> text("\nWidth $width\n");
        $this->setBarcodeWidth($width);
        $this->barcode($content, Printer::BARCODE_CODE128);
    }*/
    $this->feed();
  }

  function setStringBarra($p_string){
    $p_return = '';
    for ($i=0; $i <= strlen($p_string); $i += 4) {
      $p_return .= substr($p_string, $i, 4) . chr(32);
    }
    return $p_return;
  }

  function setQrCode($p_qr_code){
    $this -> setJustification(1);
    $this -> qrCode($p_qr_code, Printer::QR_MODEL_2);
    // $this -> text("Most simple example\n");
    $this -> feed();
  }

  function setLeftText($value){
    $this->setJustification(0);
    // $this -> qrCode($testStr);
    $this-> setFont(2);
    $this-> selectPrintMode(1);
    $this-> setTextSize( 1, 1);
    $this-> text($value);
    $this-> setJustification();
    $this-> feed();
  }

  function setRigthText($value){
    $this->setJustification(2);
    // $this -> qrCode($testStr);
    $this -> setFont(2);
    $this -> selectPrintMode(1);
    $this -> setTextSize( 1, 1);
    $this -> text($value);
    $this -> setJustification();
    $this -> feed();
  }

  function setCenterText($value){
    $this->setJustification(1);
    $this->selectPrintMode(1);
    // $this -> qrCode($testStr);
    $this-> setFont(2);
    $this-> setTextSize( 1, 1);
    $this-> text($value);
    $this-> setJustification();
    $this-> feed();
  }

  function setCenterTextBold($value, $p_width, $p_heigth){
    $this -> setJustification(1);
    $this -> selectPrintMode(40);
    // $this -> qrCode($testStr);
    $this -> setFont(1);
    $this -> setEmphasis(true);
    $this -> setTextSize($p_width, $p_heigth);
    $this -> text($value);
    $this -> setJustification();
    $this -> feed();
  }

  function title($str){
      $this-> selectPrintMode(Printer::MODE_DOUBLE_HEIGHT | Printer::MODE_DOUBLE_WIDTH);
      $this-> text($str);
      $this-> selectPrintMode();
  }
}



/*

// Most simple example
// title($this, "QR code demo\n");

/* $testStr = "Testing 123";
$this -> qrCode($testStr);
$this -> text("Most simple example\n");
$this -> feed();

// Demo of numeric data being packed more densly
title($this, "Data encoding\n");
$test = array(
    "Numeric"      => "0123456789012345678901234567890123456789",
    "Alphanumeric" => "abcdefghijklmnopqrstuvwxyzabcdefghijklmn",
    "Binary"       => str_repeat("\0", 40));
foreach ($test as $type => $data) {
    $this -> qrCode($data);
    $this -> text("$type\n");
    $this -> feed();
}

// Demo of error correction
title($this, "Error correction\n");
$ec = array(
    Printer::QR_ECLEVEL_L => "L",
    Printer::QR_ECLEVEL_M => "M",
    Printer::QR_ECLEVEL_Q => "Q",
    Printer::QR_ECLEVEL_H => "H");
foreach ($ec as $level => $name) {
    $this -> qrCode($testStr, $level);
    $this -> text("Error correction $name\n");
    $this -> feed();
}

// Change size
title($this, "Pixel size\n");
$sizes = array(
    1 => "(minimum)",
    2 => "",
    3 => "(default)",
    4 => "",
    5 => "",
    10 => "",
    16 => "(maximum)");
foreach ($sizes as $size => $label) {
    $this -> qrCode($testStr, Printer::QR_ECLEVEL_L, $size);
    $this -> text("Pixel size $size $label\n");
    $this -> feed();
}

// Change model
title($this, "QR model\n");
$models = array(
    Printer::QR_MODEL_1 => "QR Model 1",
    Printer::QR_MODEL_2 => "QR Model 2 (default)",
    Printer::QR_MICRO => "Micro QR code\n(not supported on all printers)");
foreach ($models as $model => $name) {
    $this -> qrCode($testStr, Printer::QR_ECLEVEL_L, 3, $model);
    $this -> text("$name\n");
    $this -> feed();
}
*/
