<?php 
namespace PortalPeople\netsuite;

use yii\httpclient\Client;
use yii\base\Exception;
use Yii;

class NetSuiteApi 
{
    /** @var \yii\authclient\OAuthToken $token  */
    private $token;
    
    public function __construct(){
        $oauthClient = Yii::$app->authClientCollection->getClient('NetSuite');
        Yii::warning($oauthClient, 'NetSuite OAuth Client');
        Yii::warning(Yii::$app->params['netsuite'], 'NetSuite Config Params');
        $privateKey = file_get_contents(Yii::getAlias('@common/config/NetsuiteCerts/private.pem'));
        $jwtParams = [
            'header' => [
                'alg' => 'ES256', // NetSuite expects ES256 for JWT
                'kid' => 'sMyoQV48HFBT2jkfx8n1M8CxMI0oNVYs-8_R3D6A-xg',
                'typ' => 'JWT'
            ],
            'signatureKey' => $privateKey,
        ];
        $oauthClient->authenticateUserJwt(
            $oauthClient->clientId,
            null,
            $jwtParams,
            []
        );
    }

    /**
    * Sends a GET request to the NetSuite API.
    *
    * @param string $url
    * @param array $data
    * @return array|null
    * @throws \yii\httpclient\Exception
    */
    public static function get($url, $data = []){
        $oauthClient = Yii::$app->authClientCollection->getClient('NetSuite');
        $oauthClient->getAccessToken();
        $client = new Client(['baseUrl' => $oauthClient->baseUrl]);
        $token = $oauthClient->getAccessToken();
        if(!$token){
            new self();
            $token = $oauthClient->getAccessToken();
        } 
        try {
            $request = $client->createRequest()
                ->setMethod('GET')
                ->setUrl($url)
                ->setHeaders(['Authorization' => 'Bearer '  . $token->token]);
          
            if($data !== []){
                $request->setData($data);
            }
           return $request->send();
        } catch(Exception $e){
            throw new Exception($e->getMessage(), 100);
        }       
    }


    /**
    * Sends a POST request to the NetSuite API.
    *
    * @param string $url
    * @param array $data
    * @return array|null
    * @throws \yii\httpclient\Exception
    */
    public static function post($url, $data = []){
        $oauthClient = Yii::$app->authClientCollection->getClient('NetSuite');
        $oauthClient->getAccessToken();
        $client = new Client(['baseUrl' => $oauthClient->baseUrl]);
        $token = $oauthClient->getAccessToken();
        if(!$token){
            new self();
            $token = $oauthClient->getAccessToken();
        } 
        try {
            $request = $client->createRequest()
                ->setMethod('POST')
                ->setUrl($url)
                ->setHeaders(['Authorization' => 'Bearer '  . $token->token])
                ->setFormat(Client::FORMAT_JSON);
            if($data !== []){
                $request->setData($data);
            }
           return $request->send();
        } catch(Exception $e){
            throw new Exception($e->getMessage(), 100);
        }       
    }
}
