<?php


namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;

class CustomCatService
{

    public static function getCharge($filter) {
        $filter['statuses'] = ['Shipped'];
        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_customcat_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('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) {
                if (!$item['amount']) {
                    continue;
                }
                $data = self::buildTransactionInfo($item);
                if ($data) {
                    self::store($data);
                }
            }
        }

    }

    public static function buildTransactionInfo($item) {
        $result = [];
        try {
            $result = [
                'order_id' => $item['order id'],
                'invoice' => $item['invoice'],
                'type' => 'Charge',
                'status' => $item['order status'],
                'amount' => $item['amount'],
                'item_cost' => $item['item cost'],
                'shipping_cost' => $item['shipping'],
                'tracking' => $item['tracking'],
                'transaction_created_at' => $item['order date'],
                'shipping_created_at' => $item['ship date'],
            ];
        } catch (\Exception $e) {
            echo $e->getMessage();

        }
        return $result;
    }

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

    }

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