<?php

namespace App\Services\UPG;

use App\Models\Setting;
use App\Models\Transaction;
use App\Services\Cart\CartService;
use Illuminate\Support\Facades\Config;
use App\Payments\Drivers\TorobPay;
use Shetabit\Multipay\Invoice;

class TorobpayService
{
    /** fields */
    protected CartService $cartService;

    /** get cart service */
    protected function getCartService(): CartService
    {
        if (!isset($this->cartService)) {
            $this->cartService = app(CartService::class);
        }

        return $this->cartService;
    }

    /** handle torobpay upg */
    public function torobpay($orderGroup)
    {
        try {
            // cart service
            $cartService = $this->getCartService();

            // payment transaction
            $paymentTransaction = Transaction::where('transaction_id', $orderGroup->payment_transaction_uuid)->first();
            if ($paymentTransaction == null) return;

            // check for torobpay gateway
            if ($paymentTransaction->payment_gateway != 'torobpay') return;

            // set payment gateways configs
            $this->paymentGatewaysConfigs();

            // handle torobpay action
            $this->action($orderGroup, $paymentTransaction, $cartService);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    /** set payment gateways configs */
    protected function paymentGatewaysConfigs()
    {
        // payment gateways
        $paymentGatewaySetting = Setting::where('key', 'payment_gateway')->first();
        $paymentGateways = $paymentGatewaySetting ? unserialize($paymentGatewaySetting->value) : [];

        // set payment gateway driver configs
        foreach ($paymentGateways as $pg) {
            foreach ($pg['fields'] as $key => $field) {
                Config::set('payment.drivers.' . $pg['id'] . '.' . $key, $field['value']);
            }
        }
    }

    /** orders details */
    protected function details($orderGroup, CartService $cartService)
    {
        // variables
        $cartItems = [];
        $cartTotalSendPrice = 0;
        $cartTotalAmount = 0;
        $cartTotalCouponDiscountPrice = 0;
        $cartTotalFinalPrice = 0;

        // looping orders in orderGroup
        foreach ($orderGroup->orders as $order) {
            // selected address
            $selectedAddress = $order->address != null ? unserialize($order->address) : null;
            // consignments information array
            $consignmentsInformation = $cartService->sepratedConsignmentInformation($order, $selectedAddress, true);

            // torobpay cart items
            foreach ($consignmentsInformation['consignments'] as $cartData) {
                foreach ($cartData['items'] as $item) {
                    $cartItems[] = [
                        'amount' => $item['price'],
                        'category' => $item['product']['category'] ?? null,
                        'count' => $item['count'],
                        'id' => $item['id'],
                        'name' => $item['product']['title'] ?? null,
                        'commissionType' => 100,
                    ];
                    $cartTotalAmount += ($item['price']) * $item['count'];
                }
            }

            // send Price
            $cartTotalSendPrice += data_get($consignmentsInformation, 'financial.sendPrice', 0);

            // total coupon discount price
            $cartTotalCouponDiscountPrice += data_get($consignmentsInformation, 'financial.totalCouponDiscountPrice', 0);

            // total final Price
            $cartTotalFinalPrice += data_get($consignmentsInformation, 'financial.totalFinalPrice', 0);
        }

        // final cartList
        return [
            'cartList' => [
                [
                    'cartId' => 1,
                    'cartItems' => $cartItems,
                    'isShipmentIncluded' => true,
                    'isTaxIncluded' => true,
                    'shippingAmount' => $cartTotalSendPrice,
                    'taxAmount' => 0,
                    'totalAmount' => $cartTotalAmount + $cartTotalSendPrice,
                ]
            ],
            'totalSendPrice' => $cartTotalSendPrice,
            'totalAmount' => $cartTotalAmount,
            'totalCouponDiscountPrice' => $cartTotalCouponDiscountPrice,
            'totalFinalPrice' => $cartTotalFinalPrice
        ];
    }

    /** action */
    protected function action($orderGroup, $paymentTransaction, $cartService)
    {
        // cart list
        $details = $this->details($orderGroup, $cartService);

        // invoice
        $invoice = new Invoice;
        $invoice->transactionId($paymentTransaction->gateway_transaction_id);
        $settings = config('payment.drivers.torobpay');

        // handle torobpay action
        if (count($details['cartList'][0]['cartItems']) == 0 && $details['totalFinalPrice'] == 0) {
            $torobpayDriver = new TorobPay($invoice, $settings);

            // check status
            $resultStatus = $torobpayDriver->status();
            if ($resultStatus['status'] != 'REVERT' && $resultStatus['status'] != 'CANCELED' && $resultStatus['status'] != 'CANCEL' && $resultStatus['status'] != 'FAILED') {
                $torobpayDriver->cancel();
            }
        } else {
            $invoice->amount($details['totalFinalPrice']);
            $invoice->detail('cartList', $details['cartList']);
            $invoice->detail('discountAmount', $details['totalCouponDiscountPrice']);
            $invoice->detail('externalSourceAmount', 0);
            $torobpayDriver = new TorobPay($invoice, $settings);
            $torobpayDriver->update();
        }
    }
}
