<?php

namespace Sibs\Stargate\Api;

use Sibs\Stargate\Constants\OrderStatus;
use Sibs\Stargate\Constants\PaymentStatus;
use Sibs\Stargate\Constants\WoocommerceOrderStatus;
use Sibs\Stargate\Core\SibsPaymentCore;
use Sibs\Stargate\Exceptions\SibsException;
use Sibs\Stargate\Loggers\SibsLogger;
use Sibs\Stargate\Models\SibsGeneralModels;
use Sibs\Stargate\Utils\SibsVersion;

defined('ABSPATH') || exit;

class RefundInquiry extends ApiAbstract
{
    /**
     * SIBS: Process.
     */
    public static function process(\WC_Order $wc_order)
    {
        SibsLogger::debug("[refund_inquiry] order_id: {$wc_order->get_id()}");

        $is_sibs_payment = SibsVersion::sibs_is_order_from_sibs($wc_order);

        if (!$is_sibs_payment) {
            throw new SibsException(
                __('Order is not a SIBS payment', 'sibs-woo-stg')
            );
        }

        $payment_status = $wc_order->get_status();
        $status_to_refund_inquiry = [
            OrderStatus::PENDING_REFUND,
        ];

        if (!in_array($payment_status, $status_to_refund_inquiry)) {
            throw new SibsException(
                __('Order is not on a status to refund inquiry', 'sibs-woo-stg')
            );
        }

        $sibs_payment = SibsGeneralModels::get_transaction($wc_order);
        $refund_result = SibsPaymentCore::sibs_get_payment_status($sibs_payment['refunded_id']);

        $log_sibs_payment = $sibs_payment;
        $log_sibs_payment['formConfig']
        = $log_sibs_payment['formConfig'] = json_decode($log_sibs_payment['formConfig'], true);
        $log_sibs_payment['spg_style'] = json_decode($log_sibs_payment['spg_style'], true);

        SibsLogger::debug('[refund_inquiry] sibs_payment', [
            'data' => $log_sibs_payment,
        ]);

        if (PaymentStatus::SUCCESS === $refund_result['paymentStatus']) {
            $refund_inquiry_status = WoocommerceOrderStatus::REFUNDED;

            try {
                $wc_order->update_status($refund_inquiry_status);
            } catch (\Throwable $t) {
                SibsLogger::error($t->getMessage());
            }

            $amount = $sibs_payment['refunded_amount'];
            $amountMSG = "{$amount} {$wc_order->get_currency()}";

            $note_message = sprintf(
                // translators: Amount Message
                __('Order was Refunded for %s', 'sibs-woo-stg'),
                $amountMSG
            );
            $wc_order->add_order_note($note_message);

            SibsGeneralModels::update_transaction($wc_order, [
                'payment_status' => $refund_inquiry_status,
                'refunded_amount' => $sibs_payment['refunded_amount'],
                'refund_information' => $note_message.(!empty($sibs_payment['refund_information']) ? ', '.$sibs_payment['refund_information'] : ''),
            ]);
            SibsLogger::debug('[refund_inquiry] SUCCESS');
        } else {
            if (PaymentStatus::PENDING === $refund_result['paymentStatus']) {
                $refund_inquiry_status = WoocommerceOrderStatus::PENDING_REFUND;
                $errorMessage = __('Order refund still pending', 'sibs-woo-stg');
                SibsLogger::debug('[refund_inquiry] PENDING');
            } else {
                $refund_inquiry_status = WoocommerceOrderStatus::PROCESSING;
                $errorMessage = sprintf(
                    // translators: Order ID
                    __('Order refund failed for #%s', 'sibs-woo-stg'),
                    $wc_order->get_id()
                );
                SibsLogger::debug('[refund_inquiry] FAILED');
            }

            try {
                $wc_order->update_status($refund_inquiry_status);
            } catch (\Throwable $t) {
                SibsLogger::error($t->getMessage());
            }

            SibsGeneralModels::update_transaction($wc_order, [
                'payment_status' => $refund_inquiry_status,
                'refunded_amount' => $sibs_payment['refunded_amount'],
                'refund_information' => $errorMessage.(!empty($sibs_payment['refund_information']) ? ', '.$sibs_payment['refund_information'] : ''),
            ]);

            throw new SibsException($errorMessage);
        }

        // Refund Inquiry Success
        SibsLogger::debug('[refund_inquiry] SUCCESS');

        return sprintf(
            // translators: Order Id, Amount Message
            __('Refund success for order #%1$s with %2$s', 'sibs-woo-stg'),
            $wc_order->get_id(),
            $amountMSG
        );
    }

    /**
     * SIBS Refund Inquiry Order Add Button.
     *
     * @param mixed $order
     */
    public static function add_button($order)
    {
        $order_id = esc_attr($order->get_id());
        self::print_button($order_id, '3', esc_attr(__('SIBS Refund Inquiry', 'sibs-woo-stg')));
    }
}
