<?php

require_once("db/AppManager.php");
require_once("./amazon_sp_api/vendor/autoload.php");


use Tops\AmazonSellingPartnerAPI\Authentication;

sp_api_generate_access_token(); // update the token First and fetch the details

$pm = AppManager::getPM();

$sql = "SELECT * FROM store_credentials";
$store_config = $pm->fetchResult($sql);

if (!empty($store_config)) {

    $store_details = sanitise_credentials($store_config[0]);

    define('SP_API_ACCESS_TOKEN', $store_details->sp_api_access_token);
    define('SP_API_REFRESH_TOKEN', $store_details->sp_api_refresh_token);
    define('SP_API_CLIENT_ID', $store_details->sp_api_client_id);
    define('SP_API_CLIENT_SECRET', $store_details->sp_api_client_secret);
    define('SP_API_ACCESS_KEY', $store_details->sp_api_access_key);
    define('SP_API_SECRET_KEY', $store_details->sp_api_secret_key);
    define('SP_API_AWS_REGION', $store_details->sp_api_aws_region);
    define('SP_API_BASE_URL', $store_details->sp_api_base_url);
}

function sanitise_credentials($store_config, $action = 'decrypt')
{
    $credentials = new stdClass();
    if (!empty($store_config)) {
        $secure = array('merchant_id', 'mws_auth_token', 'mws_access_key_id', 'mws_secret_key', 'aws_access_key_id', 'aws_secret_key', 'sp_api_client_id', 'sp_api_client_secret', 'sp_api_access_key', 'sp_api_secret_key');
        foreach ($store_config as $key => $item) {

            if (in_array($key, $secure)) {
                $credentials->{$key} = encrypt_decrypt($item, $action);
            } else {
                $credentials->{$key} = $item;
            }
        }
    }

    return $credentials;
}

function encrypt_decrypt($string, $action = 'encrypt')
{
    $encrypt_method = "AES-256-CBC";
    $secret_key = "PLAYz_AMAZON"; // user define private key
    $secret_iv = "PLAYz_AMAZON_SECRET_KEY"; // user define secret key
    $key = hash('sha512', $secret_key);
    $iv = substr(hash('sha512', $secret_iv), 0, 16); // sha512 is hash_hmac_algo
    if ($action == 'encrypt') {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } elseif ($action == 'decrypt') {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}

function sp_api_generate_access_token()
{
    $pm = AppManager::getPM();

    $sql = "SELECT * FROM store_credentials";
    $store_config = $pm->fetchResult($sql);
    if (!empty($store_config)) {

        $store_details = sanitise_credentials($store_config[0]);

        $refresh_token = $store_details->sp_api_refresh_token;
        $client_id = $store_details->sp_api_client_id;
        $client_secret = $store_details->sp_api_client_secret;

        if (!empty($refresh_token) && !empty($client_id) && !empty($client_secret)) {

            // Authentication object
            $objAuthentication = new Authentication($client_id, $client_secret);
            $return_token_data = $objAuthentication->getAccessTokenFromRefreshToken('refresh_token', $refresh_token);

            if (!empty($return_token_data)) {

                $access_token = $return_token_data->access_token;

                // Upadte the Token
                $pm = AppManager::getPM();
                $sql = "UPDATE `store_credentials` SET `sp_api_access_token`= '" . $access_token . "' WHERE id=1";

                $pm->executeQuery($sql);
            }
        }
    }
}
