<?php

namespace fluXtore\Core\Frontend\Checkout;

use fluXtore\Core\Settings\fluXtore_Gateway_Settings;
use fluXtore\Core\Settings\fluXtore_Settings;

if ( ! defined( 'ABSPATH' ) ) {
        exit;
}

if ( ! class_exists( 'fluXtore_Checkout_Gateways' ) ) {
        class fluXtore_Checkout_Gateways {
                /**
                 * @var self|null
                 */
                private static $instance = null;

                private function __construct() {}

                public static function init() {
                        if ( null !== self::$instance ) {
                                return;
                        }

                        self::$instance = new self();

                        add_action( 'fluxtore_before_checkout', [ self::$instance, 'render_checkout_gateways' ], 15 );
                }

                /**
                 * Render gateway prompts when available.
                 */
                public function render_checkout_gateways() {
                        if ( is_admin() ) {
                                return;
                        }

                        if ( ! function_exists( 'WC' ) || ! is_a( WC(), '\\WC' ) ) {
                                return;
                        }

                        $cart = WC()->cart;

                        if ( ! $cart || $cart->is_empty() ) {
                                return;
                        }

                        $definitions = fluXtore_Gateway_Settings::get_gateway_definitions();
                        $available   = [];

                        foreach ( $definitions as $gateway_id => $definition ) {
                                if ( ! $this->is_gateway_enabled( $definition ) ) {
                                        continue;
                                }

                                if ( ! $this->matches_customer_conditions( $definition, $cart ) ) {
                                        continue;
                                }

                                $available[] = [
                                        'id'    => $gateway_id,
                                        'label' => $definition['label'],
                                        'type'  => isset( $definition['type'] ) ? $definition['type'] : 'bnpl',
                                ];
                        }

                        if ( empty( $available ) ) {
                                return;
                        }

                        $this->output_markup( $available );
                }

                private function is_gateway_enabled( array $definition ) {
                        $option = isset( $definition['option'] ) ? $definition['option'] : '';

                        if ( '' === $option ) {
                                return false;
                        }

                        if ( ! $this->is_truthy( fluXtore_Settings::get( $option, false ) ) ) {
                                return false;
                        }

                        if ( ! empty( $definition['plugin'] ) && ! $this->is_plugin_active( $definition['plugin'] ) ) {
                                return false;
                        }

                        return true;
                }

                private function matches_customer_conditions( array $definition, $cart ) {
                        $currency = function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : '';
                        $total    = isset( $cart->total ) ? (float) $cart->total : 0.0;
                        $country  = $this->get_relevant_country();

                        if ( ! empty( $definition['currencies'] ) && ! in_array( $currency, $definition['currencies'], true ) ) {
                                return false;
                        }

                        if ( ! empty( $definition['countries'] ) && ! in_array( $country, $definition['countries'], true ) ) {
                                return false;
                        }

                        if ( isset( $definition['min_total'] ) && $definition['min_total'] > 0 && $total < $definition['min_total'] ) {
                                return false;
                        }

                        if ( isset( $definition['max_total'] ) && $definition['max_total'] > 0 && $total > $definition['max_total'] ) {
                                return false;
                        }

                        return true;
                }

                private function get_relevant_country() {
                        if ( ! function_exists( 'WC' ) || ! is_a( WC(), '\\WC' ) ) {
                                return '';
                        }

                        $customer = WC()->customer;

                        if ( ! $customer ) {
                                return '';
                        }

                        $billing = method_exists( $customer, 'get_billing_country' ) ? $customer->get_billing_country() : '';

                        if ( ! empty( $billing ) ) {
                                return $billing;
                        }

                        $shipping = method_exists( $customer, 'get_shipping_country' ) ? $customer->get_shipping_country() : '';

                        if ( ! empty( $shipping ) ) {
                                return $shipping;
                        }

                        return '';
                }

                private function is_plugin_active( $plugin_file ) {
                        return function_exists( 'is_plugin_active' ) && is_plugin_active( $plugin_file );
                }

                private function output_markup( array $gateways ) {
                        static $rendered = false;

                        if ( $rendered ) {
                                return;
                        }

                        $rendered = true;

                        ?>
                        <div class="fluxtore-checkout-gateways">
                                <p class="fluxtore-checkout-gateways__title">
                                        <?php echo esc_html__( 'Preferred payment options', 'fluxtore' ); ?>
                                </p>
                                <div class="fluxtore-checkout-gateways__actions">
                                        <?php foreach ( $gateways as $gateway ) : ?>
                                                <button
                                                        type="button"
                                                        class="fluxtore-checkout-gateways__button"
                                                        data-gateway="<?php echo esc_attr( $gateway['id'] ); ?>"
                                                >
                                                        <?php echo esc_html( $gateway['label'] ); ?>
                                                </button>
                                        <?php endforeach; ?>
                                </div>
                                <input type="hidden" name="fluxtore_preferred_gateway" id="fluxtore_preferred_gateway" value="" />
                        </div>
                        <script>
                                ( function () {
                                        const container = document.querySelector('.fluxtore-checkout-gateways');
                                        if (!container) {
                                                return;
                                        }

                                        const hiddenField = document.getElementById('fluxtore_preferred_gateway');
                                        if (!hiddenField) {
                                                return;
                                        }

                                        container.addEventListener('click', function (event) {
                                                const button = event.target.closest('[data-gateway]');
                                                if (!button) {
                                                        return;
                                                }

                                                event.preventDefault();

                                                const currentActive = container.querySelector('.fluxtore-checkout-gateways__button.is-active');
                                                if (currentActive) {
                                                        currentActive.classList.remove('is-active');
                                                }

                                                button.classList.add('is-active');
                                                hiddenField.value = button.dataset.gateway;
                                        });
                                })();
                        </script>
                        <?php
                }

                private function is_truthy( $value ) {
                        if ( is_bool( $value ) ) {
                                return $value;
                        }

                        if ( is_numeric( $value ) ) {
                                return (bool) intval( $value );
                        }

                        if ( is_string( $value ) ) {
                                $filtered = filter_var( $value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE );

                                if ( null !== $filtered ) {
                                        return $filtered;
                                }
                        }

                        return false;
                }
        }
}

fluXtore_Checkout_Gateways::init();
