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

    require APPPATH . 'third_party/REST_Controller.php';
    require APPPATH . 'third_party/Format.php';

    use Restserver\Libraries\REST_Controller;

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST");

    class auth extends REST_Controller {
        public function __construct($config = 'rest') {
            parent::__construct($config);
            $this->load->database();
            
            // Load these helper to create JWT tokens
            $this->load->helper(['jwt', 'authorization']); 
        }

    public function index_get()
    {
            // Get all the headers
            $headers = $this->input->request_headers();
            // Extract the token
            $user = $headers['x-username'];
            $pass = $headers['x-password'];
            
           // Have dummy user details to check user credentials
           // send via postman
           $dummy_user = [
               'username' => 'cpy123',
               'password' => 'upk2020'
           ];
           // Extract user data from POST request
           $username = $user;
           $password = $pass;

           // Check if valid user
           if ($username === $dummy_user['username'] && $password === $dummy_user['password']) {
               
                $issuedat_claim = time();
                $notbefore_claim = $issuedat_claim + 10;
                $expire_claim = $issuedat_claim + 3600;
                $token = array(
                    "iat" => $issuedat_claim,
                    "nbf" => $notbefore_claim,
                    "exp" => $expire_claim,
                    "data" => ['username' => $dummy_user['username']]
                );

               // Create a token from the user data and send it as reponse
               $token = AUTHORIZATION::generateToken($token);
               
               // sPrepare the response
               $status = parent::HTTP_OK;
               $response = [
				   'token' => $token
				];
               $array = [
				   'response' => $response, 
				   'metadata' => [
					   'message' => 'Ok', 
					   'code' => $status
					]
				];
               $this->response($array, $status);
           }
           else {
               $this->response(['message' => 'Username atau Password Tidak Sesuai', 'code' => 201], parent::HTTP_NOT_FOUND);
           }

    }

    
}
    /* End of file Api.php */
