<?php

class Agro_Essor_EsscrEventos_Auth
{
    /**
     * Método de autenticação do ESSCR ESSOR
     * Rota: /api/auth/login
     *
     * @return string
     */
    public static function login(): string
    {
        $data = [
            'email' => ESSCR_EVENTOS_EMAIL,
            'password' => ESSCR_EVENTOS_PASSWORD
        ];
        
        $url = ESSCR_EVENTOS_URL . "/api/auth/login";
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/x-www-form-urlencoded'
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        $data = json_decode($response, true);

        if (empty($data) || $httpCode != 200) {

            if ($data['error']) {
                throw new Exception("[ESSCR] " . $data['error']);
            }

            throw new Exception("[ESSCR] Erro ao se autenticar.");
        }

        if (empty($data['access_token'])) {
            throw new Exception("[ESSCR] Não foi possível buscar o token de acesso.");
        }
        
        return $data['access_token'];
    }
}