<?php

namespace Sibs\Stargate\Api;

use Sibs\Stargate\Constants\Plugin;
use Sibs\Stargate\Core\SibsFunctions;
use Sibs\Stargate\Core\SibsPaymentCore;
use Sibs\Stargate\Exceptions\SibsException;
use Sibs\Stargate\Exceptions\StgException;
use Sibs\Stargate\Params\OrderParams;

defined('ABSPATH') || exit;

class Checkout extends ApiAbstract
{
    /**
     * SIBS: Process.
     */
    public static function process(\WC_Order $wc_order, string $payment_id)
    {
        // Get Transaction Parameter
        $transactionParameters = (new OrderParams($wc_order))->getParams($payment_id);

        $result = SibsPaymentCore::sibs_get_checkout_result($transactionParameters);

        if (!is_array($result)) {
            throw new SibsException(sprintf(
                // translators: Order ID
                __('Error on Process Transaction for order #%s', 'sibs-woo-stg'),
                esc_attr($wc_order->get_id())
            ));
        }

        $statusCode = SibsPaymentCore::sibs_get_return_code($result);
        $statusMsg = SibsPaymentCore::sibs_get_return_msg($result);

        if (Plugin::NOK == SibsPaymentCore::sibs_get_transaction_result($statusCode)) {
            throw new StgException($statusMsg);
        }

        return $result['response'];
    }

    /**
     * Generate Form Config.
     *
     * @return array
     */
    public static function generateFormConfig(\WC_Order $wc_order, string $paymentMethod, string $returnUrl)
    {
        return [
            'paymentMethodList' => [
                $paymentMethod,
            ],
            'amount' => [
                'amount' => (float) $wc_order->get_total(),
                'currency' => $wc_order->get_currency(),
            ],
            'language' => SibsFunctions::get_language(),
            'redirectUrl' => $returnUrl,
            'customerData' => [
                'customerName' => trim($wc_order->get_billing_first_name().' '.$wc_order->get_billing_last_name()),
                'customerEmail' => $wc_order->get_billing_email(),
            ],
        ];
    }
}
