<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
class ImprOrdenMangCtrl extends MY_Controller {
function __construct() {
  
  header('Access-Control-Allow-Origin: *');
  header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Control-Request-Method");
  header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
  header("Allow: GET, POST, OPTIONS, PUT, DELETE");
  header('content-type: application/json; charset=utf-8');
  $method = $_SERVER['REQUEST_METHOD'];
  if($method == "OPTIONS") {
      die();
  }
parent::__construct(); 
// add library of Pdf 
$this->load->library('Pdf');
}


public function _remap($met,$parametros = array()){

  $method = $_SERVER['REQUEST_METHOD'];

 if($met ==="index"){

  switch ($method)  
  { case 'PUT':
     // $this->Edit(); 
    break;
    case 'POST': 
      $this->Add();
    break;
    case 'GET': 
      $this->GestionOrden($parametros);
    case 'HEAD': 
      // echo json_encode( $method );
    break; 
    case 'DELETE': 
     // $this->Delete($parametros); 
    break; 
    case 'OPTIONS': 
     // echo json_encode( $method );
   break; 
   default: 
   echo json_encode( "Error" );
   break; 
  }
}


 }

 private function Add(){
  $Datos = $this->input->raw_input_stream;
  if(is_string($Datos) ===true){
    $Datos =  json_decode($Datos, true);
  }

  if ( !isset($Datos['ID']) ){return;};

  $Datos= $this->Procesar($Datos['ID']);
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Datos);
    
}

private function Verificar($Nombre,$DB = ""){
  $Dir = Raiz();
  if (Existe($Dir.'/ImprOrdenMang/'.$Nombre.'.pdf') === true){
     return  $this->Verificar(Random($DB));
  }else{
    return $Nombre;
  }
 
}

private function Procesar($IdOrden ){

  // Buscamos los datos del usuario
  $Token = obtnerToken();
  $Autho = "";
 if($Token != FALSE){
  $Autho =str_replace('Bearer ','', $Token);
 }
 if( $Autho !=""){
  $Autho =str_replace('Bearer ','', $Autho);
  $Token = ValidarToken($Autho);
}
  if(isset($this->session)){
    $ID =  $Token== FALSE ? $this->session->userdata("User") :  $Token ;
}else{
    $ID =   $Token== FALSE ? null :  $Token ;
}
  $User = $this->UserModels->getUser($ID);

  // Buscamos los datos de la orden con el ID
  $Orden = $this->HydraulicHoseModels->getHydraulicHose($IdOrden);

  if( count($Orden)===0 ) return;

  //Buscar el Codigo del Movimiento del produto
           $this->db->select(["CodigoM"]);
        $DatosMov = $this->db->get_where("movimientop",array("CodigoP"=> '0011','CodigoT'=> $User[0]->Tienda))->result();
       
        $DatosMov= $DatosMov[0]->CodigoM;
       
// con los datos que tenemos descontaremos del inventario 
  // '{"Detalle":"15","Status":1,"Observacion":"Prueba","Cantidad":24,"CodigoMo":"2718","CodigoAux","Vence"}'
  $Datos = '{"Status":1,"Observacion":"Orden de Manguera","Cantidad":"'.$Orden[0]->Cantidad.'","CodigoMo":"'.$DatosMov.'" }';
  $Datos= json_decode($Datos, true);
  $this->WarehouseModels->Edit($Datos);
  // luego de descontar del inventario vamos a procesar la orden
  $ArrayDatos["ID"] = intval($IdOrden);
  $ArrayDatos["Status"] = "Procesada";
 $where = "ID = '".$ArrayDatos["ID"]."' ";
  return $this->db->update('ordenmanguera', $ArrayDatos, $where );

}
private function GetPremisos(){
  $Token = obtnerToken();
  $Autho = "";
 if($Token != FALSE){
  $Autho =str_replace('Bearer ','', $Token);
 }
 if( $Autho !=""){
  $Autho =str_replace('Bearer ','', $Autho);
  $Token = ValidarToken($Autho);
}
  if ( $Token === FALSE ){
    $DatosGET= isset($_GET["x"]) ? $_GET["x"]: "" ;
  
   
    $DatosGET =  $DatosGET!=""?ValidarToken($DatosGET) :"";
    $Token  =$DatosGET!=''?$DatosGET: $Token ;
    
   }
  if(isset($this->session)){
    $ID =  $Token== FALSE ? $this->session->userdata("User") :  $Token ;
}else{
    $ID =   $Token== FALSE ? null :  $Token ;
}
  $User = $this->UserModels->getUser($ID);
  $Nivel =$User[0]->Nivel;
  $Permiso= $this->db->get_where('detalleniveles',array("Status"=>"Activo","Ruta"=>"Inspetor","Nivel"=>$Nivel))->result();
  $per =0;
  if(  count($Permiso)>0){
  return $Permiso[0]->Permiso;
}else{
  return 0;
}

}
public function GestionOrden($parametros)
{

 
  $Dir = Raiz(); 
 $Token = obtnerToken();
  $Autho = "";
 if($Token != FALSE){
  $Autho =str_replace('Bearer ','', $Token);
 }
 if( $Autho !=""){
  $Autho =str_replace('Bearer ','', $Autho);
  $Token = ValidarToken($Autho);
}
  if ( $Token === FALSE ){
    $DatosGET= isset($_GET["x"]) ? $_GET["x"]: "" ;
  
   
    $DatosGET =  $DatosGET!=""?ValidarToken($DatosGET) :"";
    $Token  =$DatosGET!=''?$DatosGET: $Token ;
    
   }
  if(isset($this->session)){
    $User =  $Token== FALSE ? $this->session->userdata("User") :  $Token ;
  }else{
    $User =  $Token== FALSE ? null:  $Token ;
  }
  
  if(count($parametros) ===0){ 
    echo "Debe enviar Codigo ";
    return;
  } 
  $IdOrden = 0;
  if(is_numeric($parametros[0])){
    $IdOrden =$parametros[0];
  }else{
    $Ordenaux = $this->HydraulicHoseModels->getHydraulicHoseFiltro("s5"."^".$parametros[0]);
    if(count($Ordenaux)===0)return;
    $Codigoaux= 'ID';
  
  $IdOrden=$Ordenaux[0]->$Codigoaux;
  }
  $Orden = $this->HydraulicHoseModels->getHydraulicHose($IdOrden);
  if(count($Orden)===0)return;

  $Codigo= 'ID';
  $Codigo=$Orden[0]->$Codigo;

   $Nombre = $Orden[0]->Orden;

   

   if (Existe($Dir.'/ImprOrdenMang/'.$Nombre.".pdf") === true){
     
        header("Content-type: application/pdf");
        header("Content-Disposition: inline; filename=documento.pdf");
        readfile( $Dir.'ImprOrdenMang/'.$Nombre.'.pdf');
        return;
      
      
  } 
  $CodigoPlanilla =Digitos($Codigo,4);

 $Tecnico ='Técnico';
  $Tecnico = $this->UserModels->getUser($Orden[0]->$Tecnico);
  $Tecnico =  $Tecnico[0];


  $Armador = $this->ClientModels->getClient($Orden[0]->Armador);

  $Armador2 =  $Armador[0]->Nombre.' '. $Armador[0]->Apellidos;
  $Rut =  $Armador[0]->Rut;
  $RutTec=$Tecnico->Rut;
  $NombreTe = $Tecnico->Nombre.' '. $Tecnico->Apellido;
  $NombreTe = utf8_decode($NombreTe);
  $Armador2 = utf8_decode($Armador2);


   
  
 
  $Year = date("Y");

  $Fecha= $Orden[0]->Ingreso;
  $Cantidad= $Orden[0]->Cantidad;
  $Obs = utf8_encode('Observación');

  $Obs= $Orden[0]->$Obs;

  
// coder for CodeIgniter TCPDF Integration
// make new advance pdf document
$tcpdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
 
// set document information

$tcpdf->SetAuthor('segmarind');
$tcpdf->SetTitle('Orden De ');
$tcpdf->SetSubject('segmarind');
$tcpdf->SetKeywords('TCPDF, PDF, segmarind, test, guide');
 
//set default header information
 
$tcpdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, "", "", array(0,65,256), array(0,65,127));


$tcpdf->setFooterData(array(0,65,0), array(0,65,127));
 
//set header  textual styles
$tcpdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
//set footer textual styles
$tcpdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
 
//set default monospaced textual style
$tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
 
// set default margins
$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// Set Header Margin
$tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);
// Set Footer Margin
$tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);
 
// set auto for page breaks
$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

// set image for scale factor
$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// it is optional :: set some language-dependent strings
if (@file_exists(dirname(__FILE__).'/lang/eng.php'))
{
// optional
require_once(dirname(__FILE__).'/lang/eng.php');
// optional
$tcpdf->setLanguageArray($l);
}
 
// set default font for subsetting mode
$tcpdf->setFontSubsetting(true);



// Set textual style
// dejavusans is an UTF-8 Unicode textual style, on the off chance that you just need to
// print standard ASCII roasts, you can utilize center text styles like
// helvetica or times to lessen record estimate.
//$tcpdf->SetFont('dejavusans', '', 14, '', true);
 
// Add a new page
// This technique has a few choices, check the source code documentation for more data.
$tcpdf->AddPage();





$style = array(
  'border' => 0,
  'vpadding' => 'auto',
  'hpadding' => 'auto',
  'fgcolor' => array(0,0,0),
  'bgcolor' => array(255,255,255),
  'module_width' => 1, // width of a single module in points
  'module_height' => 1 // height of a single module in points
);
$MI_HOST = $this->ConfigModels->Value('MI_HOST');
 $tcpdf->write2DBarcode($MI_HOST.'CodeIgniter/ImprOrdenMang/'.$Nombre.'', 'QRCODE,Q', 90, 235, 30, 30, $style, 'C');
// set text shadow for effect
/*
$tcpdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,197,198), 'opacity'=>1, 'blend_mode'=>'Normal'));
 
//Set some substance to print
 */
$set_html = <<<EOD
 
 
<h3  style="text-align: center; text-decoration: underline;">Orden De Ttrabajo Manguera Hidráulica </h3>
<h5  style="text-align: right; ">Fecha:   $Fecha</h5>
<h4  style="text-align: center;">SMI $CodigoPlanilla/$Year</h4>

<br/>
<br/>
<h4  style="text-align: center; ">EMPRESA/USUARIO: $Armador2 </h4>
<br/>
<br/>
<br/>
<span><FONT SIZE="9"><b>1.- Manguera Hidráulica </b></FONT></span>
<br>
<table   border="1" >

<tr>
<td ><h5  style="text-align: LEFT; ">Fabricación de Manguera Hidráulica De $Cantidad Metros  </h5></td>
</tr>
</table>




<br/>
<br/>


<h5  style="text-align: LEFT; ">Observacion: $Obs </h5>

 
EOD;

//Print content utilizing writeHTMLCell()
$tcpdf->writeHTMLCell(0, 0, '', '', $set_html, 0, 1, 0, true, '', true);
$tcpdf->SetFont("", 'B', 10);
$tcpdf->MultiCell(70,5, "
____________________________
      Cliente
      $Armador2
      Rut: $Rut
      
  ", 0, 'C', 0, 0, '', 235, true, 0, false, false, 35, 'M', false);



  $tcpdf->MultiCell(70,5, "____________________________
         Técnico 
         $NombreTe
        Rut: $RutTec
 ", 0, 'C', 0, 1, 125, 235, true, 0, false, false, 35, 'M', false);

 $tcpdf->SetFont("", '', 8);
 $MI_HOST = $this->ConfigModels->Value('MI_HOST');
$tcpdf->MultiCell(175,5, "Puede verificar la valides de este documiento en: ".$MI_HOST."Sistema/Orden/ Debe usar el Código: $Nombre ", 0, 'C', 0, 0, 10, 265, true, 0, false, false, 35, 'M', true);
$tcpdf->SetFont("", 'B', 10);

 switch (count($parametros)) { 
  
  case 0:
    break;
  case 1:
    $tcpdf->Output('Orden.pdf', 'I');
  break;
  case 2:
   if (Existe($Dir.'/ImprOrdenMang/') === false){
    CrearCarpeta($Dir.'/ImprOrdenMang/');
   
    
   }
   
    $tcpdf->Output($Dir.'/ImprOrdenMang/'.$Nombre.'.pdf', 'F');
    if( $FirmanteInterno != 'Nada' ){
      //$DatosArmador aqui enviamos los datos del Orden
      // actualizamos la fecha de vencimiento  a un ano 
      $this->ExtinguisherModels->GuardarActa($IdOrden,$Nombre);

    
       

       

       
        
    }
   
    
    header("Content-type: application/pdf");
    header("Content-Disposition: inline; filename=documento.pdf");
    $MI_HOST = $this->ConfigModels->Value('MI_HOST');
    readfile($MI_HOST.'ImprOrdenMang/'.$Nombre.'.pdf');
   
  
    return;
    
    break;
  }





//
// successfully created CodeIgniter TCPDF Integration
}

function BodyTabla($arr){
  
  $arrayTitulo = [];
  $arrayTituloImprimir = "";
  $posT =0;
  $arrayTituloImprimir ="<tr>";
  $Fi = "";
  foreach (  $arr[0] as $key => $val){
    $arrayTitulo[$posT] = $key;
    if($key=='Si' OR $key== 'No'){
      $arrayTituloImprimir=$arrayTituloImprimir.'<th ><FONT SIZE="8"><b>'.utf8_decode($key).'</b></FONT></th>';
      
    }else{
      $arrayTituloImprimir=$arrayTituloImprimir.'<th  ><FONT SIZE="8"><b>'.utf8_decode($key).'</b></FONT></th>';
    }
   
    $posT++;
  }
  $arrayTituloImprimir =$arrayTituloImprimir."</tr>";
  foreach ($arr as $Fila){
    $Fi=  $Fi.'<tr>';
    $Colum= '';
 
    
         for( $i=0; $i< count($arrayTitulo); $i++  ){
          foreach (  $Fila as $key => $val){
          if( $arrayTitulo[$i] ===$key){
            $Colum =  $Colum. '<td ><FONT SIZE="8"> '. $val.' </FONT></td>';
          }
        }
        }
    
    $Fi= $Fi.$Colum.'</tr>';
  }
return $arrayTituloImprimir.$Fi;
}

protected function middleware()
{
 return ['Sesion','Permisos'];
}
}
/* end ImprOrdenMangCtrl.php file for CodeIgniter TCPDF Integration */
?>