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

class DataBaseCtrl 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');
      $this->load->dbutil();
      $this->load->helper('file');
  }
  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->CreateDb2();
    echo('Hola');
    //  $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);
  }

    $DataBasees= $this->DataBaseModels->Add($Datos);

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

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

// aqui viene los metodos de buscar



private function Search($Arr =array() ){
  $DataBasees =array();
  switch (count($Arr)) 
  { case 0:
    $DataBasees= $this->DataBaseModels->getDataBase();
    break;
    case 1: 
      $DataBasees = $this->DataBaseModels->getDataBase($Arr[0]);
    break;
    case 2: 
      $DataBasees = $this->DataBaseModels->getDataBaseLimite($Arr[0],$Arr[1]);
    break; 
    case 4: 
      $DataBasees = $this->DataBaseModels->getDataBaseLimiteOrden($Arr[0],$Arr[1],$Arr[2],$Arr[3]);
    break; 
    case 5: 
      $DataBasees = $this->DataBaseModels->getDataBaseLimiteOrdenColumnas($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($DataBasees); 
}

private function Buscar1 ($Arr = array()){
  $DataBasees =array();
  switch (count($Arr)) 
  {
    case 1: 
      $DataBasees = $this->DataBaseModels->getDataBaseFiltro(urldecode($Arr[0]));
    break;
    case 3: 
      $DataBasees = $this->DataBaseModels->getDataBaseFiltroLimite(urldecode($Arr[0]),$Arr[1],$Arr[2]);
    break; 
    case 5: 
      $DataBasees = $this->DataBaseModels->getDataBaseFiltroLimiteOrden(urldecode($Arr[0]),$Arr[1],$Arr[2],$Arr[3],$Arr[4]);
   break; 
   case 6: 
    $DataBasees = $this->DataBaseModels->getDataBaseFiltroLimiteOrdenColumnas(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($DataBasees); 
  
}
private function Buscar2 ($Arr =array()){
  $DataBasees =array();
  $DataBasees = $this->DataBaseModels->getDataBaseFiltroColumnas(urldecode($Arr[0]),urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($DataBasees); 
}

private function Buscar3 ($Arr =array()){
  $DataBasees =array();
    $DataBasees= $this->DataBaseModels->  getDataBaseIdColum($Arr[0],urldecode($Arr[1]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($DataBasees); 
}
private function Buscar4 ($Arr = array()){
  $DataBasees =array();
    $DataBasees= $this->DataBaseModels->getDataBaseLimiteColum($Arr[0],$Arr[1],urldecode($Arr[2]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($DataBasees); 
}
private function Buscar5 ($Arr =  array()){
  $DataBasees =array();
  $DataBasees = $this->DataBaseModels->getDataBaseFiltroLimitesColumnas(urldecode($Arr[0]),$Arr[1],$Arr[2],urldecode($Arr[3]));
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($DataBasees); 

}

private function Pdf(){

  $DataBasees= $this->DataBaseModels->getDataBase();
  $DataBasees = str_replace('C\u00c3\u00b3digo','Codigo',json_encode($DataBasees));
  $DataBasees = str_replace('Tel\u00c3\u00a9fono','Telefono',$DataBasees);
  $DataBasees = str_replace('Direcci\u00c3\u00b3n','Direccion',$DataBasees);
  $DataBasees= json_decode($DataBasees);
 $bodytDataBasees= $this->BodyTabla($DataBasees,array('Codigo','Rut',"Nombre","Apellidos",'Telefono','Direccion',"Comuna"));
 //echo json_encode($DataBasees);
// return;
  $tcpdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
  $tcpdf->SetAuthor('segmarind');
  $tcpdf->SetTitle('Reporte de DataBasees');
  $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 DataBasees</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>
$bodytDataBasees
</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(){
  $DataBasees =array();
  $DataBasees = $this->DataBaseModels->MetaData();
  header('Content-type: application/json; charset=utf-8');
  echo json_encode($DataBasees); 
}


private function CreateDb2(){
  $Dir = Raiz(); 

  $this->load->dbforge();
  if ($this->dbutil->database_exists('rodwin'))
{
  echo("Base de Datos ya existente");
 
}else {
  
}
return;
  $Creada = $this->dbforge->create_database("Rodwin");
  $dbHost     = 'localhost';
  $dbUsername = 'root';
  $dbPassword = '19432798';
  $dbName     = 'Rodwin';
  $filePath   = $Dir.'db/'.'respaldo.sql';

restoreDatabaseTables($dbHost, $dbUsername, $dbPassword, $dbName, $filePath);
}
private function CreateDb(){
    $this->load->dbforge();
   // $Creada = $this->dbforge->create_database("HolaMundo");
    
    $fields = array( 
        'blog_id' => array(
                'type' => 'INT',
                'constraint' => 5,
                'unsigned' => TRUE,
                'auto_increment' => TRUE
        ),
        'blog_title' => array(
                'type' => 'VARCHAR',
                'constraint' => '100',
                'unique' => TRUE,
        ),
        'blog_author' => array(
                'type' =>'VARCHAR',
                'constraint' => '100',
                'default' => 'King of Town',
        ),
        'blog_description' => array(
                'type' => 'TEXT',
                'null' => TRUE,
        ),
);
//$this->dbforge->add_field($fields);
//$this->dbforge->add_key('blog_id', TRUE);
// gives PRIMARY KEY `blog_id` (`blog_id`)
//$this->dbforge->create_table('Rodwin');
$prefs = array(
  'tables'        => array(),   // Listado de tablas.
  'ignore'        => array(),                     // Listado de tablas a omitir
  'format'        => 'zip',                       // gzip, zip, txt
  'filename'      => 'backup.zip',                // Nombre del fichero - SOLAMENTE PARA FICHEROS ZIP
  'add_drop'      => TRUE,                        // Si agregar la sentencia DROP TABLE al backup
  'add_insert'    => TRUE,                        // Si agregar la sentencia INSERT al backup
  'newline'       => "\n"                         // Salto de línea
);
//print_r($this->dbutil);
//return;

$prefs = array(
  'format'      => 'txt',            
  'filename'    => 'mybackup.sql', );
  $backup = $this->dbutil->backup($prefs);
$path=$this->config->base_url()."database/";
$this->load->helper('file');
write_file($path, $backup); 
$this->load->helper('download');
force_download('mybackup.gz', $backup);
}
    protected function middleware()
    {
        return [];
      //return ['Sesion','Permisos'];
    }

	
}