<?php

namespace Sibs2;

defined('ABSPATH') || exit;

class sibsGeneralFunctions
{
    /**
     * @var int
     */
    public static $percent = 100;

    /**
     * SIBS Get Payment Gateway Variable.
     *
     * @param string $payment_id
     * @return array
     */
    public static function sibs_get_payment_gateway_variable($payment_id)
    {
        $payment_gateway                  = [];
        $payment_gateway['payment_type']  = self::sibs_get_payment_type($payment_id);
        $payment_gateway['payment_brand'] = self::sibs_get_payment_brand($payment_id);
        $payment_gateway['payment_group'] = self::sibs_get_payment_group($payment_id);
        $payment_gateway['is_recurring']  = self::sibs_is_recurring($payment_id);
        $payment_gateway['language']      = sibsFunctions::get_language();

        return $payment_gateway;
    }

    /**
     * SIBS Get Credentials.
     *
     * @param string $payment_id
     * @param bool $is_testmode_available
     * @param bool $is_multichannel_available
     * @return array
     */
    public static function sibs_get_credentials($payment_id, $is_testmode_available = true, $is_multichannel_available = false)
    {
        $payment_settings = sibsConfig::getPaymentOption($payment_id);

        $credentials                = [];
        $credentials['server_mode'] = sibsConfig::getEnvironment();
        $credentials['channel_id']  = (! empty($payment_settings['multichannel']) && $is_multichannel_available) ? $payment_settings['channel_moto'] : sibsConfig::getTerminalId();

        if ($is_testmode_available) {
            $credentials['test_mode'] = self::sibs_get_test_mode($credentials['server_mode']);
        }

        return $credentials;
    }

    /**
     * SIBS Get Test Mode.
     *
     * @param string $server_mode
     * @return string
     */
    public static function sibs_get_test_mode($server_mode)
    {
        if ($server_mode === 'LIVE') {
            return false;
        }

        return 'EXTERNAL';
    }

    /**
     * SIBS Get Recurring Payment.
     *
     * @return string
     */
    public static function sibs_get_recurring_payment()
    {
        $payments = [
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED,
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED,
        ];

        return $payments;
    }

    /**
     * SIBS Get Payment Brand.
     *
     * @param string $payment_id
     * @return string
     */
    public static function sibs_get_payment_brand($payment_id)
    {
        switch ($payment_id) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD:
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
                $payment_brand = self::sibs_get_payment_brand_cards($payment_id);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_BLIK;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_PAY_BY_LINK;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_PBLKV;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_XPAY;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_GPAY:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_XPAY;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_APAY:
                $payment_brand = sibsConstants::SIBS_PAYMENT_METHOD_XPAY;

                break;
            default:
                $payment_brand = false;
        }

        return $payment_brand;
    }

    /**
     * SIBS Get Payment Brand Card.
     *
     * @param string $payment_id
     * @return string
     */
    public static function sibs_get_payment_brand_cards($payment_id)
    {
        $cards            = sibsConfig::getPaymentOption($payment_id, 'card_types');
        $payment_brand    = '';

        if (! empty($cards) && is_array($cards)) {
            foreach ($cards as $card) {
                $payment_brand .= strtoupper($card) . ' ';
            }
        }

        return $payment_brand;
    }

    /**
     * SIBS Get Payment Type.
     *
     * @param string $payment_id
     * @return string
     */
    public static function sibs_get_payment_type($payment_id)
    {
        $payment_auth_db = [
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED,
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DEBIT_CARD,
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT,
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED,
            sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD,
            //sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY,
            //sibsConstants::SIBS_PAYMENT_METHOD_ORDER_APAY,
            //sibsConstants::SIBS_PAYMENT_METHOD_ORDER_GPAY,
        ];

        if (in_array($payment_id, $payment_auth_db)) {
            $trans_mode = sibsConfig::getPaymentOption($payment_id, 'trans_mode');

            return ! empty($trans_mode) ? $trans_mode : sibsConstants::SPG_PAYMENT_TYPE_PURS;
        } else {
            return sibsConstants::SPG_PAYMENT_TYPE_PURS;
        }
    }

    /**
     * SIBS Get Payment Group.
     *
     * @param string $payment_id
     * @return string
     */
    public static function sibs_get_payment_group($payment_id)
    {
        switch ($payment_id) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
                $payment_group = sibsConstants::SIBS_PAYMENT_METHOD_CC;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED:
                $payment_group = sibsConstants::SIBS_PAYMENT_METHOD_DD;

                break;
            default:
                $payment_group = false;
        }

        return $payment_group;
    }

    /**
     * SIBS Get Payment ID By Groupt.
     *
     * @param string $payment_group
     * @return string
     */
    public static function sibs_get_payment_id_by_group($payment_group)
    {
        switch ($payment_group) {
            case sibsConstants::SIBS_PAYMENT_METHOD_CC:
                $payment_id = sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED;

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_DD:
                $payment_id = sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED;

                break;
            default:
                $payment_id = false;
        }

        return $payment_id;
    }

    /**
     * SIBS Is Recurring.
     *
     * @param string $payment_id
     * @return bool
     */
    public static function sibs_is_recurring($payment_id)
    {
        return
            $payment_id === sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED ||
            $payment_id === sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED;
    }

    /**
     * SIBS Get Account By Result.
     *
     * @param string $payment_id
     * @param array $payment_result
     * @return array
     */
    public static function sibs_get_account_by_result($payment_id, $payment_result)
    {
        switch ($payment_id) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
                $account_card['holder']        = $payment_result['card']['holder'];
                $account_card['last_4_digits'] = $payment_result['card']['last4Digits'];
                $account_card['expiry_month']  = $payment_result['card']['expiryMonth'];
                $account_card['expiry_year']   = $payment_result['card']['expiryYear'];
                $account_card['email']         = '';

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED:
                $account_card['holder']        = $payment_result['bankAccount']['holder'];
                $account_card['last_4_digits'] = substr($payment_result['bankAccount']['iban'], -4);
                $account_card['expiry_month']  = '';
                $account_card['expiry_year']   = '';
                $account_card['email']         = '';

                break;
        }

        return $account_card;
    }

    /**
     * Translate Frontend Payment Name.
     *
     * @param string $payment_id payment id.
     * @return string
     */
    public static function sibs_translate_frontend_payment($payment_id)
    {
        $payment_locale = '';

        switch ($payment_id) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD:
                $payment_locale = __('Cards', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
                $payment_locale = __('Cards (Recurring)', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DEBIT_CARD:
                $payment_locale = __('Debit Cards', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT:
                $payment_locale = __('Direct Debit', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED:
                $payment_locale = __('Direct Debit', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK:
                $payment_locale = __('BLIK', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK:
                $payment_locale = __('Pay by Link', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN:
                $payment_locale = __('Pay by Link', sibsConstants::SIBS_TRANSLATE);

                break;
            default:
                $payment_locale = '';

                break;
        }

        return $payment_locale;
    }

    /**
     * Translate Backend Payment Name.
     *
     * @param string $payment_id payment id.
     * @return string
     */
    public static function sibs_translate_backend_payment($payment_id)
    {
        $payment_locale = '';

        switch ($payment_id) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD:
                $payment_locale = __('SIBS Cards', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD_SAVED:
                $payment_locale = __('Cards (Recurring)', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DEBIT_CARD:
                $payment_locale = __('Debit Cards', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT:
                $payment_locale = __('Direct Debit', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_DIRECT_DEBIT_SAVED:
                $payment_locale = __('Direct Debit (Recurring)', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK:
                $payment_locale = __('SIBS BLIK', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK:
                $payment_locale = __('SIBS Pay By Link', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN:
                $payment_locale = __('SIBS Pay By Link', sibsConstants::SIBS_TRANSLATE);

                break;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY:
                $payment_locale = __('SIBS Google Pay / Apple Pay', sibsConstants::SIBS_TRANSLATE);

                break;
            default:
                $payment_locale = '';

                break;
        }

        return $payment_locale;
    }

    /**
     * Translate Additional Information Name.
     *
     * @param string $info_name info name.
     * @return string
     */
    public static function sibs_translate_additional_information($info_name)
    {
        switch ($info_name) {
            case 'Interest':
                return __('Interest', sibsConstants::SIBS_TRANSLATE);
            case 'Order Total':
                return __('Order Total', sibsConstants::SIBS_TRANSLATE);
            default:
                return $info_name;
        }
    }

    /**
     * Get _REQUEST value.
     *
     * @param string $key key.
     * @param string $default default.
     * @return value
     */
    public static function sibs_get_request_value($key, $default = false)
    {
        if (isset($_REQUEST[$key])) {
            return sanitize_text_field(wp_unslash($_REQUEST[$key]));
        }

        return $default;
    }

    /**
     * Include template.
     *
     * @param string $template_file_path template file path (templates/template.php).
     * @param array  $args variable to include in template.
     */
    public static function sibs_include_template($template_file_path, $args = [])
    {
        if (function_exists('wc_get_template')) {
            $template      = pathinfo($template_file_path);
            $template_path = $template['dirname'] . '/';
            $template_file = $template['basename'];
            wc_get_template(
                $template_file,
                $args,
                $template_path,
                $template_path
            );
        } else {
            foreach ($args as $key => $value) {
                $$key = $value;
            }
            include $template_file_path;
        }
    }

    /**
     * Check if billing address and shipping addres are equal.
     *
     * @return bool
     */
    public static function sibs_is_address_billing_equal_shipping()
    {
        $customer                 = WC()->customer;
        $billing['street']        = "{$customer->address_1}, {$customer->address_2}";
        $billing['city']          = $customer->city;
        $billing['zip']           = $customer->postcode;
        $billing['country_code']  = $customer->country;
        $shipping['street']       = "{$customer->shipping_address_1}, {$customer->shipping_address_2}";
        $shipping['city']         = $customer->shipping_city;
        $shipping['zip']          = $customer->shipping_postcode;
        $shipping['country_code'] = $customer->shipping_country;

        foreach ($billing as $i => $bill) {
            if ($bill !== $shipping[$i]) {
                return false;
            }
        }

        return true;
    }

    /**
     * Get customer order count.
     *
     * @return int count
     */
    public static function sibs_get_order_count()
    {
        if (wc_get_customer_order_count(get_current_user_id()) > 0) {
            return wc_get_customer_order_count(get_current_user_id());
        }

        return 0;
    }

    /**
     * Convert SPG payment status to WooCommerce status by payment type.
     *
     * @param string $payment_type DPG payment type
     * @return string WooCommerce status
     */
    public static function convertTransactionStatusByPaymentType($payment_type)
    {
        return ($payment_type === sibsConstants::SPG_PAYMENT_TYPE_AUTH) ?
            sibsConstants::SIBS_ORDER_STATUS_AUTHORIZED :
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_PROCESSING;
    }

    /**
     * Convert SPG payment status to WooCommerce status.
     *
     * @param string $payment_status SPG payment status
     * @param string  $payment_type SPG payment type
     * @return string WooCommerce status
     */
    public static function convertTransactionStatus($payment_status, $payment_type)
    {
        switch ($payment_status) {
            case sibsConstants::SIBS_RESULT_SUCCESS:
            case sibsConstants::SIBS_RESULT_PARTIAL:
                return self::convertTransactionStatusByPaymentType($payment_type);
            case sibsConstants::SIBS_RESULT_IN_PROCESSING:
            case sibsConstants::SIBS_RESULT_PENDING:
                return sibsConstants::WOOCOMMERCE_ORDER_STATUS_ON_HOLD;
            case sibsConstants::SIBS_RESULT_DECLINED:
            case sibsConstants::SIBS_RESULT_TIMEOUT:
            case sibsConstants::SIBS_RESULT_ERROR:
            default:
                return sibsConstants::WOOCOMMERCE_ORDER_STATUS_FAILED;
        }
    }

    /**
     * Convert Capture and Refund Status.
     *
     * @param string $payment_status webhook transaction status
     * @return string WooCommerce status
     */
    public static function convertTransactionStatusCaptRfnd($payment_status)
    {
        switch ($payment_status) {
            case sibsConstants::SIBS_RESULT_SUCCESS:
            case sibsConstants::SIBS_RESULT_PARTIAL:
                return sibsConstants::SIBS_PAYMENT_STATUS_REFUND_COMPLETED;
            case sibsConstants::SIBS_RESULT_IN_PROCESSING:
            case sibsConstants::SIBS_RESULT_PENDING:
                return sibsConstants::SIBS_PAYMENT_STATUS_REFUND_PROGRESS;
            case sibsConstants::SIBS_RESULT_DECLINED:
            case sibsConstants::SIBS_RESULT_TIMEOUT:
            case sibsConstants::SIBS_RESULT_ERROR:
                return sibsConstants::SIBS_PAYMENT_STATUS_REFUND_FAILED;
        }
    }

    /**
     * SIBS SPG get Payment Method.
     *
     * @return string
     */
    public static function sibs_spg_get_payment_method($payment_method)
    {
        switch ($payment_method) {
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_BLIK:
                return sibsConstants::SIBS_PAYMENT_METHOD_BLIK;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_CREDIT_CARD:
                return sibsConstants::SIBS_PAYMENT_METHOD_CARD;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK:
                return sibsConstants::SIBS_PAYMENT_METHOD_PAY_BY_LINK;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_PAY_BY_LINK_KEVIN:
                return sibsConstants::SIBS_PAYMENT_METHOD_PBLKV;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_XPAY:
                return sibsConstants::SIBS_PAYMENT_METHOD_XPAY;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_GPAY:
                return sibsConstants::SIBS_PAYMENT_METHOD_GPAY;
            case sibsConstants::SIBS_PAYMENT_METHOD_ORDER_APAY:
                return sibsConstants::SIBS_PAYMENT_METHOD_APAY;
            default:
                return $payment_method;
        }
    }

    /**
     * Process Refund Successfull.
     *
     * @param int $order_id
     * @return bool
     */
    public static function processRefundSucessfull($order_id)
    {
        $args = [
            'post_parent' => $order_id,
            'post_type'   => 'shop_order_refund',
        ];

        $child_posts  = get_children($args);
        $stringSearch = esc_attr(__('Order Fully Refunded', sibsConstants::SIBS_TRANSLATE));
        $posts        = self::sibs_search_array_by_postmeta($child_posts, $stringSearch, '_refund_reason');

        if (count($posts) > 0) {
            wp_delete_post($posts->ID, true);
        }

        sibsGeneralModels::sibs_update_db_transaction_log_status($order_id, sibsConstants::WOOCOMMERCE_ORDER_STATUS_REFUNDED);

        return true;
    }

    /**
     * SIBS Search Array By Post Meta.
     *
     * @param array $array
     * @param string $string
     * @param string $postmeta_key
     * @return mixed
     */
    public static function sibs_search_array_by_postmeta($array, $string, $postmeta_key = '')
    {
        foreach ($array as $val) {
            $postmeta = get_post_meta($val->ID, $postmeta_key, true);

            if (str_contains($postmeta, $string)) {
                return $val;
            }
        }

        return null;
    }

    /**
     * SIBS Search Array By Value.
     *
     * @param string $value
     * @param array $array
     * @return mixed
     */
    public static function sibs_search_array_by_value($value, $array)
    {
        foreach ($array as $val) {
            if ($val->post_excerpt === $value) {
                return $val;
            }
        }

        return null;
    }

    /**
     * Get Page Link.
     *
     * @param string $page_prefix
     * @return string|false
     */
    public static function get_page_link($page_prefix)
    {
        $location               = __('en_US', sibsConstants::SIBS_TRANSLATE);
        $location_lower         = strtolower($location);
        $page_prefix_translated = "{$page_prefix}_{$location_lower}";

        return get_permalink(sibsConfig::getWoocommerceOption("{$page_prefix_translated}_id"));
    }

    /**
     * Is Already Paid Or Authorized.
     *
     * @param string $order_status
     * @return bool
     */
    public static function isAlreadyPaidOrAuthorized($order_status)
    {
        return in_array($order_status, [
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_PROCESSING,
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_COMPLETED,
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_REFUNDED,
            sibsConstants::SIBS_ORDER_STATUS_PARTIALLY_CAPTURED,
            sibsConstants::SIBS_ORDER_STATUS_PARTIALLY_REFUNDED,
            sibsConstants::SIBS_ORDER_STATUS_AUTHORIZED,
            sibsConstants::SIBS_ORDER_STATUS_PENDING_REFUND,
        ]);
    }

    /**
     * Is Already Captured.
     *
     * @param string $order_status
     * @return bool
     */
    public static function isAlreadyCaptured($order_status)
    {
        return in_array($order_status, [
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_PROCESSING,
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_COMPLETED,
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_REFUNDED,
            sibsConstants::SIBS_ORDER_STATUS_PARTIALLY_REFUNDED,
            sibsConstants::SIBS_ORDER_STATUS_PENDING_REFUND,
        ]);
    }

    /**
     * Is Already Refunded.
     *
     * @param string $order_status
     * @return bool
     */
    public static function isAlreadyRefunded($order_status)
    {
        return in_array($order_status, [
            sibsConstants::WOOCOMMERCE_ORDER_STATUS_REFUNDED,
        ]);
    }
}
