<?php

namespace CodeConfig\EAW\App\CartManager;

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

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

class MenuCart
{
    use Singleton;
    protected $settings;

    public function doHooks()
    {
        $this->settings = AppSettings::getInstance();
        add_filter('wp_page_menu', [$this, 'create_primary_menu_cart_item'], PHP_INT_MAX, 2);
        add_filter('wp_nav_menu_items', [$this, 'create_menu_cart'], PHP_INT_MAX, 2);
    }

    public function create_primary_menu_cart_item($menu, $args)
    {
        if (!class_exists('WooCommerce') || (!is_customize_preview() && !$this->settings->getParams('mcEnable'))) {
            return $menu;
        }

        $selected_menus = $this->settings->getParams('mcMenusDisplay') ?: [];

        if (empty($selected_menus) || !isset($args['theme_location']) || $args['theme_location'] !== 'primary') {
            return $menu;
        }

        if (!strstr($menu, 'eaw-menu-cart')) {
            $menu .= $this->get_menu_cart_html();
        }

        return $menu;
    }

    public function create_menu_cart($items, $args)
    {
        if (!class_exists('WooCommerce') || (!is_customize_preview() && !$this->settings->getParams('mcEnable'))) {
            return $items;
        }

        $selected_menus = $this->settings->getParams('mcMenusDisplay') ?: [];
        if (empty($selected_menus)) {
            return $items;
        }

        // Get the menu slug or ID
        $menu_id = $args->menu->slug ?? $args->menu->term_id ?? $args->menu ?? '';
        if (!$menu_id || !in_array($menu_id, $selected_menus, true)) {
            return $items;
        }

        if (!strstr($items, 'eaw-menu-cart')) {
            $items .= $this->get_menu_cart_html();
        }

        return $items;
    }

    public function get_menu_cart_html()
    {
        wp_enqueue_style('eaw-cart-icons');
        wp_enqueue_style('eaw-menu-cart');
        wp_enqueue_script('eaw-menu-cart');

        $wc_cart        = class_exists('WooCommerce') ? WC()->cart : null;
        $mcContent      = $this->settings->getParams('mcContent');
        $mcDisplayStyle = $this->settings->getParams('mcDisplayStyle');
        $mcCartTotal    = $this->settings->getParams('mcCartTotal');
        $mcEmptyEnable  = $this->settings->getParams('mcEmptyEnable');
        $mcNavPage      = $this->settings->getParams('mcNavPage');

        $nav_url   = in_array($mcNavPage, ['cart', 'checkout']) ? esc_url(get_permalink(wc_get_page_id($mcNavPage))) : '#';
        $nav_title = '';
        switch ($mcNavPage) {
            case 'open_sidebar':
            case 'cart':
                $nav_title = esc_html__('View your shopping cart', 'essential-addons-for-woocommerce');
                break;
            case 'checkout':
                $nav_title = esc_html__('Quick checkout', 'essential-addons-for-woocommerce');
                break;
        }

        $cart_content_count = $wc_cart ? $wc_cart->get_cart_contents_count() : 0;
        $cart_total         = $wc_cart ? ($mcCartTotal === 'total' ? $wc_cart->get_total() : $wc_cart->get_cart_subtotal()) : wc_price(0);

        $class = [
            'eaw-menu-cart',
            is_rtl() ? 'eaw-menu-cart-rtl' : '',
            $mcContent ? 'eaw-menu-cart-show' : '',
            (is_customize_preview() && !$this->settings->getParams('mcEnable')) || (!$mcEmptyEnable && $wc_cart && $wc_cart->is_empty()) ? 'eaw-disabled' : '',
        ];
        $class = trim(implode(' ', array_filter($class)));

        ob_start();
        ?>
		<li class="<?php echo esc_attr($class); ?>"
			data-empty_enable="<?php echo esc_attr($mcEmptyEnable ? '1' : ''); ?>"
			data-open_sidebar="<?php echo esc_attr($mcNavPage === 'open_sidebar' ? '1' : ''); ?>">
			<a href="<?php echo esc_url($nav_url); ?>"
				title="<?php echo esc_attr(apply_filters('eaw_menu_nav_title', $nav_title)); ?>"
				class="eaw-menu-cart-nav-wrap">
				<span class="eaw-menu-cart-icon">
					<i class="<?php echo esc_attr($this->settings->getClassIcon($this->settings->getParams('mcIcon'), 'cart_icons')); ?>"></i>
				</span>
				<span class="eaw-menu-cart-text-wrap">
					<?php $this->get_menu_cart_text($mcDisplayStyle, $cart_total, $cart_content_count); ?>
				</span>
			</a>
			<?php if ($wc_cart && (is_customize_preview() || ($mcContent && !wp_is_mobile() && !is_cart() && !is_checkout()))) : ?>
				<div class="eaw-menu-cart-content-wrap">
					<div class="widget woocommerce widget_shopping_cart">
						<div class="widget_shopping_cart_content">
							<?php woocommerce_mini_cart(); ?>
						</div>
					</div>
				</div>
			<?php endif; ?>
		</li>
<?php
                return ob_get_clean();
    }

    public static function get_menu_cart_text($display_style, $cart_total, $cart_content_count)
    {
        if (!$display_style) {
            return;
        }

        switch ($display_style) {
            case 'product_counter':
                $text = $cart_content_count;
                break;
            case 'price':
                $text = $cart_total;
                break;
            default:
                $text = $cart_content_count . ' - ' . $cart_total;
        }

        $is_empty = !$cart_content_count ? ' eaw-menu-cart-empty' : '';
        echo sprintf(
            '<span class="eaw-menu-cart-text eaw-menu-cart-text-%s%s">%s</span>',
            esc_attr($display_style),
            esc_attr($is_empty),
            wp_kses_post($text)
        );
    }

    public function get_inline_css()
    {
        $css      = '';
        $frontend = Frontend::getInstance();

        $css .= $frontend->add_inline_style(
            ['.eaw-menu-cart .eaw-menu-cart-icon i'],
            ['mcIconColor'],
            ['color'],
            ['']
        );
        $css .= $frontend->add_inline_style(
            ['.eaw-menu-cart .eaw-menu-cart-nav-wrap:hover .eaw-menu-cart-icon i'],
            ['mcIconHoverColor'],
            ['color'],
            ['']
        );
        $css .= $frontend->add_inline_style(
            ['.eaw-menu-cart .eaw-menu-cart-text-wrap *'],
            ['mcColor'],
            ['color'],
            ['']
        );
        $css .= $frontend->add_inline_style(
            ['.eaw-menu-cart .eaw-menu-cart-nav-wrap:hover .eaw-menu-cart-text-wrap *'],
            ['mcHoverColor'],
            ['color'],
            ['']
        );

        return $css;
    }
}
