<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class UserCtrl extends MY_Controller {
  public function __construct($config = 'rest')
  {
    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();
      $this->load->library('Pdf');
  }

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

  $method = $_SERVER['REQUEST_METHOD'];
  header('Access-Control-Allow-Origin: *');
  header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, 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');
 switch ($met)  
 { case 'Buscar1':
     $this->Buscar1($parametros); 
     break;
   case 'Buscar2': 
     $this->Buscar2($parametros);   
   break;
   case 'Buscar3': 
     $this->Buscar3($parametros); 
   break; 
   case 'Buscar4': 
    $this->Buscar4($parametros);
   break; 
   case 'Buscar5': 
    $this->Buscar5($parametros);
   break; 
   case "MetaData":
    $this->MetaData($parametros);
   break;
   case "Pdf":
    $this->Pdf($parametros);
    break;
    case "ExportExcel":
      $this->ExportExcel($parametros);
      break;
    
 }
 if($met ==="index"){

  switch ($method)  
  { case 'PUT':
      $this->Edit(); 
    break;
    case 'POST': 
      $this->Add();
    break;
    case 'GET': 
      $this->Search($parametros);
 break;
    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 = count($_POST) ===0 ? $this->input->raw_input_stream :  $this->input->post();
  if(is_string($Datos) ===true){
    $Datos =  json_decode($Datos, true);
  }
  $Datos2 = array();
 

    // aqui ingresamos la informacion a la data general de usuarios
   
    $Login = array("Login"=>$Datos["6"],"Password"=>$Datos["7"]);
    $Login =  json_decode(json_encode( $Login),true);
    $BuscarLogin= $this->LoginModels->Login($Login);
     if($BuscarLogin[0] != FALSE){
      header('Content-type: application/json; charset=utf-8');
      echo json_encode(array("Error"=>"Cambiar Credenciales"));
      return;
     }
    
    $Usuarios= $this->UserModels->Add($Datos);
    if (DbMultiple== TRUE){
      if(!is_array($Usuarios)){
        $DatosDB= $this->UserDbModels->getUserDb($this->UserDB);
        $Datos2 = array(1=>$Datos["6"],2=>$Datos["7"],3=>$DatosDB[0]->DB,4=>$DatosDB[0]->Host,5=>$DatosDB[0]->password_db,6=>$DatosDB[0]->user_db,7=>$Datos["5"],8=>$Usuarios);
       $Datos2= json_decode(json_encode( $Datos2),true);
       $Usuarios2= $this->UserDbModels->Add( $Datos2);
      }
    }
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios);
}
     
private function Edit(){
  $Datos = $this->input->raw_input_stream;
  if(is_string($Datos) ===true){
    $Datos =  json_decode($Datos, true);
  }
  $Datos2 = array();
  if (DbMultiple== TRUE){
       $poli = false;
      $DatosDB= $this->UserDbModels->getUserDb($this->UserDB);
      $DatosDB= $this->UserDbModels->getUserDbFiltro("sCodigo"."^".$Datos["0"]."|"."DB"."^".$DatosDB[0]->DB);
      $Datos2[0] = $DatosDB[0]->ID;
      if (isset($Datos["6"])){
        $Datos2[1] = $Datos["6"];
        $poli = true;
      }else{
     //   $Datos2[1] = $DatosDB[0]->Login;
      }
      if (isset($Datos["7"])){
        $Datos2[2] = $Datos["7"];
        $poli = true;
      }else{
       // $Datos2[2] = $DatosDB[0]->Password;
      }
      if (isset($Datos["5"])){
        $Datos2[7] = $Datos["5"];
        $poli = true;
      }else{
      //  $Datos2[7] = $DatosDB[0]->Correo;
      }
      if ( $poli == true){
        $Datos2= json_decode(json_encode( $Datos2),true);
        $Usuarios2= $this->UserDbModels->Edit( $Datos2);
      }
    

  }

  $Usuarios= $this->UserModels->Edit($Datos);
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios);
    
}

private function Delete($ID ){
  if (DbMultiple== TRUE){
    $DatosDB= $this->UserDbModels->getUserDb($this->UserDB);
    $DatosDB= $this->UserDbModels->getUserDbFiltro("sCodigo".$this->Separador.$ID[0]."|"."DB".$this->Separador.$DatosDB[0]->DB);
    $Usuarios2= $this->UserDbModels->Delete($DatosDB[0]->ID);
  }
  $Usuarios= $this->UserModels->Delete($ID[0]);
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios);
}

// aqui viene los metodos de buscar



private function Search($Arr =array() ){
  $Usuarios =array();
  switch (count($Arr)) 
  { case 0:
    $Usuarios= $this->UserModels->getUser();
    break;
    case 1: 
      $Usuarios = $this->UserModels->getUser($Arr[0]);
    break;
    case 2: 
      $Usuarios = $this->UserModels->getUserLimite($Arr[0],$Arr[1]);
    break; 
    case 4: 
      $Usuarios = $this->UserModels->getUserLimiteOrden($Arr[0],$Arr[1],$Arr[2],$Arr[3]);
    break; 
    case 5: 
      $Usuarios = $this->UserModels->getUserLimiteOrdenColumnas($Arr[0],$Arr[1],$Arr[2],$Arr[3],urldecode($Arr[4]));
   break; 
   default: 
   echo json_encode( "Error" );
   break; 
  }
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
}

private function Buscar1 ($Arr = array()){

  $Usuarios =array();
  switch (count($Arr)) 
  {
    case 1: 
      
     
      $Usuarios = $this->UserModels->getUserFiltro(urldecode($Arr[0]));
    break;
    case 3: 
      $Usuarios = $this->UserModels->getUserFiltroLimite(urldecode($Arr[0]),$Arr[1],$Arr[2]);
    break; 
    case 5: 
      $Usuarios = $this->UserModels->getUserFiltroLimiteOrden(urldecode($Arr[0]),$Arr[1],$Arr[2],$Arr[3],$Arr[4]);
   break; 
   case 6: 
    $Usuarios = $this->UserModels->getUserFiltroLimiteOrdenColumnas(urldecode($Arr[0]),$Arr[1],$Arr[2],$Arr[3],$Arr[4],urldecode($Arr[5]));
    break; 
   default: 
   echo json_encode( $Arr );
   break; 
  }
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
  
}
private function Buscar2 ($Arr =array()){
  $Usuarios =array();
  $Usuarios = $this->UserModels->getUserFiltroColumnas(urldecode($Arr[0]),urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
}

private function Buscar3 ($Arr =array()){
  $Usuarios =array();
    $Usuarios= $this->UserModels->  getUserIdColum($Arr[0],urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
}
private function Buscar4 ($Arr = array()){
  $Usuarios =array();
    $Usuarios= $this->UserModels->getUserLimiteColum($Arr[0],$Arr[1],urldecode($Arr[2]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
}
private function Buscar5 ($Arr =  array()){
  $Usuarios =array();
  $Usuarios = $this->UserModels->getUserFiltroLimitesColumnas(urldecode($Arr[0]),$Arr[1],$Arr[2],urldecode($Arr[3]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 

}


private function MetaData(){
  $Usuarios =array();
  $Usuarios = $this->UserModels->MetaData();
  
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($Usuarios); 
}

private function Pdf(){

  $datausuarios = $this->UserModels->getUserFiltroColumnas("s","s1|2|3|4|5|10");
  //echo  json_encode($datausuarios[0]);
  $arrayTitulo = [];
  $arrayTituloImprimir = "";
  $posT =0;
  $arrayTituloImprimir ="<tr>";
  foreach (  $datausuarios[0] as $key => $val){
    $arrayTitulo[$posT] = $key;
    $arrayTituloImprimir=$arrayTituloImprimir.'<th ><FONT SIZE="8"><b>'.utf8_decode($key).'</b></FONT></th>';
    $posT++;
  }  
  $arrayTituloImprimir =$arrayTituloImprimir."</tr>";
  $bodytusuario= $this->BodyTabla($datausuarios,$arrayTitulo);
  $tcpdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
  $tcpdf->SetAuthor('segmarind');
  $tcpdf->SetTitle('Reporte de Usuarios');
  $tcpdf->SetSubject('segmarind');
  $tcpdf->SetKeywords('TCPDF, PDF, segmarind, test, guide');
  $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));
  $tcpdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $tcpdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
  $tcpdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
  $tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
  $tcpdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $tcpdf->SetFooterMargin(PDF_MARGIN_FOOTER);
  $tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
  $tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
if (@file_exists(dirname(__FILE__).'/lang/eng.php'))
{
// optional
require_once(dirname(__FILE__).'/lang/eng.php');
// optional
$tcpdf->setLanguageArray($l);
}
 
$tcpdf->setFontSubsetting(true);
$tcpdf->AddPage();
// Mi contenido
$set_html = <<<EOD
 
 

<h3  style="text-align: center;">Reporte De Usuarios</h3>

<br/>

<br>
<br/>
<br/>

<br>
<br>



<table   border="1" >

$arrayTituloImprimir
$bodytusuario
</table> 
EOD;

//Print content utilizing writeHTMLCell()
$tcpdf->writeHTMLCell(0, 0, '', '', $set_html, 0, 1, 0, true, '', true);


$tcpdf->Output('tcpdfexample-onlinecode.pdf', 'I');
  return ;

}
function BodyTabla($arr,$Titulos){
 
  $Fi = "";
  foreach ($arr as $Fila){
    $Fi=  $Fi.'<tr>';
    $Colum= '';
 
    
         for( $i=0; $i< count($Titulos); $i++  ){
          foreach (  $Fila as $key => $val){
          if( $Titulos[$i] ===$key){
            $Colum =  $Colum. '<td ><FONT SIZE="8"> '. utf8_decode($val).' </FONT></td>';
          }
        }
        }
    
    $Fi= $Fi.$Colum.'</tr>';
  }
return $Fi;
}
 private function ExportExcel(){
  $datausuarios = $this->UserModels->getUserFiltroColumnas("s","s1|2|3|4|5|10");
  //echo  json_encode($datausuarios[0]);
  $arrayTitulo = [];
  $arrayTituloImprimir = "";
  $posT =0;
  foreach (  $datausuarios[0] as $key => $val){
    $arrayTitulo[$posT] = $key;
    $posT++;
  }  
  Excel($datausuarios,$arrayTitulo,"Usuarios");
  return;
 }


    protected function middleware()
    {
     
       return ['Sesion','Permisos'];
    }

	
}