<?php

namespace App\Http\Controllers\Network\Classes;

use GuzzleHttp\Client;
use RuntimeException;

class HO implements SalesGetterApi
{
    public $api_key;
    public $aff_id;
    public $short_name;
    public $client;
    public $stores;
    public $sales;

    public function __construct($api_key, $short_name)
    {
        $this->api_key = $api_key;
        $this->short_name = $short_name;
        $this->client = new Client(['base_uri'=> 'https://'.$short_name.'.api.hasoffers.com/Apiv3/json' ]);
        $this->stores = [];
        $this->sales = [];
    }

    public function getStores()
    {

        $response = $this->client->request('GET', null, [
            'query' => ['Target' => 'Affiliate_Offer','Method'=>'findAll','api_key'=>$this->api_key,'limit'=>5000,
                        'filters'=> ['status'=>'active'] , 'fields' => ['status','preview_url','id','name','default_payout','default_goal_name','percent_payout','payout_type']
            ]
        ]);

        $store_json = json_decode($response->getBody(),true);


        if(json_last_error()!==JSON_ERROR_NONE){
            throw new RuntimeException(
                'API response not well-formed (json error code: '.json_last_error().')'
            );
        }

        // Print out the response details or, any error messages
        if(isset($store_json['response']['status']) && $store_json['response']['status']===1){
            $this->stores = $store_json['response']['data']['data'];
        }else{

        }
        return;
    }

    public function getSales($start_days, $end_days)
    {
        if ($start_days > 762 || $end_days > 762)
            return [];
        $start_date = date('Y-m-d', strtotime('today - '.$start_days.' days'));
        $end_date = date('Y-m-d', strtotime('today - '.$end_days.' days'));

        $response = $this->client->request('GET', null, [
            'query' => ['Target' => 'Affiliate_Report','Method'=>'getConversions','api_key'=>$this->api_key,'limit'=>5000,
                        'filters'=> array ( 'Stat.date' => array ( 'conditional' => 'BETWEEN', 'values' => array ( 0 => $start_date, 1 => $end_date, ), ), ),
                        'fields' => ['Stat.conversion_status','Stat.affiliate_info1','Stat.approved_payout','Stat.payout','Stat.datetime','Stat.sale_amount','Stat.offer_id','Stat.ip','Stat.id']
            ]
        ]);

        $sales_json = json_decode($response->getBody(),true);

        if(json_last_error()!==JSON_ERROR_NONE){
            throw new RuntimeException(
                'API response not well-formed (json error code: '.json_last_error().')'
            );
        }

        // Print out the response details or, any error messages
        if(isset($sales_json['response']['status']) && $sales_json['response']['status']===1){
            return $this->sales = $sales_json['response']['data']['data'];
        }
        return [];
    }
}
