<?php
/*####################################################################
 # Copyright ©2020 UseePay Ltd. All Rights Reserved.                 #
 # This file may not be redistributed in whole or significant part.  #
 # This file is part of the UseePay package and should not be used   #
 # and distributed for any other purpose that is not approved by     #
 # UseePay Ltd.                                                      #
 # https://www.useepay.com                                           #
 ####################################################################*/

abstract class WC_UseePay_Inner_Payment_Gateway extends WC_Payment_Gateway
{

    public function payment_scripts() {
        if (
            ! is_product()
            && ! WC_Useepay_Inner_Helper::has_cart_or_checkout_on_current_page()
            && ! $this->is_valid_pay_for_order_endpoint()
            && ! is_add_payment_method_page()
            && ! isset( $_GET['change_payment_method'] )
            && ! ( ! empty( get_query_var( 'view-subscription' ) )
                && is_callable( 'WCS_Early_Renewal_Manager::is_early_renewal_via_modal_enabled' )
                && WCS_Early_Renewal_Manager::is_early_renewal_via_modal_enabled()
            )
            || is_order_received_page()
        ) {
            return;
        }

        if ( 'no' === $this->get_option('enabled') ) {
            return;
        }

        $suffix =  $this->isDebug() ? '' : '.min';
        $script_relative_path = 'assets/js/useepay-drop-in-card' . $suffix . '.js';
        $script_version = $this->get_local_asset_version($script_relative_path);

        $sdk_url = $this->isDebug()
            ? 'https://cashier1.uat.useepay.com/jssdkV3/1.0.1/useepay.min.js'
            : 'https://cashier.useepay.com/jssdkV3/1.0.1/useepay.min.js';

        wp_register_script(
            'woocommerce_useepay',
            $sdk_url,
            [],
            WC_USEEPAY_INNER_VERSION,
            true
        );
        wp_enqueue_script( 'woocommerce_useepay' );

        wp_register_script(
            'woocommerce_useepay_init',
            plugins_url( '../' . $script_relative_path, __FILE__ ),
            array( 'woocommerce_useepay', 'jquery' ),
            $script_version,
            true
        );
        wp_enqueue_script( 'woocommerce_useepay_init' );

        wp_localize_script(
            'woocommerce_useepay_init',
            'wc_useepay_params',
            apply_filters( 'wc_useepay_params', $this->get_js_params() )
        );
    }

    private function isDebug(){
        $options = get_option('woocommerce_' . $this->id . '_settings', []);
        $sandbox_mode       = isset($options["testMode"]) && 'yes' === $options["testMode"];
        return (bool)$sandbox_mode;

    }

    private function get_local_asset_version($relative_path) {
        $asset_path = plugin_dir_path(dirname(__FILE__)) . ltrim($relative_path, '/\\');

        if (file_exists($asset_path)) {
            $mtime = filemtime($asset_path);
            if ($mtime) {
                return (string) $mtime;
            }
        }

        return WC_USEEPAY_INNER_VERSION;
    }


    public function get_js_params(){
        $options = get_option('woocommerce_' . $this->id . '_settings', []);
        $sandbox_mode       = isset($options["testMode"]) && 'yes' === $options["testMode"];
        $endpoint           = $sandbox_mode ? 'UAT' : 'PRODUCTION';
        $merchantNo         = $options["merchantNo"];
        $appId          = $options["useepay_app_id"];

        $parmas = [
            'appId' => $appId,
            'merchantId'    => $merchantNo,
            'env'    => $endpoint
        ];
        return array_merge($parmas);
    }

    /**
     * Checks if the current page is the pay for order page and the current user is allowed to pay for the order.
     *
     * @return bool
     */
    public function is_valid_pay_for_order_endpoint(): bool {

        // If not on the pay for order page, return false.
        if ( ! is_wc_endpoint_url( 'order-pay' ) || ! isset( $_GET['key'] ) ) {
            return false;
        }

        $order_id = absint( get_query_var( 'order-pay' ) );
        $order    = wc_get_order( $order_id );

        // If the order is not found or the param `key` is not set or the order key does not match the order key in the URL param, return false.
        if ( ! $order || ! isset( $_GET['key'] ) || wc_clean( wp_unslash( $_GET['key'] ) ) !== $order->get_order_key() ) {
            return false;
        }

        // If the order doesn't need payment, we don't need to prepare the payment page.
        if ( ! $order->needs_payment() ) {
            return false;
        }

        return current_user_can( 'pay_for_order', $order->get_id() );
    }
}
