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

class LoginCtrl 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->UseToken = $this->ConfigModels->Value('UseToken');
  }
	public function index()
	{
        
       
        
    if( $this->UseToken != TRUE ){
      $data = array(
        "User"=> "id", //Guardaremos el user o el id si se a logeado correctamenteo;
         "intentos"=> 0, // valor de intentos al loguearse
         "login" => true
    );
    $this->session->set_userdata($data); //guardamos la session
    $this->session->userdata("login");

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

        $method = $_SERVER['REQUEST_METHOD'];
         
        switch ($method)  
        { 
          case 'POST': 
          $this->Login();
          break;
          case 'GET': 
            $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 ;
        }
            echo json_encode( $ID );
            break; 
          case 'DELETE': 
            $this->Delete(); 
          break; 
         default: 
         echo json_encode( "Error" );
         break; 
        }
       }

      private function Login(){
        $Token = "";
        $Datos = count($_POST) ===0 ? $this->input->raw_input_stream :  $this->input->post();
        if(is_string($Datos) ===true){
            $Datos =  json_decode($Datos, true);
          }
         
          $Usuarios= $this->LoginModels->Login($Datos);
          if(isset($this->session)){
            if (!$this->session->has_userdata("login")) {
            
        
  
              if( $Usuarios[0] === false  ){
                if( $this->UseToken== TRUE ){
                  $login=   array(
                    "User"=> null, 
                     "intentos"=> 0, 
                     "login" => false);
                  echo(json_encode($login));
                  return ;
                }
                  if($this->session->userdata("login")!==false){
                      $data = array(
                          "User"=> null, 
                           "intentos"=> 0, 
                           "login" => false
                      );
                      if( $this->UseToken == TRUE ){
                       return FALSE;
                      }else {
                        $this->session->set_userdata($data);
                      }
                      
                     
                     
                  }
                 
              }else{
                if( $this->UseToken == TRUE ){
                  if (!isset($Usuarios[1])){
                    $Token=   GenerarToken( $Usuarios[0], 9);
                  }else{
                    $Token=   GenerarToken( $Usuarios[0], 9,$Usuarios[1]);
                  }
                  
                  
                }else{
                  if (!isset($Usuarios[1])){
                    if (!isset($Usuarios[1])){
                      $data = array(
                        "User"=> $Usuarios[0], 
                         "intentos"=> 0, 
                         "login" => true
                    );
                    }else{
                      $data = array(
                        "User"=> $Usuarios[0], 
                         "intentos"=> 0, 
                         "login" => true,
                         "DB"=> $Usuarios[1]
                    );
                    }
                  }else{
                    $data = array(
                      "User"=> $Usuarios[0], 
                       "intentos"=> 0, 
                       "login" => true,
                       "DB"=> $Usuarios[1]
                  );
                  }
                 
                $this->session->set_userdata($data);
                }
                
  
              }
          
             
          }
          }else{
            if( $Usuarios[0] === false  ){
           $login=   array(
                "User"=> null, 
                 "intentos"=> 0, 
                 "login" => false);
              echo(json_encode($login));
              return ;
            }else{
              if( $this->UseToken == TRUE ){
                if (!isset($Usuarios[1])){
                  $Token=   GenerarToken( $Usuarios[0], 9);
                }else{
                  $Token=   GenerarToken( $Usuarios[0], 9,$Usuarios[1]);
                }
               
              }
            
            }
         
          }

        if(  $Token!= ""){
          echo json_encode(array("Token"=> $Token, "User"=>$Usuarios[0]));
         return; 
        }
          
          $Status=  $this->session->userdata("login");
          if($Status=== false &&  $Usuarios[0] === false){
              $intentos =  $this->session->userdata("intentos");
              $intentos++;
            $this->session->set_userdata('intentos',   $intentos);
            echo json_encode(array("Intentos"=>$intentos)); 
            return;
          }
          if($Usuarios[0] !== false && $Status ===false){
            $this->session->set_userdata('login', true);
            $this->session->set_userdata('User', $Usuarios[0]);
          }

         
          
               echo json_encode(array("User"=>$Usuarios[0]));
        return;
      } 
      private function Delete()
      {
        if( $this->UseToken != TRUE ){
        $this->session->set_userdata('login',false);
        $this->session->sess_destroy();
        header('Content-type: application/json; charset=utf-8');
        echo json_encode("Session cerrada"); 
        }
      }


}