<?php
/**
 * Created by PhpStorm.
 * User: Villa
 * Date: 03/12/2018
 * Time: 16:21
 */


trait Trait_InutraliaWS {

    public function save_token_credentials ($token_auth){
        \Session::set('token_auth',$token_auth);
    }

    public function get_header(){

        return array(
            'Content-Type: application/json',
            'Accept: application/json',
            'Authorization: Basic '. \Session::get('token_auth')
        );

    }

    /**
     * Method to make requests to inutralia.
     *
     * MORE INFO CURL --> http://php.net/manual/es/function.curl-setopt.php
     *
     * @param $parameter_url
     * @param bool $header
     * @param int $timeout
     * @param bool $httpget
     * @param int $return_transfer
     * @return mixed
     */

    public function request_generic($parameter_url, $header = false, $timeout = 30, $httpget = true, $return_transfer = 1){

        $constant = \Config::load('constants');

        // La url la obtiene de config dependiendo del entorno.
        $process = curl_init($constant[$parameter_url]);

        curl_setopt($process, CURLOPT_HTTPHEADER,$this->get_header());
        curl_setopt($process, CURLOPT_HEADER, $header);
        curl_setopt($process, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($process, CURLOPT_HTTPGET , $httpget);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, $return_transfer);

        $return = curl_exec($process);

        curl_close($process);

        return $return;
    }

    /**
     *
     * User auth basic request for login, save the user token in session for all requests.
     *
     * @param $user
     * @param $password
     */

    public function ws_user($user,$password){

        $this->save_token_credentials(base64_encode("$user:$password"));

        return json_decode($this->request_generic('user'));

    }

    /**
     * Request get profile
     */
    public function ws_profile(){

        return json_decode($this->request_generic('profile'));

    }


}