<?php

namespace App\Http\Controllers\Network\Classes;

use GuzzleHttp\Client;


class FirstGrabberApi implements SalesGetterApi
{

    public $api_key;
    public $api_url;
    public $web_ids;
    public $client;
    public $sales;
    public $api_secret;

    public function __construct($api_key, $api_secret, $api_url, $web_ids = [])
    {
        $this->api_key = $api_key;
        $this->api_url = $api_url;
        $this->web_ids = $web_ids;
        $this->api_secret = $api_secret;
        $this->client = new Client();
        $this->sales = [];
    }

    public function getSales($start_days, $end_days)
    {
        if (sizeof($this->web_ids) == 0)
            $this->callApi($start_days, $end_days);
        else {
            foreach ($this->web_ids as $web_id) {
                $this->callApi($start_days, $end_days, $web_id);
            }
        }
        return $this->sales;
    }

    private function generateSign($query)
    {
        ksort($query);
        $signStr = '';
        foreach ($query as $key => $val) {
            if ('sign' == $key) continue;
            if ($key != '' && $val != '') {
                $signStr .= $key . $val;
            }
        }
        $query['sign'] = strtoupper(hash_hmac('sha256', $signStr, $this->api_secret));
        return $query;
    }

    private function callApi($start_days, $end_days, $web_id = null)
    {
        $total_pages = 1;
        for ($i = 1; $i <= $total_pages; $i++) {
            $query = [
                'api_key' => $this->api_key,
                'hash_method' => 'hmac_sha256',
                'time' => time(),
                'start_date' => date('Y-m-d', strtotime("today - {$start_days} days ")),
                'end_date' => date('Y-m-d', strtotime("tomorrow - {$end_days} days ")),
                'page' => $i,
            ];
            if ($web_id) $query['web_id'] = $web_id;
            $query = $this->generateSign($query);
            try {
                $result = $this->client->request(
                    'GET',
                    $this->api_url . '/completed-orders',
                    [
                        'query' => $query
                    ]
                );
                $salesResponse = json_decode($result->getBody())->data;
            } catch (\Exception $e) {
                return [];
            }
            $total_pages = $salesResponse->total_pages;
            $this->sales = array_merge($this->sales, $salesResponse->items);
        }
    }
}
