<?php


namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;
use Modules\FinancialStatement\Services\PaypalService;


class GelatoService
{

    public static function getCharge($filter) {
        $filter['types'] = ['charge'];
        return self::getCost($filter) * -1;
    }

    public static function getRefund($filter) {
        $filter['types'] = ['refund', 'full_refund'];
        return self::getCost($filter);
    }

    public static function getCost($filter) {
        $report = self::buildQuery($filter)->first([
            DB::raw('SUM((amount * currency_rate)/100) as result')
        ]);
        //EUR
        //@todo convert usd
        return isset($report->result) ? $report->result : 0;
        return isset($report->result) ? PaypalService::convertToUsd($report->result, 'EUR') : 0;
    }

    public static function buildQuery($filter) {
        $query = DB::table('payment_gelato_transaction');
        if (array_key_exists('transaction_from', $filter)) {
            $query->where('transaction_created_at', '>=', $filter['transaction_from']);
        }
        if (array_key_exists('transaction_to', $filter)) {
            $query->where('transaction_created_at', '<=', $filter['transaction_to']);
        }
        if (array_key_exists('types', $filter)) {
            $query->whereIn('type', $filter['types']);
        }
        return $query;
    }

    public static function getTransaction($token, $wallet, $params) {
        $endPoint = "https://dashboard.gelato.com/api/payments/v1/wallets/$wallet/transactions:search";
        $limit = 200;
        $offset = 0;
        $result = [];
        $total = 0;
        do {
            $response = PrintifyService::getData($endPoint, 'POST', [
                'createdAtBefore' => $params['createdAtBefore'],
                'createdAtAfter' => $params['createdAtAfter'],
                'offset' => $offset,
                'limit' => $limit
            ], [
                'Authorization: ' . trim($token),
                'Content-Type: application/json'
            ]);
            $offset = $offset + $limit;
            if ((!empty($response['code']) && $response['code'] == 'access_invalid')) {
                echo $response['code'] . '<br>';
                break;
            }
            if (empty($response['transactions'])) {
                break;
            }
            $result = array_merge($result, $response['transactions']);
            if (isset($response['total'])) {
                $total = $response['total'];
            }
        } while (count($result) < $total);
        return $result;
    }


    public static function storeItems($items) {
        foreach ($items as $item) {
            $data = self::buildTransactionInfo($item);
            if ($data) {
                self::store($data);
            }
        }
    }

    public static function buildTransactionInfo($item) {
        $result = [];
        try {
            $result = [
                'transaction_id' => $item['walletTransactionUid'],
                'wallet' => $item['walletUid'],
                'order_reference' => $item['orderReference'],
                'type' => $item['type'],
                'amount' => $item['amountInMinorUnits'],
                'wallet_balance_after' => $item['walletBalanceAfter'],
                'wallet_balance_before' => $item['walletBalanceBefore'],
                'currency' => $item['currencyIsoCode'],
                'currency_rate' => $item['currencyRate'],
                'comment' => $item['comment'],
                'transaction_created_at' => $item['createdAt'],
                'transaction_updated_at' => $item['updatedAt'],
                'balance_at' => null,
            ];
        } catch (\Exception $e) {
            echo $e->getMessage();
            echo '<pre>';
            echo print_r($transactionInfo);
            echo '</pre>';
            exit;
        }
        return $result;
    }

    public static function store($item) {
        if (self::exists($item['transaction_id'])) {
            $item['updated_at'] = new \DateTime();
            DB::table('payment_gelato_transaction')
                ->where('transaction_id', $item['transaction_id'])
                ->update($item);
        } else {
            $item['created_at'] = new \DateTime();
            DB::table('payment_gelato_transaction')->insert($item);
        }
    }

    public static function exists($transactionId) {
        return DB::table('payment_gelato_transaction')
            ->where('transaction_id', $transactionId)
            ->exists();
    }
}