<?php

namespace App\Http\Controllers\Network\Classes;

use Exception;
use GuzzleHttp\Client;

class Admitad implements SalesGetterApi, LinkValidationApi
{

    public $client_id;
    public $auth_token;
    public $client;
    public $sales;
    public $website_id;

    public function __construct($client_id, $auth_token, $website_id)
    {
        $this->client_id = $client_id;
        $this->auth_token = $auth_token;
        $this->website_id = $website_id;
        $this->client = new Client(['base_uri' => 'https://api.admitad.com']);
        $this->sales = [];
    }

    /**
     * Getting sales from network and prepare it to be ready for saving.
     *
     * @param DateTime $start_days filter sales based on start days
     * @param DateTime $end_days filter sales based on end days
     *
     * @return array sales orders
     * @throws Exception If issue happened on saving sales
     *
     */
    public function getSales($start_days, $end_days)
    {
        $token = $this->getToken();
        if (!$token) die;

        try {
            $salesResponse = $this->client->request(
                'GET',
                'https://api.admitad.com/statistics/actions/',
                [
                    'query' => ['website' => $this->website_id, 'date_start' => date('d.m.Y', strtotime("today - {$start_days} days ")), 'date_end' => date('d.m.Y', strtotime("today - {$end_days} days ")), 'limit' => 500, 'offset' => 0],
                    'headers' => ['Authorization' => 'Bearer ' . $token]
                ]
            );

            $sales = json_decode($salesResponse->getBody());
            if (!$sales) return [];

            $this->sales = $sales;
            return $sales->results;

        } catch (Exception $e) {
            return [];
        }
    }

    /**
     * Validating link of store in Admitad network.
     *
     * @param URL $link Store link
     *
     * @return boolean true if link is valid
     */
    public function validateLink($link): bool
    {
        $token = $this->getToken('validate_links');
        if (!$token) die;

        try {
            $salesResponse = $this->client->request(
                'GET',
                'https://api.admitad.com/validate_links/',
                [
                    'query' => ['link' => $link],
                    'headers' => ['Authorization' => 'Bearer ' . $token]
                ]
            );

            return $salesResponse->getStatusCode() == 200;

        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Getting authentication token.
     *
     * @param string $scope $scope of the authentication token
     *
     * @return string the authentication token
     */
    public function getToken($scope = 'statistics')
    {

        $token = false;

        try {
            $response = $this->client->request(
                'POST',
                'https://api.admitad.com/token/',
                [
                    'form_params' => [
                        'grant_type' => 'client_credentials',
                        'client_id' => $this->client_id,
                        'scope' => $scope
                    ],
                    'headers' => ['Authorization' => 'Basic ' . $this->auth_token]
                ]
            );

            $res = json_decode($response->getBody());
            if ($res) {
                $token = $res->access_token;
            }
        } catch (Exception $e) {
        } finally {
            return $token;
        }
    }
}
