<?php

namespace App\Http\Controllers\Network\Classes;

use Illuminate\Support\Facades\Log;
use SoapClient;

class TradeTrackerAPI implements SalesGetterApi
{
    public $api_key;
    public $customer_id;
    public $client;
    public $sales;
    public $affiliateSiteID;

    public function __construct($customer_id, $affiliateSiteID, $api_key, $wsdl_url)
    {
        $this->customer_id = $customer_id;
        $this->affiliateSiteID = $affiliateSiteID;
        $this->api_key = $api_key;
        $this->sales = [];

        try {
            $this->client = new SoapClient($wsdl_url, [
                'soap_version' => SOAP_1_2,
                'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP,
                'exception' => false
            ]);
        } catch (\Exception $exception) {
            Log::info('TradeTracker SoapClient Construct Error', ['exception' => $exception]);
        }

        $this->authenticate();
    }

    public function getSales($start_days, $end_days)
    {
        $start_date = date('Y-m-d H:i:s', strtotime('today - ' . $start_days . ' days'));
        $end_date = date('Y-m-d H:i:s', strtotime('tomorrow - ' . $end_days . ' days'));

        $filterOptions = [
            'transactionType' => 'sale',
            'registrationDateFrom' => $start_date,
            'registrationDateTo' => $end_date
        ];

        try {
            $this->sales = $this->client->__soapCall('getConversionTransactions', [
                'affiliateSiteID' => $this->affiliateSiteID,
                'options' => $filterOptions
            ]);
        } catch (\Exception $exception) {
            Log::info('TradeTracker Get Transactions Error', ['exception' => $exception]);
        }

        return $this->sales;
    }

    private function authenticate()
    {
        try {
            $this->client->__soapCall('authenticate', [
                'customerID' => $this->customer_id,
                'passphrase' => $this->api_key
            ]);
        } catch (\Exception $exception) {
            Log::info('TradeTracker Authenticate Error', ['exception' => $exception]);
        }
    }
}
