<?php

namespace Sibs\Stargate\Api;

use Sibs\Stargate\Constants\Plugin;
use Sibs\Stargate\Core\SibsGeneralFunctions;
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 CheckStatus extends ApiAbstract
{
    /**
     * SIBS: Process.
     */
    public static function process(\WC_Order $wc_order)
    {
        SibsLogger::debug("[check_status] 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')
            );
        }

        $sibs_payment = SibsGeneralModels::get_transaction($wc_order);

        SibsLogger::debug('[check_status] sibs_payment: '.SibsLogger::prettify($sibs_payment));

        $payment_result = SibsPaymentCore::sibs_get_payment_status($sibs_payment['reference_id']);

        $returnCode = SibsPaymentCore::sibs_get_return_code($payment_result);
        $result_status = SibsPaymentCore::sibs_get_transaction_result($returnCode);
        SibsLogger::debug("[check_status] result_status: {$result_status}");

        if (Plugin::NOK === $result_status) {
            throw new SibsException(sprintf(
                // translators: Order ID
                __('Error on Status Inquiry for order #%s', 'sibs-woo-stg'),
                esc_attr($wc_order->get_id())
            ));
        }

        $payment_type = $payment_result['paymentType'];
        $payment_method = $payment_result['paymentMethod'];

        SibsLogger::debug('[dealACKStatus] payment_type: '.esc_attr($payment_type));
        SibsLogger::debug('[dealACKStatus] payment_method: '.esc_attr($payment_method));

        $payment_status = SibsGeneralFunctions::convertTransactionStatus(
            $payment_result['paymentStatus'],
            $payment_type
        );

        SibsGeneralModels::update_transaction($wc_order, [
            'payment_status' => $payment_status,
        ]);

        self::save_or_update_token_info($payment_result);

        $wc_order->update_status($payment_status);

        // Checked Success
        return sprintf(
            // translators: Payment Status, Order ID
            __('SIBS status payment is %1$s for order #%2$s ', 'sibs-woo-stg'),
            esc_attr($payment_status),
            esc_attr($wc_order->get_id())
        );
    }

    /**
     * SIBS Status 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, '1', esc_attr(__('SIBS Check Status', 'sibs-woo-stg')));
    }

    /**
     * Save or Update Token Info.
     */
    public static function save_or_update_token_info(array $payment_result)
    {
        $hasToken = isset($payment_result['token']);
        SibsLogger::debug('hasToken '.var_export($hasToken, true));

        if ($hasToken) {
            $token = $payment_result['token'];
            SibsLogger::debug('token: '.SibsLogger::prettify($token));

            $token_saved = SibsGeneralModels::save_or_update_token($token);
            SibsLogger::debug('token_saved: '.($token_saved ? 'yes' : 'no'));
        }
    }
}
