<?php

namespace Sibs\Stargate\Api;

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

defined('ABSPATH') || exit;

class Capture extends ApiAbstract
{
    /**
     * SIBS: Process.
     */
    public static function process(\WC_Order $wc_order)
    {
        SibsLogger::debug("[process_capture] 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_capture = [
            OrderStatus::AUTHORIZED,
        ];

        if (!in_array($payment_status, $status_to_capture)) {
            throw new SibsException(
                __('Order is cannot be captured in this status', 'sibs-woo-stg')
            );
        }

        $sibs_payment = SibsGeneralModels::get_transaction($wc_order);
        $payment_type = PaymentTypes::CAPT;
        $error_message = __('Capture request has an ERROR', 'sibs-woo-stg');
        $amount = $wc_order->get_total();

        SibsLogger::debug('[process_capture] sibs_payment: '.SibsLogger::prettify($sibs_payment));
        SibsLogger::debug("[process_capture] payment_type: {$payment_type}");
        SibsLogger::debug("[process_capture] amount: {$amount}");

        $backoffice_config = self::get_backoffice_config(
            $sibs_payment,
            $payment_type,
            $amount,
            $error_message
        );

        $backoffice_result = self::sibs_do_back_office_payment($wc_order, $backoffice_config);

        SibsGeneralModels::update_transaction($wc_order, [
            'captured_id' => $backoffice_result['response']['transactionID'],
            'capture_status' => $backoffice_result['response']['paymentStatus'],
        ]);

        if (!$backoffice_result['is_valid']) {
            throw new SibsException($error_message);
        }

        switch ($backoffice_result['response']['paymentStatus']) {
            case PaymentStatus::SUCCESS:
                $capture_status = $backoffice_config['order_status'];
                SibsLogger::debug('[process_capture] SUCCESS');

                break;

            default:
                throw new SibsException(
                    __('Capture request denied by SIBS', 'sibs-woo-stg')
                );
        }

        $amountMSG = "{$amount} {$wc_order->get_currency()}";

        $note_message = sprintf(
            // translators: Order ID
            __('Order was Captured for %s', 'sibs-woo-stg'),
            $amountMSG
        );

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

        SibsGeneralModels::update_transaction($wc_order, [
            'payment_status' => $capture_status,
            'captured_amount' => $backoffice_result['response']['amount']['value'] + $sibs_payment['captured_amount'],
            'capture_information' => $note_message.(!empty($sibs_payment['capture_information']) ? ', '.$sibs_payment['capture_information'] : ''),
        ]);

        // Add cpture note
        $wc_order->add_order_note($note_message);

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

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