<?php
defined( 'ABSPATH' ) || exit();

class WPCP_Pro_AmazonAPI {
    protected $public_key = "";

    protected $private_key = "";

    private $associate_tag = "";

    private $region = "";

    private $host = "";

    protected $awsv4;

    /**
     * WPCP_Pro_AmazonAPI constructor.
     *
     * @param string $public_key
     * @param string $private_key
     * @param string $associate_tag
     * @param string $region
     */
    public function __construct( $public_key, $private_key, $associate_tag, $region ) {
        $this->public_key    = $public_key;
        $this->private_key   = $private_key;
        $this->associate_tag = $associate_tag;
        $this->region        = $region;

        $this->host = "webservices.amazon." . $this->region;

        $this->awsv4 =  new WPCP_AWSV4($public_key, $private_key);
        $this->awsv4->setRegion($region)
            ->setServiceName('ProductAdvertisingAPI')
            ->setHeader('host', $this->host)
            ->setRequestMethod('POST')
            ->setHeader('content-encoding', 'amz-1.0' )
            ->setHeader('content-type', 'application/json; charset=utf-8');
    }


    /**
     * Return details of a product searched by ASIN
     *
     * @param int $asin_code
     *        	ASIN code of the product to search
     * @return mixed simpleXML object
     */
    public function getItemByAsin($asin_code) {
        $uriPath = "/paapi5/getitems";

        $search_params ['PartnerTag'] = $this->associate_tag;
        $search_params ['PartnerType'] = 'Associates';
        $search_params ['Marketplace'] = 'www.amazon.' . $this->region;
        $search_params ['ItemIds'] = array (
            $asin_code
        );
        $search_params ['Resources'] = array (
            "Images.Primary.Large",
            "Images.Variants.Large",
            "ItemInfo.ContentInfo",
            "ItemInfo.Features",
            "ItemInfo.ProductInfo",
            "ItemInfo.Title",
            "Offers.Listings.Price"
        );

        $payload = json_encode ( $search_params );
        $this->awsv4->setHeader ( 'x-amz-target', 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.GetItems' );

        $this->awsv4->setPath ( $uriPath );
        $this->awsv4->setPayload ( $payload );
        $headers = $this->awsv4->getHeaders ();
        $curl = wpcp_setup_request();
        $curl->setHeaders($headers);

        $request_url = 'https://' . $this->host . $uriPath;

        $curl->post($request_url);
        var_dump($curl->getResponse());

    }
}
