<?php


namespace Modules\PrintSuppliers\Services;

use Illuminate\Support\Facades\DB;

class ToadditService
{
    public static function getCharge($filter) {
        $filter['types'] = ['charge'];
        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_toaddit_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('types', $filter)) {
            $query->whereIn('type', $filter['types']);
        }
        return $query;
    }

    public static function storeItems($items) {
        if (!$items) {
            return;
        }
        foreach ($items as $item) {
            if (!$item['Date'] || $item['Date'] == 'paid') {
                continue;
            }
            $data = self::buildTransactionInfo($item);
            if ($data) {
                self::store($data);
            }
        }
    }

    public static function buildTransactionInfo($item) {
        $result = [];
        try {
            $dayExp = explode('/', $item['Date']);
            if (!isset($dayExp[2])) {
                $dayExp[2] = 2023;
            }
            $result['type'] = 'charge';
            $result['amount'] = $item['COST'];
            $result['date'] = "$dayExp[2]-$dayExp[1]-$dayExp[0]";
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return $result;
    }

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

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