<?php

namespace Sibs\Stargate\Blocks;

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use Sibs\Stargate\Config\SibsConfig;
use Sibs\Stargate\Constants\Tokens;
use Sibs\Stargate\Constants\WoocommercePaymentMethods;
use Sibs\Stargate\Core\SibsFunctions;

defined('ABSPATH') || exit;

/**
 * Sibs payment method integration.
 *
 * @since 1.5.0
 */
final class SibsBlocksSupport extends AbstractPaymentMethodType
{
    /**
     * Name of the payment method.
     *
     * @var string
     */
    protected $name;

    /**
     * Constructor.
     *
     * @param mixed $method_id
     */
    public function __construct($method_id)
    {
        $this->name = $method_id;
    }

    /**
     * Initializes the payment method type.
     */
    public function initialize()
    {
        $this->settings = SibsConfig::getPaymentOption($this->get_name());
    }

    /**
     * Returns payment method.
     *
     * @return mixed
     */
    public function get_payment_method()
    {
        $payment_gateways_class = WC()->payment_gateways();
        $payment_gateways = $payment_gateways_class->payment_gateways();

        return $payment_gateways[$this->get_name()] ?? null;
    }

    /**
     * Returns if this payment method should be active. If false, the scripts will not be enqueued.
     *
     * @return bool
     */
    public function is_active()
    {
        $payment_method = $this->get_payment_method();

        return $payment_method && method_exists($payment_method, 'is_available')
            ? $payment_method->is_available()
            : false;
    }

    /**
     * Returns an array of scripts/handles to be registered for this payment method.
     *
     * @return array
     */
    public function get_payment_method_script_handles()
    {
        $handle = 'wc-'.$this->get_name().'-blocks';
        $asset_path = constant('SIBS_PLUGIN_PATH').'build/index.asset.php';
        $src_url = constant('SIBS_PLUGIN_URL').'build/index.js';
        $version = constant('SIBS_VERSION');
        $dependencies = [];

        if (file_exists($asset_path)) {
            $asset = require $asset_path;
            $version = is_array($asset) && isset($asset['version'])
                ? $asset['version']
                : $version;
            $dependencies = is_array($asset) && isset($asset['dependencies'])
                ? $asset['dependencies']
                : $dependencies;
        }

        wp_register_script(
            $handle,
            $src_url,
            $dependencies,
            $version,
            true
        );

        wp_set_script_translations(
            $handle,
            'sibs-woo-stg'
        );

        return [$handle];
    }

    /**
     * Returns an array of key=>value pairs of data made available to the payment methods script.
     *
     * @return array
     */
    public function get_payment_method_data()
    {
        $payment_method = $this->get_payment_method();
        $logo_path = constant('SIBS_PLUGIN_URL').'assets/images/';
        $logo_name = str_replace('sibs_stg_', '', strtolower($this->get_name()));
        $logos = [];

        if (isset($payment_method->settings['card_types'])) {
            foreach ($payment_method->settings['card_types'] as $logo) {
                $multi_logo_name = str_replace('sibs_stg_', '', strtolower($logo));
                $logos[] = $logo_path.$multi_logo_name.'.svg';
            }
        } else {
            $logos[] = $logo_path.$logo_name.'.svg';
        }

        $oneclick = SibsConfig::getPaymentOption(WoocommercePaymentMethods::CARD, 'tokenization');
        $checkoutLabel = '';
        $lang = SibsFunctions::get_language();
        $pdf = "sibs_terms_and_conditions_{$lang}.pdf";
        $siteUrl = constant('SIBS_PLUGIN_URL');
        $pdfUrl = "{$siteUrl}assets/files/{$pdf}";

        if (Tokens::ONECLICK === $oneclick && get_current_user_id()) {
            $termsAndConditionsLinkLabel = __('Terms and conditions', 'sibs-woo-stg');
            $oneclickExplanationLinkLabel = __('OneClick', 'sibs-woo-stg');
            $oneclickExplanationLink = "<a href='{$pdfUrl}' target='_blank'>{$oneclickExplanationLinkLabel}</a>";

            $checkoutLabel = sprintf(
                // translators: terms and conditions link, payment method name
                __('I agree to the %1$s and will adhere to them unconditionally for %2$s payment', 'sibs-woo-stg'),
                $termsAndConditionsLinkLabel,
                $oneclickExplanationLink,
            );
        }

        return [
            'title' => $payment_method->title,
            'description' => $payment_method->settings['payment_desc'] ?? '',
            'supports' => $payment_method->supports,
            'checkoutLabel' => $checkoutLabel,
            'logos' => $logos,
            'translation' => 'sibs-woo-stg',
        ];
    }
}
