<?php
/**
 * Created by PhpStorm.
 * User: JairMunoz
 * Date: 24/07/2018
 * Time: 4:45 PM
 */

require_once APPPATH . '/libraries/REST_Controller.php';
require_once APPPATH . '/libraries/JWT.php';

require_once APPPATH . '/libraries/BeforeValidException.php';
require_once APPPATH . '/libraries/ExpiredException.php';
require_once APPPATH . '/libraries/SignatureInvalidException.php';

use \Firebase\JWT\JWT;

class GD_Controller extends REST_Controller
{
    private $headers;
    public $certAut;

    function __construct()
    {
        parent::__construct();
        # $this->load->library('jwt');
        #var_dump(apache_request_headers());# apache_request_headers();
    }

    public function genToken($user_data = [])
    {
        $aud = AudGetRealIP();
        $tk = [
            'data' => $user_data,
            'aud' => $aud,
            'iat' => time(),
            'exp' => time() +(60 * 30)
        ];
        return JWT::encode($tk, $this->config->item('encryption_key'));
    }

    public function auth()
    {
        // Configure limits on our controller methods
        // Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
        $this->methods['users_get']['limit'] = 500; // 500 requests per hour per user/key
        $this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key
        $this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key
        //JWT Auth middleware
        $headers = $this->input->get_request_header('Jwt');
        #echo '-'. $headers;
        $kunci = $this->config->item('encryption_key'); //secret key for encode and decode
        $token = "token";
        if (!empty($headers)) {
            if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
                $token = $matches[1];
            }
        }

        try {
            $decoded = JWT::decode($token, $kunci, array('HS256'));
            $this->certAut = $decoded->data;
            #var_dump($this->user_data);
        } catch (Exception $e) {
            $invalid = [
                'error' => true,
                'msg' => $e->getMessage(),
                'errores' => 'Session expirada',
            ];
            $this->response($invalid, 401);//401
        }
    }

    public function viewFile($archivo){
        $this->output
            ->set_content_type('application/pdf')
            ->set_output(file_get_contents($archivo));
    }

    public function respuesta($data = NULL, $http_code = NULL)
    {
        $this->output->set_header('Jwt:' . $this->genToken($this->certAut));
        $this->response($data, $http_code);
    }
}