<?php
$error = isset($_GET['error']);
$error_message = $_GET['error_message'] ?? 'Error';
$info = null;

if (isset($_GET['code'])) {
    $ch = curl_init('https://test-ainergy.simpleone.ru/v1/api/auth/ro/getTokenByAuthorizationCode?client_id=test&client_secret=foobar&code=' . $_GET['code']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HEADER, false);
    $jwt = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);


    if ($httpcode != 200) {
        $error = true;
        $error_message = $jwt;
    } else {
        $ch = curl_init('https://test-ainergy.simpleone.ru/v1/api/auth/ro/user-info');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $jwt));
        $json = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpcode != 200) {
            $error = true;
            $error_message = $json;
        } else {
            $info = json_decode($json, true);
        }            
    }
}

if ($error) {
    var_dump($error_message);
} else {
    var_dump($info);
}
