<?php
namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;

class PrintLogicticsService
{
    public static function getCharge($filter) {
        $filter['types'] = ['fulfillment', 'charge'];
        $report = self::buildQuery($filter)->first([
            DB::raw('SUM(price) as result')
        ]);
        return isset($report->result) ? $report->result : 0;
    }

    public static function getRefund($filter) {
        $filter['types'] = ['refund'];
        $report = self::buildQuery($filter)->first([
            DB::raw('SUM(amount) as result')
        ]);
        return isset($report->result) ? $report->result : 0;
    }

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


    public static function getTransaction($token, $params) {
        $url = self::buildUrl($token, $params);
        $response = self::requestData($url);
        $items = self::parseResponse($response);
        self::storeItems($items);
    }

    protected static function parseResponse($response) {
        $rows = str_getcsv($response, "\n");
        $items = [];
        foreach ($rows as $key => $row) {
            if ($key == 0) {
                continue;
            }
            $row = str_getcsv($row);
            $paidAt = \DateTime::createFromFormat('d/m/Y H:i', $row[6]);
            $items[] = [
                'type' => $row[0],
                'amount' => $row[1],
                'order' => $row[2],
                'price' => $row[3],
                'balance' => $row[4],
                'invoice' => $row[5],
                'paid_at' => $paidAt->format('Y-m-d H:i:s'),
                'external_number' => $row[7],
            ];
        }
        return $items;
    }

    public static function buildUrl($token, $params) {
        $params['token'] = $token;
        $url = 'https://bo-5mjd36b.merchize.com/bo-api/billing/exports/balance-history/date-range?' . http_build_query($params);
        return $url;
    }

    public static function requestData($url) {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'authority: bo-5mjd36b.merchize.com',
                'accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                'referer: https://seller.merchize.com/',
                'sec-ch-ua: "Chromium";v="118", "Microsoft Edge";v="118", "Not=A?Brand";v="99"',
                'sec-ch-ua-mobile: ?0',
                'sec-ch-ua-platform: "Windows"',
                'sec-fetch-dest: document',
                'sec-fetch-mode: navigate',
                'sec-fetch-site: same-site',
                'sec-fetch-user: ?1',
                'upgrade-insecure-requests: 1',
                'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.69'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;

    }

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

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

    public static function exists($order) {
        return DB::table('payment_merchize_transaction')
            ->where('order', $order)
            ->exists();
    }
}