<?php

namespace App\Http\Controllers\Network\Classes;

use GuzzleHttp\Client;
use GuzzleHttp\Promise\EachPromise;
use Psr\Http\Message\ResponseInterface;

class CJ implements SalesGetterApi
{

    public $api_key;
    public $aff_id;
    public $website_id;
    public $client;
    public $stores;
    public $coupons;
    public $sales;

    public function __construct($api_key, $aff_id, $website_id)
    {
        $this->api_key = $api_key;
        $this->aff_id = $aff_id;
        $this->website_id = $website_id;
        $this->client = new Client();
        $this->stores = [];
        $this->coupons = [];
        $this->sales = [];
    }

    public function getSales($start_days, $end_days)
    {
        $start_date = date('Y-m-d\TH:i:s', strtotime("today - {$start_days} days")) . 'Z';
        $end_date = date('Y-m-d', strtotime("today - {$end_days} days")) . 'T23:59:59Z';

        $response = $this->client->request('POST', 'https://commissions.api.cj.com/query', [
            'headers' => ['Authorization' => 'Bearer ' . $this->api_key, 'Content-Type' => 'application/json'],
            'body' => "{ publisherCommissions(forPublishers: [\"{$this->aff_id}\"],websiteIds:[\"{$this->website_id}\"], sincePostingDate:\"{$start_date}\",beforePostingDate:\"{$end_date}\"){count payloadComplete records {actionStatus actionTrackerName actionTrackerId actionType advertiserId aid commissionId eventDate orderId shopperId pubCommissionAmountUsd saleAmountUsd saleAmountPubCurrency pubCommissionAmountPubCurrency}  }}"
        ]);

        $sales_json = json_decode($response->getBody(), true);
        if (isset($sales_json['data']['publisherCommissions']['records']))
            return $this->sales = $sales_json['data']['publisherCommissions']['records'];
        return [];
    }

    public function getStores()
    {


        /** @var PsrCacheCacheItemPoolInterface $cache */

        $response = $this->client->request('GET', 'https://advertiser-lookup.api.cj.com/v2/advertiser-lookup', [
            'query' => ['requestor-cid' => $this->website_id, 'advertiser-ids' => 'joined', 'records-per-page' => 100, 'page-number' => 1],
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key
            ]
        ]);
        $merchants_xml = simplexml_load_string($response->getBody());

        if ($merchants_xml->advertisers->advertiser)
            $this->stores[] = $merchants_xml->advertisers->advertiser;


        $total_merchants = $merchants_xml->advertisers->attributes()->{'total-matched'};
        $total_pages = ceil($total_merchants / 10);


        $promises = (function () use ($total_pages) {
            for ($page = 2; $page <= $total_pages; $page++) {
                yield $this->client->requestAsync('GET', 'https://advertiser-lookup.api.cj.com/v2/advertiser-lookup', [
                    'query' => ['requestor-cid' => $this->website_id, 'advertiser-ids' => 'joined', 'records-per-page' => 100, 'page-number' => $page],
                    'headers' => [
                        'Authorization' => 'Bearer ' . $this->api_key
                    ]
                ]);
            }
        })(); // Self-invoking anonymous function (PHP 7 only), use call_user_func on older PHP versions.

        $eachPromise = new EachPromise($promises, [
            'concurrency' => 4,
            'fulfilled' => function (ResponseInterface $response) {
                $merchants_xml = simplexml_load_string($response->getBody());

                if ($merchants_xml->advertisers->advertiser)
                    $this->stores[] = $merchants_xml->advertisers->advertiser;
                // Do something with the profile.
            }
        ]);

        $eachPromise->promise()->wait();

        return;
    }


    public function getCoupons()
    {


        $response = $this->client->request('GET', 'https://link-search.api.cj.com/v2/link-search', [
            'query' => ['website-id' => $this->aff_id, 'advertiser-ids' => 'joined', 'link-type' => 'Text Link', 'records-per-page' => 100, 'page-number' => 1],
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key
            ]
        ]);
        $coupons_xml = simplexml_load_string($response->getBody());

        if ($coupons_xml->links->link)
            $this->coupons[] = $coupons_xml->links->link;


        $total_coupons = $coupons_xml->links->attributes()->{'total-matched'};
        $total_pages = ceil($total_coupons / 100);

        //  $total_pages = 3;

        $promises = (function () use ($total_pages) {
            for ($page = 2; $page <= $total_pages; $page++) {
                yield $this->client->requestAsync('GET', 'https://link-search.api.cj.com/v2/link-search', [
                    'query' => ['website-id' => $this->aff_id, 'advertiser-ids' => 'joined', 'link-type' => 'Text Link', 'records-per-page' => 100, 'page-number' => $page],
                    'headers' => [
                        'Authorization' => 'Bearer ' . $this->api_key
                    ]
                ]);
            }
        })(); // Self-invoking anonymous function (PHP 7 only), use call_user_func on older PHP versions.

        $eachPromise = new EachPromise($promises, [
            'concurrency' => 4,
            'fulfilled' => function (ResponseInterface $response) {
                $coupons_xml = simplexml_load_string($response->getBody());

                if ($coupons_xml->links->link)
                    $this->coupons[] = $coupons_xml->links->link;
                // Do something with the profile.
            }
        ]);

        $eachPromise->promise()->wait();

        return;
    }
}
