<?php
header_remove('Access-Control-Allow-Origin');
header('Access-Control-Allow-Origin: *');
error_reporting(0);

function _panelAction(){

  // $bufferDetele = file_get_contents('buffer/printers_list.txt');


  // $file = file_get_contents('buffer/printers_list.txt');

  // $lPrinters = explode("\n", $file);
  // unset($lPrinters[0]);
  // foreach ($lPrinters as $key => $value) {

  //   print_r($key);
  //   print_r(utf8_decode($value).'<br>');
  // }

  // print_r($lPrinters);

  // for ($i=0; $i < count($lPrinters) ; $i++) { 
  //   print_r( utf8_decode($lPrinters[$i]).'<br>');
  // }

  require 'view/panel.php';
}

function _recargarImpresorasAction(){

  $micarpeta = 'buffer';
  if (!file_exists($micarpeta)) {
      mkdir($micarpeta, 0777, true);
  }


  if (file_exists('buffer/printers_list.xml')) {
    unlink('buffer/printers_list.xml');
  }

  // print_r($_SERVER);
  $server = $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];

  list($baseUrl) = explode('index.php', $server);
  // print_r("Base: {$baseUrl}");

  // $realPath = realpath('');

  // print_r($realPath);

  $path = str_replace("/", "\\\\", $baseUrl);

  // print_r($path);

  shell_exec("wmic printer get Shared, ShareName, drivername, local, network, servername /format:rawxml >> {$path}buffer\\printers_list.xml");

  $file = file_get_contents('buffer/printers_list.xml');

  // print_r($file);

  $xml_peticion = simplexml_load_string($file);
  $array = json_decode(json_encode($xml_peticion->RESULTS->CIM));
  // print_r($array);
  $lPrinters = $array->INSTANCE;

  foreach ($lPrinters as $device) {
    $device = $device->PROPERTY;

    foreach ($device as $print) {   
      // print_R($print->{'@attributes'});
      // print_r($print);
      if($print->{'@attributes'}->NAME == 'Shared'){
        $status = $print->VALUE;
        // print_r($status);
      }
      if ($print->{'@attributes'}->NAME == 'ShareName') {
        $shareName = $print->VALUE;
      }
      if ($print->{'@attributes'}->NAME == 'DriverName') {
        $driverName = $print->VALUE;
      }
      if ($print->{'@attributes'}->NAME == 'Local') {
        $local = $print->VALUE;
      }
      if ($print->{'@attributes'}->NAME == 'Network') {
        $network = $print->VALUE;
      }
      if ($print->{'@attributes'}->NAME == 'ServerName') {
        $servername = substr($print->VALUE, 2);
      }
    }
    $lImpresoras[] = (object) array('status' =>$status, 'shareName' => $shareName, 'driverName' => $driverName, 'local' => $local, 'network' => $network,'servername' => $servername );

    // print_r($print->PROPERTY);
  }
  // print_r($lImpresoras);

  // print_r($newArray[9]);

  
  // $peticion_parse = $xml_peticion->children('soap', true)->Body->children()->BuscarAseguradosDocIdentResponse;
  // $peticion_parse = $xml_peticion->children('COMMAND');
  // print_r($peticion_parse);
  

  // $lPrinters = explode("\n", $file);
  // print_r($lPrinters);
  // unset($lPrinters[0]);

  // $parts = explode(" ", $lPrinters[6]);
  // print_r($parts);

  // list($status, $nombre) = explode(" ", $lPrinters[6]);

  // echo "Estado: {$status} -- Nombre : {$nombre}";
  // $options = utf8_decode($value)
  // $options ="";
  foreach ($lImpresoras as $value) {
    if ($value->status == 'TRUE') {
      $options .= "<option value='{$value->shareName}' data-drivername='{$value->driverName}' data-local='{$value->local}' data-network='{$value->network}' data-servername='{$value->servername}' >{$value->shareName}</option>";      
    }
  }
  // echo $options;
  $response = array();
  $response['options'] = $options;

  header('Content-Type: application/json');
	echo json_encode($response);
}

function _pruebaimpresionAction(){

  $micarpeta = 'buffer';
  if (!file_exists($micarpeta)) {
      mkdir($micarpeta, 0777, true);
  }
  $nombreTicketera = $_POST['namePrint'];
  $driverName = $_POST['driverName'];
  $local = $_POST['local'];
  $network = $_POST['network'];
  $servername = $_POST['servername'];

  $mostrarImagen = true;

  if ($driverName == 'EPSON TM-U220 ReceiptE4') {
    $mostrarImagen = false;
  }
  
  // print_r($_POST);


  if ($local == 'FALSE') {
    
    $nombreTicketera = "smb://{$servername}/{$nombreTicketera}";
  }

  // print_r($mostrarImagen);
  require 'view/impresion_prueba.php';
  
}

function _guardarTicketeraAction(){
  
  $namePrint = $_POST['namePrint'];
  $driverName = $_POST['driverName'];
  $local = $_POST['local'];
  $network = $_POST['network'];
  $servername = $_POST['servername'];

  // print_r($namePrint);

  $data = Array (
    'namePrint' => $namePrint,
    'driverName' => $driverName,
    'local' => $local,
    'network' => $network,
    'servername' => $servername,
  );

  // encode array to json
  $json = json_encode($data, JSON_PRETTY_PRINT);
  

  file_put_contents("buffer/data.json", $json);

  $msj = "<code><b>Se guardó la Ticketera => ${namePrint}</b></code>";


  $response['msj'] = $msj;

  header('Content-Type: application/json');
	echo json_encode($response);
}

function _impresionAction(){
  
  $dataJson = json_decode(file_get_contents('buffer/data.json'));
  $msj = "Ticketera: {$dataJson->namePrint}";

  $nombreTicketera = $dataJson->namePrint;
  $driverName = $dataJson->driverName;
  $local = $dataJson->local;
  $servername = $dataJson->servername;

  $body = base64_decode($_POST['body']);

  list($heder_logo, $logobase64) = explode( ',', $_POST['logo']);
  $logoDecode = base64_decode($logobase64);

  
  list($secs, $microsec) = explode('.',  microtime(true)); //se extrae los microsegundos
  
  $nameTemp = "_".date('YmdHsi').$microsec;

  $img_file = "buffer/{$nameTemp}.png";
  // print_r($img_file);
  
  $mostrarImagen = true;
  
  if ($driverName == 'EPSON TM-U220 ReceiptE4') {
    $mostrarImagen = false;
  }
  
  if ($local == 'FALSE') {
    $nombreTicketera = "smb://{$servername}/{$nombreTicketera}";
  }
  
  
  // imagepng($im, $img_file, 0);
  // print_r($body);
  
  file_put_contents("buffer/{$nameTemp}.php", $body);
  file_put_contents("buffer/{$nameTemp}.png", $logoDecode);

  $logoCabecera = "buffer/{$nameTemp}.png";

  $msj = 'Impresion enviada';

  try {
    require "buffer/{$nameTemp}.php";
    // unlink("buffer/{$nameTemp}.php");
  } catch (Error $e) {
    // print_r($e['message:protected']);

    $msj = "No se pudo imprimit ticket";
  }
  unlink("buffer/{$nameTemp}.php");
  unlink("buffer/{$nameTemp}.png");
  
  $statusCode = 200;
  


  $response['msj'] = $msj;
  $response['nombreTicketera'] = $nombreTicketera;
  $response['statusCode'] = $statusCode;

  header('Content-Type: application/json');
	echo json_encode($response);

}


function addSpaces($string = '', $valid_string_length = 0) {

  if (strlen($string) < $valid_string_length) {
      $spaces = $valid_string_length - strlen($string);
      for ($index1 = 1; $index1 <= $spaces; $index1++) {
          $string = $string . ' ';
      }
  }

  return $string;
}

function dd($array)
{
  echo "<pre>";
  print_r($array);
  echo "</pre>";
  exit();
}

function _serverTicketeraAction(){
  
  $dataJson = json_decode(file_get_contents('buffer/server_data.json'));

  $response = $dataJson;
  
  header('Content-Type: application/json');
  echo json_encode($response);
}