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

class ChangePasswordModels extends CI_Model
{
    private $Tabla = "usuarios";
    private $Delimitador= "|";
    private $Separador = "^";
    private $CamposInternos = ['Status'=>'Status', 'Rut'=>'Rut','Apellidos'=>'Apellidos','Telefono'=>'Telefono','Direccion'=>'Direccion','Correo'=>'Correo','Nivel'=>'Nivel','Cd_Tienda'=>"Cd_Tienda",'Codigo'=>'Codigo','Fecha_Egreso'=>'Fecha_Egreso','Login'=>'Login','FechaNa'=>'FechaNa','Fecha_in'=>'Fecha_in'];
    private $Select = null;
    private $SoloLetras = [];
    private $CamposNecesarios = ['Password'=>'Password', 'Nombres'=>'Nombres'];
    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->db->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;
    }
 

    
   
 
    
    private function total(){
        $this->db->select("count(*) As Total");
        return  $this->db->get($this->Tabla)->result();
    }
  
    
    
    

    
   
// desde aqui comianza la configuracion

    private function Mascara($Clave){
        $ArrayChangePassword["Codigo"]=  utf8_encode('Código');
        $ArrayChangePassword["Nombres"]= "Clave";
        $ArrayChangePassword["Password"]= "Repetir Clave";
        $ArrayChangePassword["Apellidos"]="Apellido";
        $ArrayChangePassword["Telefono"]= utf8_encode('Teléfono');
        $ArrayChangePassword["Fecha_in"]="Ingreso" ;
        $ArrayChangePassword["FechaNa"]= "Nacimiento";
        $ArrayChangePassword["Fecha_Egreso"]="Egreso";
        $ArrayChangePassword["Cd_Tienda"]="Tienda" ;
if (isset($ArrayChangePassword[$Clave])){
return $ArrayChangePassword[$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;
        } 

        }
        if($meta[$clave]["nombre"]=== "Password"){
            $ArrayDatos[$meta[$clave]["nombre"]] = $verificar;
        }
      

          next($Datos);
          }
          return $ArrayDatos;     
}

public function Edit($datos){
   
    $ArrayDatos= $this->validar($datos);
    $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 ;
  }
    $ArrayDatos["Codigo"]=$ID;
  
    if( $ArrayDatos === false){
        return array("Error"=>"Verificar Datos");
    } 
  
    if (isset($ArrayDatos["Rut"])){
      
        $ArrayDatos["Rut"]=  $this->FormatoRut($ArrayDatos["Rut"]);
      
    }
  

    if (!isset($ArrayDatos["Codigo"])){
        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));
    }else{
        return array("Error"=>"Debe Enviar el id del Usuario");
    }
 

    
   $where = "Codigo = '".$ArrayDatos["Codigo"]."' ";
    return $this->db->update($this->Tabla, $ArrayDatos, $where );
}


private function FormatoRut($Rut){
    $newRut = str_replace(".", "", $Rut);
    $newRut = str_replace("-", "", $newRut);
    $Ultimo = substr($newRut, -1);
    $rest = substr($newRut, 0, -1);
   
    return $rest."-".$Ultimo;
   }
   Public function MetaData($Mascara = true){
      
    $meta = $this->db->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 === "longtext" || $field->type === "varchar" || $field->type === "date" ? "a":"n",       
        "disabled"=> false, 
        "len"=> $field->type === "date"? 10 :$field->max_length,         
        "primary"=>$field->name =="Rut",  
        "type"=> $field->type === "date"? $field->type : "password",    
        "necessary"=> isset($this->CamposNecesarios[$field->name]), 
        "modified"=> false,  
        "Buscar" => $field->name =="Rut",
    ];
    
    if(isset($this->SoloLetras[$field->name])){
        $meta2[$id]["Tipo"] = $this->SoloLetras[$field->name];
    }
   }
   if (isset($this->Select[$field->name])){
    $id= (string)$i;
    $meta3[$id] = [
        "name"=> $this->Mascara($field->name),
        "value"=> "",     
        "disabled"=> false,      
        "primary"=>$field->name =="Rut",
        "date"=>$this->Select[$field->name]["date"],
        "option"=>$this->Select[$field->name]["option"],
        "filter"=>$this->Select[$field->name]["filter"],
        "Datos"=>$this->Select[$field->name]["Datos"],
        "necessary"=> $this->Select[$field->name]["necessary"], 
        "modified"=> false,  
    ];
   
   } 
   $Total = $this->total();
   $meta2["Total"] = $Total[0]->Total;
   $meta2["Select"]= null;
   $meta2["Delimitador"] = $this->Delimitador;
   $meta2["Separador"]  = $this->Separador;
}else{
    $meta2[$i] = ["nombre"=> $field->name, "len"=> $field->max_length, "type"=> $field->type, "Obligatorio"=>isset($this->CamposNecesarios[$field->name]),"ID"=>$i];
   
}

$i++;
}

   return   $meta2;
} 

}
