<?php

include __DIR__ . '/vendor/autoload.php';

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Auth_Sede
 *
 * @author dirceu.benelli
 */
class Auth_Sede {

    private static $accesstoken = "0orYXh94okaSb8VX";
    private static $baseurl = "https://sistemas.sede.embrapa.br/";
    private static $url = "segurancaws/rest/segurancaservice/autenticacao/provedor";
 
    private static function getClient() {
        try {
            $client = new Client(['verify' => false, 'base_uri' => self::$baseurl]);
            return $client;
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    private static function getHeaderAuth($login, $passwd) {
        try {
            $client = self::getClient();
            $response = $client->request('GET', self::$url, ['headers' => [
                    "Content-Type" => "application/json;charset=UTF-8",
                    "Accept" => "application/json",
                    "accesstoken" => self::$accesstoken,
                    "login" => $login,
                    "senha" => $passwd
                ], 'debug' => false, 'curl' => [CURLOPT_SSL_CIPHER_LIST => 'DEFAULT@SECLEVEL=1']]);
            return $response;
        } catch (Exception $e) {
            throw $e;
        }
    }

    public static function authSede($login, $passwd) {
        try {
            $response = self::getHeaderAuth($login, $passwd);
            if ($response->getStatusCode() == "200") {
                return true;
            } else {
                return false;
            }
        } catch (Exception $ex) {
            throw $ex;
        }
    }

    public static function getUser($login, $passwd) {
        try {
            $response = self::getHeaderAuth($login, $passwd);
            if ($response->getStatusCode() == "200") {
                $tmpUsr = (Object) json_decode($response->getBody());                
                $usuario = $tmpUsr->usuario;
                return $usuario;
            } else {
                throw new Exception("Senha_ou_login_invalido");
            }
        } catch (Exception $ex) {
            throw $ex;
        }
    }

}
