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

class UserDbCtrl 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'];

 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();
    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);
  }
  if ( !isset($Datos[3])) // validamos que venga la base de datos
  {
    header('Content-type: application/json; charset=utf-8');
    echo json_encode(array("Error"=>"Debe ingresar la Base de datos"));
    return ;
  }
  $Dir = Raiz(); 
  $Db =$Datos[3];
  $host = isset($Datos[4]) === true ?  $Datos[4] : DbHost;
  $passDb =  isset($Datos[5]) === true ?  $Datos[5] : DbPass;
  $UserDb =  isset($Datos[6]) === true ?  $Datos[6] : DbUser;
  // validamos que el login y el pass son correctos 
  $Login = array("Login"=>$Datos[1],"Password"=>$Datos[2]);
  $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;
   }
// nos aseguramos que existan los datos
$Datos[4]= encriptar($host);
$Datos[5]=  encriptar($passDb);
$Datos[6]= encriptar($UserDb);
// ingresamos los datos en nuestra tabla User 

$UserDbes= $this->UserDbModels->Add($Datos);
// luego de eso procedamos a cargar la informacion 
// para crear nuestra db

$this->myforge = $this->load->dbforge(configDB( $host,$UserDb, $passDb,$Db), TRUE);

$Creada = $this->myforge->create_database($Db);
$filePath   = $Dir.'db/'.'respaldo.sql';
restoreDatabaseTables($host, $UserDb, $passDb, $Db, $filePath);
// aqui cargamos la base de datos 
$this->db = $this->load->database(configDB($host,$UserDb,$passDb, $Db), TRUE);

$DatosEdit= array(0=>1,"Login"=>$Datos[1],"Password"=>$Datos[2]);

$UserDbesEdit= $this->UserModels->Edit($DatosEdit);


  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes);
}
     
private function Edit(){
  $Datos = $this->input->raw_input_stream;
  if(is_string($Datos) ===true){
    $Datos =  json_decode($Datos, true);
  }
  $UserDbes= $this->UserDbModels->Edit($Datos);
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes);
    
}

private function Delete($ID ){
  $UserDbes= $this->UserDbModels->Delete($ID[0]);
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes);
}

// aqui viene los metodos de buscar



private function Search($Arr =array() ){
  $UserDbes =array();
  switch (count($Arr)) 
  { case 0:
    $UserDbes= $this->UserDbModels->getUserDb();
    break;
    case 1: 
      $UserDbes = $this->UserDbModels->getUserDb($Arr[0]);
    break;
    case 2: 
      $UserDbes = $this->UserDbModels->getUserDbLimite($Arr[0],$Arr[1]);
    break; 
    case 4: 
      $UserDbes = $this->UserDbModels->getUserDbLimiteOrden($Arr[0],$Arr[1],$Arr[2],$Arr[3]);
    break; 
    case 5: 
      $UserDbes = $this->UserDbModels->getUserDbLimiteOrdenColumnas($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($UserDbes); 
}

private function Buscar1 ($Arr = array()){
  $UserDbes =array();
  switch (count($Arr)) 
  {
    case 1: 
      $UserDbes = $this->UserDbModels->getUserDbFiltro(urldecode($Arr[0]));
    break;
    case 3: 
      $UserDbes = $this->UserDbModels->getUserDbFiltroLimite(urldecode($Arr[0]),$Arr[1],$Arr[2]);
    break; 
    case 5: 
      $UserDbes = $this->UserDbModels->getUserDbFiltroLimiteOrden(urldecode($Arr[0]),$Arr[1],$Arr[2],$Arr[3],$Arr[4]);
   break; 
   case 6: 
    $UserDbes = $this->UserDbModels->getUserDbFiltroLimiteOrdenColumnas(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($UserDbes); 
  
}
private function Buscar2 ($Arr =array()){
  $UserDbes =array();
  $UserDbes = $this->UserDbModels->getUserDbFiltroColumnas(urldecode($Arr[0]),urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes); 
}

private function Buscar3 ($Arr =array()){
  $UserDbes =array();
    $UserDbes= $this->UserDbModels->  getUserDbIdColum($Arr[0],urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes); 
}
private function Buscar4 ($Arr = array()){
  $UserDbes =array();
    $UserDbes= $this->UserDbModels->getUserDbLimiteColum($Arr[0],$Arr[1],urldecode($Arr[2]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes); 
}
private function Buscar5 ($Arr =  array()){
  $UserDbes =array();
  $UserDbes = $this->UserDbModels->getUserDbFiltroLimitesColumnas(urldecode($Arr[0]),$Arr[1],$Arr[2],urldecode($Arr[3]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes); 

}

private function Pdf(){

  $UserDbes= $this->UserDbModels->getUserDb();
  $UserDbes = str_replace('C\u00c3\u00b3digo','Codigo',json_encode($UserDbes));
  $UserDbes = str_replace('Tel\u00c3\u00a9fono','Telefono',$UserDbes);
  $UserDbes = str_replace('Direcci\u00c3\u00b3n','Direccion',$UserDbes);
  $UserDbes= json_decode($UserDbes);
 $bodytUserDbes= $this->BodyTabla($UserDbes,array('Codigo','Rut',"Nombre","Apellidos",'Telefono','Direccion',"Comuna"));
 //echo json_encode($UserDbes);
// return;
  $tcpdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
  $tcpdf->SetAuthor('segmarind');
  $tcpdf->SetTitle('Reporte de UserDbes');
  $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();
$set_html = <<<EOD
 
 

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

<br/>

<br>
<br/>
<br/>

<br>
<br>



<table   border="1" >

<tr>
<th ><FONT SIZE="8"><b> Código</b></FONT></th>
<th ><FONT SIZE="8"><b> Rut</b></FONT></th>
<th ><FONT SIZE="8"><b> Nombre</b></FONT></th>
<th ><FONT SIZE="8"><b> Apellidos </b></FONT></th>
<th ><FONT SIZE="8"><b> Teléfono</b></FONT></th>
<th ><FONT SIZE="8"><b> Dirección</b></FONT></th>
<th ><FONT SIZE="8"><b> Comuna</b></FONT></th>
</tr>
$bodytUserDbes
</table> 
EOD;
$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 MetaData(){
  $UserDbes =array();
  $UserDbes = $this->UserDbModels->MetaData();
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($UserDbes); 
}

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

	
}