<?php

namespace BitApps\SocialPro\HTTP\Services\Social\ThreadsService;

use BitApps\Social\Model\Account;
use BitApps\Social\Utils\Hash;
use BitApps\SocialPro\Deps\BitApps\WPKit\Http\Client\HttpClient;

class ThreadsRefreshTokenService
{
    private $httpHandler;

    private $refreshTokenUrl = 'https://graph.threads.net/refresh_access_token';

    private $accountId;

    private $accountDetails;

    private $accessToken;

    private $expiresIn;

    public function __construct($accountDetails)
    {
        $this->httpHandler = new HttpClient();

        $this->accountDetails = $accountDetails;
        $this->accountId = $accountDetails->account_id;
        $this->accessToken = Hash::decrypt($accountDetails->access_token);
        $this->expiresIn = $accountDetails->expiresIn;
    }

    public function tokenExpiryCheck()
    {
        if ((\intval($this->expiresIn)) < time()) {
            return $this->refreshAccessToken();
        }

        return $this->accessToken;
    }

    public function accessToken()
    {
        return $this->tokenExpiryCheck();
    }

    public function refreshAccessToken()
    {
        $accessTokenUrl = $this->refreshTokenUrl . 'token?';

        $params = [
            'grant_type'   => 'th_refresh_token',
            'access_token' => $this->accessToken,
        ];

        $accessTokenUrlWithParams = $accessTokenUrl . http_build_query($params);

        $result = $this->httpHandler->request($accessTokenUrlWithParams, 'GET', []);

        if (isset($result->access_token)) {
            $this->accessToken = $result->access_token;
            $this->expiresIn = time() + (int) $result->expires_in;
            $this->saveAccessToken();
        }

        return $this->accessToken;
    }

    public function saveAccessToken()
    {
        if (empty($this->accountId)) {
            return;
        }

        $account = Account::findOne(['account_id' => $this->accountId]);

        $accountDetails = $this->accountDetails;
        $accountDetails->access_token = Hash::encrypt($this->accessToken);
        $accountDetails->expiresIn = $this->expiresIn;
        $account->update(['details' => $accountDetails])->save();
    }
}
