<?php


namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;

class YiwangService
{
    public static function getCharge($filter) {
        $filter['types'] = ['confirm'];
        return self::getCost($filter);
    }

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

    public static function getCost($filter) {
        $report = self::buildQuery($filter)->first([
            DB::raw('SUM(total_customer_price + incurred_cost) as result')
        ]);
        return isset($report->result) ? $report->result : 0;
    }


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

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

    public static function buildTransactionInfo($item) {
        try {
            $dateTime = \DateTime::createFromFormat('d/m/Y', $item['Date Order']);

            $result = [
                'detail_code' => $item['DetailsCode'],
                'type' => $item['Confirm'],
                'date_order' => $dateTime->format('Y-m-d'),
                'order_number' => $item['Order Number'],
                'quantity' => $item['Quantity'],
                'customer_price' => $item['Customer Price'],
                'total_customer_price' => $item['Total Customer Price'],
                'incurred_cost' => $item['Incurred Cost'],
            ];
        } catch (\Exception $e) {
            $result = [];
            echo $e->getMessage();
        }
        return $result;
    }

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

    public static function exists($item) {
        return DB::table('payment_yiwang_transaction')
            ->where('detail_code', $item['detail_code'])
            ->where('date_order', $item['date_order'])
            ->exists();
    }
}