<?php
/**
 * Instantiation class for the Credorax gateway.
 */

// phpcs:disable

class WC_Credorax
{

    /**
     * @var Singleton The reference the *Singleton* instance of this class
     */
    private static $instance;

    private function __construct()
    {
        $this->init();
    }

    /**
     * Returns the *Singleton* instance of this class.
     *
     * @return Singleton The *Singleton* instance.
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Prevent cloning of the instance of the Singleton instance.
     *
     * @return void
     */
    public function __clone()
    {
	    wc_doing_it_wrong( __FUNCTION__, __( 'Cloning is forbidden.', 'woocommerce' ), '2.1' );
    }

    /**
     * Prevent unserializing of the Singleton instance.
     *
     * @return void
     */
    public function __wakeup()
    {
	    wc_doing_it_wrong( __FUNCTION__, __( 'Cloning is forbidden.', 'woocommerce' ), '2.1' );
    }

    /**
     * Init the plugin after plugins_loaded so environment variables are set.
     */
    public function init()
    {
        require_once(WC_CREDORAX_PATH . 'includes/autoload.php');

        // Filters
        add_filter('woocommerce_payment_gateways', [$this, 'add_gateway' ]);
        add_filter('plugin_action_links_' . plugin_basename(__FILE__), [$this, 'plugin_action_links']);
        add_filter('woocommerce_order_actions', [$this, 'add_capture_order_action']);
        add_filter('woocommerce_payment_token_class', [$this, 'credorax_payment_token_class'], 10, 2);
        add_filter('woocommerce_payment_methods_list_item', [$this, 'wc_get_account_saved_payment_methods_list_item_credorax'], 10, 2);

        // Admin actions
        add_action('woocommerce_order_action_credorax_capture', [$this, 'credorax_capture_action']);
        add_action('woocommerce_order_action_credorax_void', [$this, 'credorax_void_action']);

        // Front actions
        add_action('template_redirect', [$this, 'credorax_frontend_router']);
    }

    /**
     * Add the Credorax gateway to WooCommerce.
     */
    public function add_gateway($methods)
    {
        $methods[] = 'WC_Credorax_Gateway';

        return $methods;
    }

    /**
     * Adds plugin action links.
     */
    public function plugin_action_links($links)
    {
        $plugin_links = [
            '<a href="admin.php?page=wc-settings&tab=checkout&section=credorax">' . esc_html__('Settings', 'woocommerce-gateway-credorax') . '</a>',
            '<a href="https://epower.credorax.com/">' . esc_html__('Docs', 'woocommerce-gateway-credorax') . '</a>',
            '<a href="https://www.credorax.com/support">' . esc_html__('Support', 'woocommerce-gateway-credorax') . '</a>',
        ];
        return array_merge($plugin_links, $links);
    }

    /**
     * Adds plugin action links.
     */
    public function credorax_payment_token_class($class_name, $type = null)
    {
        if ($type === WC_Credorax_Gateway::GATEWAY_ID) {
            return WC_Credorax_Model_Token::class;
        }
        return $class_name;
    }

    /**
     * Controls the output for credit cards on the my account page.
     *
     * @since 2.6
     * @param  array            $item         Individual list item from woocommerce_saved_payment_methods_list.
     * @param  WC_Payment_Token $payment_token The payment token associated with this method entry.
     * @return array                           Filtered item.
     */
    public function wc_get_account_saved_payment_methods_list_item_credorax($item, $payment_token)
    {
        if (WC_Credorax_Gateway::GATEWAY_ID !== strtolower($payment_token->get_type())) {
            return $item;
        }

        $card_type               = $payment_token->get_card_type();
        $item['method']['last4'] = $payment_token->get_last4();
        $item['method']['brand'] = (! empty($card_type) ? ucfirst($card_type) : esc_html__('Credit card', 'woocommerce'));
        $item['expires']         = $payment_token->get_expiry_month() . '/' . substr($payment_token->get_expiry_year(), -2);

        return $item;
    }

    public function add_capture_order_action($actions)
    {
        if (! isset($_REQUEST['post'])) {
            return $actions;
        }

        $order = wc_get_order($_REQUEST['post']);

        if ($order->get_payment_method() !== WC_Credorax_Gateway::GATEWAY_ID) {
            return $actions;
        }

        if (!is_array($actions)) {
            $actions = [];
        }

        if ($order->get_meta(WC_Credorax_Gateway::KEY_CREDORAX_PAYMENT_STATUS) === WC_Credorax_Gateway::CREDORAX_PAYMENT_STATUS_PENDNIG) {
            $actions[WC_Credorax_Gateway::GATEWAY_ID . '_capture'] = esc_html__('Capture payment via Credorax', 'woocommerce-gateway-credorax');
            $actions[WC_Credorax_Gateway::GATEWAY_ID . '_void'] = esc_html__('Void payment via Credorax', 'woocommerce-gateway-credorax');
        }

        return $actions;
    }

    public function credorax_capture_action($order)
    {
        if (! is_object($order)) {
            $order = wc_get_order($order);
        }
        $gateway = new WC_Credorax_Gateway();
        return $gateway->process_capture($order->get_id());
    }

    public function credorax_void_action($order)
    {
        if (! is_object($order)) {
            $order = wc_get_order($order);
        }
        $gateway = new WC_Credorax_Gateway();
        return $gateway->process_void($order->get_id());
    }

    public function credorax_frontend_router()
    {
        if (isset($_GET['credorax_fingerprint_form']) && isset($_GET['3ds_data'])) {
            $parsedData = array_merge(
                ['3ds_method' => null, '3ds_trxid' => null],
                (array) json_decode(rawurldecode(filter_input(INPUT_GET, '3ds_data')), true)
            );

            WC()->session->set(WC_Credorax_Gateway::KEY_CREDORAX_3DS_METHOD, $parsedData['3ds_method']);
            WC()->session->set(WC_Credorax_Gateway::KEY_CREDORAX_3DS_TRXID, $parsedData['3ds_trxid']);

            $threeDSMethodData = base64_encode(json_encode([
                "threeDSMethodNotificationURL" => get_site_url(null, '?credorax_fingerprint_notification'),
                "threeDSServerTransID" => $parsedData['3ds_trxid'],
            ])); ?>
            <form id="credorax_fingerprint_form" action="<?php echo $parsedData['3ds_method']; ?>" method="POST">
                <input type="text" name="threeDSMethodData" value="<?php echo $threeDSMethodData; ?>">
            </form>
            <script>
                window.onload = function(){
                    parent.credorax_fingerprint_form_submitted = Date.now() + 10000;
                    document.getElementById('credorax_fingerprint_form').submit();
                }
            </script>
            <?php
            exit();
        }

        if (isset($_GET['credorax_fingerprint_notification']) && isset($_GET['threeDSMethodData'])) {
            $credorax3dCompind = (array) unserialize(rawurldecode(filter_input(INPUT_GET, 'threeDSMethodData')));
            print_r($credorax3dCompind);
            die;
            if ($credorax3dCompind['threeDSServerTransID'] === WC()->session->get(WC_Credorax_Gateway::KEY_CREDORAX_3DS_TRXID)) {
                WC()->session->set(WC_Credorax_Gateway::KEY_CREDORAX_3DS_COMPIND, 'Y');
            } ?>
            <script>
                parent.credorax_fingerprint_done=true;
            </script>
            <?php
            exit();
        }

        if (isset($_GET['credorax_challenge_callback'])) {
            $gateway = new WC_Credorax_Gateway();
            return $gateway->process_payment($_GET['credorax_challenge_callback']);
        }
    }
}
