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

class UserDbModels extends CI_Model

{
    public function __construct()
    {
     
       
        parent::__construct();
        if(DbMultiple==TRUE){
            $this->db2 = $this->load->database(configDB(DbHost,DbUser,DbPass,'usercontrol'), TRUE);
        }
        
    }
    private $Tabla = "user";
    private $Delimitador= "|";
    private $Separador = "^";
    private $CamposInternos = ['Status'=>'Status', 'ID'=>'ID'];
    private $Select = null;
    private $SoloLetras = [];
    private $CamposNecesarios = ['Login'=>"Login", 'Password'=>"Password","Correo"=>"Correo","Codigo"=>"Codigo"];
    private function Filtros($Filtros){
        $Filtros= str_replace('ø','/',$Filtros);
        $arr1 = explode($this->Delimitador,$Filtros);
        $array_num = count($arr1);
        for ($i = 0; $i < $array_num; ++$i){
           
            $posicion_coincidencia = strpos($arr1[$i], $this->Separador);
            if(  $posicion_coincidencia != FALSE ){
              $Array2 = explode($this->Separador,$arr1[$i]);
              $Array2[0]= $this->columna($Array2[0]);
              $arr1[$i] =  $Array2;
            }else {
                $arr1[$i]= array("Todo", $arr1[$i]);
            }
        }
        return  $arr1;
    }

   
    private  function columna($id = null,$Mascara = false){
        $fields = $this->db2->list_fields($this->Tabla);
        if($id === null){
          
            $array_num = count($fields);
            for ($i = 0; $i < $array_num; ++$i){
                $fields[$i] =  $fields[$i]. " AS ". $this->Mascara($fields[$i]);
            }
            return $fields;

        }

        if(is_numeric($id)===false){
            $array_num = count($fields);
            for ($i = 0; $i < $array_num; ++$i){
                if($id === $fields[$i] ||  $this->Mascara($fields[$i]) === $id ){
                    if($Mascara=== false){
                        return $fields[$i];
                    }else{
                        return $fields[$i]. " AS ". $this->Mascara($fields[$i]);
                    }
                  
                }
              
            }
            return $fields[0];
        }else{

       

        if($Mascara === false){
            if(intval($id) < count($fields) && intval($id) > 0 ){
                return  $fields[intval($id)];
              }else{
                return $fields[0];
              }
        }else{
            if(intval($id) < count($fields) && intval($id) > 0 ){
                return  $fields[intval($id)]. " AS ". $this->Mascara($fields[intval($id)]);
              }else{
                return $fields[0]. " AS ". $this->Mascara($fields[0]);
              }        
        }
    }
       
    }
    private function Columnas($col = null,$Mascara = false){
          if($col=== null){
           $Arra =  $this->columna(null);
           return $Arra;
          }

        $Colu = substr($col, 1);
        $posicion_coincidencia = strpos($Colu, $this->Delimitador);
        if(  $posicion_coincidencia === FALSE ){
            $arr1 = str_split($Colu);
        }else{
            $arr1 = explode($this->Delimitador,$Colu);
        }
     
        $array_num = count($arr1);
        for ($i = 0; $i < $array_num; ++$i){
            $arr1[$i] =  $this->columna($arr1[$i],$Mascara);
        }
        return $arr1;
    }
    public function getUserDb($id=NULL)
    {
       
       if ($id === NULL){
        $this->db2->select($this->Columnas());
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo"))->result();
       }else{
           $Columna = $this->columna(0);
           $this->db2->select($this->Columnas());
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo", "$Columna"=>$id))->result();
       }
       
    }
    public function getUserDbLimite($Canti,$Desde){
        $this->db2->select($this->Columnas());
        
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo"),$Canti,$Desde)->result();
    }
    public function getUserDbLimiteOrden($Canti,$Desde,$Columna,$Orden){
        $Direccion ="Error en el Orden";
        $Direccion = $Orden ==="0" ? "ASC" :   $Direccion;
        $Direccion = $Orden ==="1" ? "DESC" :   $Direccion;
     
        if($Direccion ==="Error en el Orden" ) 
        {
            return array("Error"=> $Direccion);
        }
        $this->db2->select($this->Columnas());
        $this->db2->order_by($this->columna($Columna), $Direccion);
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo"),$Canti,$Desde)->result();
    }
    public function getUserDbLimiteOrdenColumnas($Canti,$Desde,$Columna,$Orden,$Columnas){
        $Direccion ="Error en el Orden";
        $Direccion = $Orden ==="0" ? "ASC" :   $Direccion;
        $Direccion = $Orden ==="1" ? "DESC" :   $Direccion;
        if($Direccion ==="Error en el Orden" ) 
        {
            return array("Error"=> $Direccion);
        }
        
       
     
        $this->db2->select($this->Columnas($Columnas,true));
        $this->db2->order_by($this->columna($Columna), $Direccion);
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo"),$Canti,$Desde)->result();
    }
    public function getUserDbIdColum($id,$Columnas){
  
        $this->db2->select($this->Columnas($Columnas,true));
        $Columna = $this->columna(0);
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo", "$Columna"=>$id))->result();
    }
    public function getUserDbLimiteColum($Canti,$Desde,$Columnas){
        $this->db2->select($this->Columnas($Columnas,true));
        return  $this->db2->get_where($this->Tabla,array("Status"=>"Activo"),$Canti,$Desde)->result();
    }
    public function getUserDbFiltro($Filtros){
       
        $Filtro = substr($Filtros, 1);
      
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
   
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
      
        $this->db2->select($this->Columnas());
     return  $this->db2->get($this->Tabla)->result();
      
    }
    private function total(){
        $this->db2->select("count(*) As Total");
        return  $this->db2->get($this->Tabla)->result();
    }
    public function getUserDbFiltroLimite($Filtros,$Canti,$Desde){
        $Filtro = substr($Filtros, 1);
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
      
        $this->db2->select($this->Columnas());
     return  $this->db2->get($this->Tabla,$Canti,$Desde)->result();
      
    }
    public function getUserDbFiltroLimiteOrden($Filtros,$Canti,$Desde,$Columna,$Orden){
        $Filtro = substr($Filtros, 1);
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
        $Direccion ="Error en el Orden";
        $Direccion = $Orden ==="0" ? "ASC" :   $Direccion;
        $Direccion = $Orden ==="1" ? "DESC" :   $Direccion;
        if($Direccion ==="Error en el Orden" ) 
        {
            return array("Error"=> $Direccion);
        }
        
       
     
        $this->db2->select($this->Columnas());
     $this->db2->order_by($this->columna($Columna), $Direccion);
     return  $this->db2->get($this->Tabla,$Canti,$Desde)->result();
      
    }
    public function getUserDbFiltroLimiteOrdenColumnas($Filtros,$Canti,$Desde,$Columna,$Orden,$Columnas){
        $Filtro = substr($Filtros, 1);
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
        $Direccion ="Error en el Orden";
        $Direccion = $Orden ==="0" ? "ASC" :   $Direccion;
        $Direccion = $Orden ==="1" ? "DESC" :   $Direccion;
        if($Direccion ==="Error en el Orden" ) 
        {
            return array("Error"=> $Direccion);
        }
        
       
     
     $this->db2->select($this->Columnas($Columnas,true));
     $this->db2->order_by($this->columna($Columna), $Direccion);
     return  $this->db2->get($this->Tabla,$Canti,$Desde)->result();
      
    }
    public function getUserDbFiltroColumnas($Filtros,$Columnas){
        $Filtro = substr($Filtros, 1);
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
        $this->db2->select($this->Columnas($Columnas,true));

     return  $this->db2->get($this->Tabla)->result();
      
    }

    public function getUserDbFiltroLimitesColumnas($Filtros,$Canti,$Desde,$Columnas){
        $Filtro = substr($Filtros, 1);
        $cont = 0;
      $arrayconsulta=  $this->Filtros($Filtro);
      $this->db2->where('Status',"Activo" ); 
      $array_num = count($arrayconsulta);
        for ($i = 0; $i < $array_num; ++$i){
           if($arrayconsulta[$i][0] != "Todo"){
            $this->db2->where($arrayconsulta[$i][0],$arrayconsulta[$i][1]);
           }else{
            $cont++;
           }
        }
        if($cont >0){
            $fields = $this->db2->list_fields($this->Tabla);
            $poli=false;
            for ($i = 0; $i < $array_num; ++$i){
            if($arrayconsulta[$i][0] === "Todo"){
                 for($e =0 ; $e <count( $fields)-1; ++$e )
                 {
                if( $poli===false){
                    $this->db2->like('('.$fields[$e],$arrayconsulta[$i][1] );
                    $poli= true; 
                }else{ 
                    $this->db2->or_like($fields[$e],$arrayconsulta[$i][1]);
                }
            }
            $this->db2->or_where($fields[count( $fields)-1].' LIKE',"'%".$arrayconsulta[$i][1]."%')",false );
            $this->db2->like('('."Status",$arrayconsulta[$i][1] );
               }
            }
            $this->db2->or_where('Status =',"'Activo')",false ); 
        }
        $this->db2->select($this->Columnas($Columnas,true));

     return  $this->db2->get($this->Tabla,$Canti,$Desde)->result();
      
    }
   
// desde aqui comianza la configuracion

    private function Mascara($Clave){
$ArrayUserDb["Codigo"]=  utf8_encode('Codigo');
$ArrayUserDb["ID"]= "ID";
if (isset($ArrayUserDb[$Clave])){
return $ArrayUserDb[$Clave];
}else{
return $Clave;
}
}

    private function verificarExistencia($dato,$Array)
    {
        $array_num = count($Array);
        for ($id = 0; $id < $array_num; ++$id){
            if($Array[$id]["nombre"] == $dato){
              return $id;
            }
        }
        return false;
    }
private function validar($Datos){
    $meta = $this->MetaData(false);
    $ArrayDatos = array();
    while (current($Datos)!==false) {
        $verificar = current($Datos);
        if(is_numeric(key($Datos))===false){
            $clave=  $this->verificarExistencia(key($Datos),$meta);
            if ($clave=== false){
                return false;
            }
        }else{
            $clave = intval(key($Datos));
        }
        
        if (!isset($meta[$clave])){
            end($Datos);
            return false;
        }else{
        if (intval($meta[$clave]["len"]) < strlen($verificar) && $meta[$clave]["len"]!= null ){
            end($Datos);
            return false;
        } 

        }
        $ArrayDatos[$meta[$clave]["nombre"]] = $verificar;

          next($Datos);
          }
          return $ArrayDatos;     
}
public function Add($datos){
        
    $ArrayDatos= $this->validar($datos);
    if( $ArrayDatos === false){
        return array("Error"=>"Verificar Datos");
    }
        
         foreach ($this->CamposNecesarios as $campo){
            if (!isset($ArrayDatos[$campo])){
                return array("Error"=>"Debe Enviar Campo $campo");
            }
         }
    
       
        //aqui debe haber una encriptacion 
        $ArrayDatos["Status"] = "Activo";
  

   $ArrayDatos["Password"]= password_hash( $ArrayDatos["Password"],PASSWORD_DEFAULT,array("cost"=>12));

    return $this->db2->insert($this->Tabla, $ArrayDatos);
 
}
public function Edit($datos){
   
    $ArrayDatos= $this->validar($datos);
    if( $ArrayDatos === false){
        return array("Error"=>"Verificar Datos");
    }
  
  
    if (!isset($ArrayDatos["ID"])){
        return array("Error"=>"Debe Enviar el id del Usuario");
    }
    if (isset($ArrayDatos["Password"])){
        //aqui debe haber una encriptacion 
        $ArrayDatos["Password"]= password_hash( $ArrayDatos["Password"],PASSWORD_DEFAULT,array("cost"=>12));
    }
    
   $Buscar = $this->getUserDbFiltro("sID".$this->Separador.$ArrayDatos["ID"]);
  
   if (count($Buscar)===0){
    return array("Error"=>"Usuarion No Existe");
   }else{
  
   $where = "ID = '".$ArrayDatos["ID"]."' ";
    return $this->db2->update($this->Tabla, $ArrayDatos, $where );

   }
}
public function Delete($ID){

   $Buscar = $this->getUserDbFiltro("sID".$this->Separador.intval($ID));
   if (count($Buscar)===0){
    return array("Error"=>"Usuarion No Existe");
   }else{
    $ArrayDatos["ID"] = intval($ID);
    $ArrayDatos["Status"] = "Inactivo";
  
   $where = "ID = '".$ArrayDatos["ID"]."' ";
    return $this->db2->update($this->Tabla, $ArrayDatos, $where );

   }
}

Public function MetaData($Mascara = true){
      
    $meta = $this->db2->field_data($this->Tabla);

    $meta2 =array();
    $meta3 = array();
    $i=0;
    foreach ($meta as $field)
{ 
if($Mascara=== true){
   
   if(!isset($this->CamposInternos[$field->name]) && !isset($this->Select[$field->name]) ){
    $id= (string)$i;
  
    $meta2[$id] = [
        "name"=> $this->Mascara($field->name),
        "value"=> $field->type === "date"? date("Y-m-d") : "" ,
        "Tipo"=>  $field->type === "text" || $field->type === "varchar" || $field->type === "date" ? "a":"n",       
        "disabled"=> false, 
        "len"=> $field->type === "date"? 10 :$field->max_length,         
        "primary"=>$field->name =="ID",  
        "type"=> $field->type === "date"? $field->type : "text",    
        "necessary"=> isset($this->CamposNecesarios[$field->name]), 
        "modified"=> false,  
        "Buscar" => $field->name =="ID",
    ];
    
    if(isset($this->SoloLetras[$field->name])){
        $meta2[$id]["Tipo"] = $this->SoloLetras[$field->name];
    }
   }
   if (isset($this->Select[$field->name])){
    $id= (string)$i;
    $meta3[$id] = [];
   
   } 
   $Total = $this->total();
   $meta2["Total"] = $Total[0]->Total;
   $meta2["Select"]= [];
   $meta2["Delimitador"] = $this->Delimitador;
   $meta2["Separador"]  = $this->Separador;
   $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->UserDbdata("UserDb") :  $Token ;
}else{
    $ID =   $Token== FALSE ? null :  $Token ;
} 


 
   
            $meta2["Permiso"] = 2;
        
       
}else{
    $meta2[$i] = ["nombre"=> $field->name, "len"=> $field->max_length, "type"=> $field->type, "Obligatorio"=>isset($this->CamposNecesarios[$field->name]),"ID"=>$i];
   
}

$i++;
}

   return   $meta2;
} 

public function DatosRepor(){
    $this->db2->join("tienda","usuarios.Cd_Tienda = tienda.Codigo","LEFT",false);
    $this->db2->where('usuarios.Status',$this->db2->escape("Activo"),false);
    $this->db2->select(array('usuarios.Rut AS Rut ','usuarios.Nombres As Nombres','usuarios.Apellidos AS Apellidos', 'usuarios.Telefono AS Telefono','usuarios.Correo AS Correo','usuarios.FechaNa AS FechaNa','tienda.NombreT AS NombreT' ),false); 
    $datausuarios= $this->db2->get("usuarios")->result();
    return $datausuarios;
}

}
