<?php
/**
 * Created by Prointel Putumayo.
 * User: Jair Muñoz
 * Date: 23/07/18
 * Time: 22:18
 */

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

use \Firebase\JWT\JWT;

#require APPPATH . 'libraries/REST_Controller.php';

class Aut extends GD_Controller
{
    private $respuesta;
    private $error_rta;

    function __construct()
    {
        // Construct the parent class
        parent::__construct();
        $this->load->database();
        $this->error_rta = GD_Controller::HTTP_OK;
    }

    public function aut_post()
    {
        try {
            # var_dump($_POST);
            $this->load->model('auth_model', 'model_aut');
            $usuario = $this->input->post('usuario');
            $pass = $this->input->post('pwd');

            if (empty($pass) OR empty($usuario)) {
                $this->error_rta = GD_Controller::HTTP_BAD_REQUEST;
                throw new Exception('Usuario/Contraseña son requeridos', 404);
            }

            $user_data = $this->model_aut->auth($usuario, encryptar($pass));

            if (is_null($user_data)) {
                $this->error_rta = GD_Controller::HTTP_NOT_FOUND;
                throw new Exception('Credenciales invalidas', 404);
            }
            $aud = AudGetRealIP();
            $tk = [
                'data' => $user_data,
                'aud' => $aud,
                'iat' => time(),
                'exp' => time() + (60 * 30)
            ];
            #$this->load->library('jwt');

            #$jwt = $this->jwt->encode($tk, $this->config->item('encryption_key'));
            $jwt = JWT::encode($tk, $this->config->item('encryption_key'));
            $this->respuesta = ['msg' => '', 'err' => false, 'tk' => $jwt];

        } catch (Exception $exc) {
            $this->respuesta = [
                'msg' => $exc->getMessage(),
                'err' => true,
                'data' => null
            ];
        }
        $this->response($this->respuesta, $this->error_rta); // OK (200) being the HTTP response code
    }

    public function menu_get()
    {
        $this->auth();
        #echo $this->certAut->idu," - ", $this->certAut->ide_rol;
        #var_dump($this->certAut);
        $this->load->model('auth_model', 'auth');
        $menu = $this->auth->menu($this->certAut->idu, $this->certAut->ide_rol);
        #echo json_encode($menu);

        $this->response($menu, $this->error_rta); // OK (200) being the HTTP response code
    }

}
