<?php


namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;

class TezzilyService
{

    public static function getCharge($filter) {
        $filter['statuses'] = ['Done'];
        return self::getCost($filter);
    }

    public static function getRefund($filter) {

        return 0;
    }

    public static function getCost($filter) {
        $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_tezzily_transaction');
        if (array_key_exists('transaction_from', $filter)) {
            $query->where('date', '>=', $filter['transaction_from']);
        }
        if (array_key_exists('transaction_to', $filter)) {
            $query->where('date', '<=', $filter['transaction_to']);
        }
        if (array_key_exists('statuses', $filter)) {
            $query->whereIn('status', $filter['statuses']);
        }
        if (array_key_exists('types', $filter)) {
            $query->whereIn('type', $filter['types']);
        }
        return $query;
    }


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

    }

    public static function buildTransactionInfo($item) {
        $result = [];
        try {

            $result = [
                'order_id' => $item['OrderID'],
                'order_reference' => $item['Order Reference'],
                'type' => 'Charge',
                'status' => $item['Status of order'],
                'order_seller_id' => $item['Order Seller Id'],
                'total_item_price' => str_replace('$', '', $item['Total Item Price']),
                'total_shipping' => str_replace('$', '', $item['Total Shipping']),
                'amount' => str_replace('$', '', $item['Total Amount']),
                'date' => $item['Date'],
            ];
        } catch (\Exception $e) {
            echo $e->getMessage();

        }
        return $result;
    }

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

    }

    public static function exists($orderId, $orderRefer) {
        return DB::table('payment_tezzily_transaction')
            ->where('order_id', $orderId)
            ->where('order_reference', $orderRefer)
            ->exists();
    }
}