<?php
class api_rest_model extends Cf_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * Gets api info through rest interface
     *
     * @return array
     * @throws Exception
     */
    public function get_api_details()
    {
        try {
            $settings = $this->getRestClient()->get('/');
            $data = $this->checkData($settings);
            if (is_array($data) && $this->hasErrors() == 0) {
                return $data['data'][0];
            } else {
                throw new Exception($this->getErrorsString());
            }
        } catch (HttpClient_NotFound $e) {
            log_message('error', $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        } catch (HttpClient_Unauthorized $e) {
            log_message('info', $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), $e->getMessage() . ' ' . $e->getFile() . ' line:' . $e->getLine());
            throw $e;
        }
    }

    public function refresh_token($refreshToken)
    {
        try {
            $mpClient = config_item('MP_CLIENT_ID');
            $mpSecret = config_item('MP_CLIENT_SECRET');
            $grantType = 'refresh_token';

            $data = [
                'client_id' => $mpClient,
                'grant_type' => $grantType,
                'refresh_token' => $refreshToken,
            ];

            if (!empty($mpSecret)) {
                $data['client_secret'] = $mpSecret;
            }

            $settings = $this->getRestClient()->post('/oauth2/token', $data);
            $data = $this->checkData($settings);
            if (is_array($data) && !empty($data['access_token'])) {
                return $data;
            }
            return null;
        } catch (Exception $e) {
            log_message(log_level_for_exception($e), 'Error while refreshing token:: ' . $e->getMessage());
            return null;
        }
    }
}
