<?php

namespace CodeConfig\EAW\App\CartManager;

use CodeConfig\EAW\AppSettings;
use CodeConfig\EAW\Utils\Singleton;

defined('ABSPATH') || exit('No direct script access allowed');

class AddToCartButton
{
    use Singleton;
    protected $settings;
    protected $language;


    public function doHooks()
    {
        $this->settings = AppSettings::getInstance();
        update_option('woocommerce_enable_ajax_add_to_cart', $this->settings->getParams('enableAjaxATC') ? 'yes' : 'no');
        if ($this->settings->getParams('atcBtnHoverEffect')) {
            add_filter('woocommerce_loop_add_to_cart_link', [$this, 'eawWcLoopAddToCartLink'], PHP_INT_MAX, 1);
        }

        if ($this->settings->getParams('atcBtnTextEnable')) {
            $this->language = null;
            add_filter('woocommerce_product_add_to_cart_text', [$this, 'eawWcProductAddToCartText'], PHP_INT_MAX, 2);
        }

        add_action('eaw_before_add_to_cart_button', [$this, 'eawWcBeforeAddToCartButton']);
        add_action('eaw_after_add_to_cart_button', [$this, 'eawWcAfterAddToCartButton']);

        add_action('wp_enqueue_scripts', [$this, 'enqueueScripts']);

        add_filter('init', [$this, 'redirectCartPageAfterCart'], 9999);

        add_action('woocommerce_add_to_cart', [$this, 'redirectCartPageAfterCart'], 9999);
    }

    public function enqueueScripts()
    {
        if (is_admin() || is_customize_preview()) {
            return;
        }


        // TODO: need to optimize this
        wp_enqueue_script('eaw-ajax-atc', CCPEAW_ASSETS . '/js/' . 'ajax-add-to-cart.js', ['jquery'], CCPEAW_VERSION, false);
        $args = [
            'isAjaxAtcEnabled'                    => 1,
            'wc_ajax_url'                         => \WC_AJAX::get_endpoint("%%endpoint%%"),
            'nonce'                               => wp_create_nonce('ccpeaw'),
            'woocommerce_enable_ajax_add_to_cart' => 'yes' === get_option('woocommerce_enable_ajax_add_to_cart') ? 1 : '',
            'added_to_cart'                       => did_action('woocommerce_add_to_cart') ?: '',
            'ajax_atc_pd_exclude'                 => $this->settings->getParams('ajax_atc_pd_exclude') ?? [],
            'i18n_make_a_selection_text'          => apply_filters('eaw-i18n_make_a_selection_text', esc_html__('Please select some product options before adding this product to your cart.', 'essential-addons-for-woocommerce')),
            'i18n_unavailable_text'               => apply_filters('eaw-i18n_unavailable_text', esc_html__('Sorry, this product is unavailable. Please choose a different combination.', 'essential-addons-for-woocommerce')),
            'cart_url'                            => apply_filters('woocommerce_add_to_cart_redirect', wc_get_cart_url(), null),
            'cart_redirect_after_add'             => get_option('woocommerce_cart_redirect_after_add'),
        ];
        wp_localize_script('eaw-ajax-atc', 'eawAtcVars', $args);
    }
    public function eawWcBeforeAddToCartButton()
    {
        ?>
		<div class="eaw-before-add-to-cart">
			<?php do_action('woocommerce_before_add_to_cart_button'); ?>
		</div>
<?php
    }
    public function eawWcLoopAddToCartLink($result)
    {
        $result = str_replace('class="', 'class="eaw-effect-' . $this->settings->getParams('atcBtnHoverEffect') . ' ', $result);

        return $result;
    }
    public function eawWcAfterAddToCartButton()
    {

        if (function_exists('gtm4wp_woocommerce_single_add_to_cart_tracking')) {
            gtm4wp_woocommerce_single_add_to_cart_tracking();
        }
    }

    public function eawWcProductAddToCartText($text, $product)
    {
        if (! $product) {
            global $product;
        }
        if ($product && ($product->is_type('variable') ||  $product->is_type('grouped') ||  $product->is_type('simple') || $product->is_type('external'))) {
            if ($this->language === null) {
                if (is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
                    $default_lang     = apply_filters('wpml_default_language', null);
                    $current_language = apply_filters('wpml_current_language', null);
                    if ($current_language && $current_language !== $default_lang) {
                        $this->language = "_$current_language";
                    }
                } elseif (class_exists('Polylang')) {
                    $default_lang     = pll_default_language('slug');
                    $current_language = pll_current_language('slug');
                    if ($current_language && $current_language !== $default_lang) {
                        $this->language = "_$current_language";
                    }
                }
                $this->language ??= '';
            }

            $buttonTextSettings = [
                'simple'   => $this->settings->getParams('simpleProductBtnTxt', $text),
                'variable' => $this->settings->getParams('variationButtonText', __('Select Variation', 'essential-addons-for-woocommerce')),
                'grouped'  => $this->settings->getParams('groupedButtonText', __('View Products', 'essential-addons-for-woocommerce')),
                'external' => $this->settings->getParams('externalButtonText', __('Buy Now', 'essential-addons-for-woocommerce')),
            ];

            return $buttonTextSettings[$product->get_type()] ?? $buttonTextSettings['simple'];
        }

        return $text;
    }

    public function redirectCartPageAfterCart($url)
    {
        $redirectSettings = $this->settings->getParams('redirectCartPageForSimpleProduct');
        if ($redirectSettings && !is_cart()) {
            $currentOption = get_option('woocommerce_cart_redirect_after_add');

            if ($currentOption !== 'yes') {
                update_option('woocommerce_cart_redirect_after_add', 'yes');
            }
        } else {
            update_option('woocommerce_cart_redirect_after_add', 'no');
        }
    }
}
