<?php

namespace CodeConfig\EAW;

use CodeConfig\EAW\App\CartManager\MenuCart;
use CodeConfig\EAW\Customizer__premium_only\Design;
use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;
defined( 'ABSPATH' ) || exit( 'No direct script access allowed' );
class Enqueue {
    use Singleton;
    /**
     * Initialize hooks
     *
     * @return void
     */
    private function doHooks() : void {
        add_action( 'admin_enqueue_scripts', [$this, 'adminEnqueue'] );
        add_action( 'wp_enqueue_scripts', [$this, 'frontendEnqueue'] );
        add_action( 'customize_preview_init', [$this, 'customize_preview_init'] );
        add_action( 'customize_controls_enqueue_scripts', [$this, 'customize_controls_enqueue_scripts'] );
    }

    private function style( string $handle, array $deps = [], $args = [] ) {
        $_args = [
            'ver'       => CCPEAW_VERSION,
            'folder'    => "css",
            'in_footer' => false,
            'type'      => 'enqueue',
            'nesting'   => false,
        ];
        $args = wp_parse_args( $args, $_args );
        if ( $args['nesting'] ) {
            $args['folder'] = "css/{$handle}";
        }
        $filePath = CCPEAW_ASSETS . "/{$args['folder']}/{$handle}.css";
        if ( $args['type'] === 'enqueue' ) {
            wp_enqueue_style(
                "ccpeaw-" . $handle,
                $filePath,
                $deps,
                $args['ver']
            );
        } elseif ( $args['type'] === 'register' ) {
            wp_register_style(
                "ccpeaw-" . $handle,
                $filePath,
                $deps,
                $args['ver']
            );
        }
    }

    private function r_style( string $handle, array $deps = [], $args = [] ) {
        $args['type'] = 'register';
        $this->style( $handle, $deps, $args );
    }

    private function script( string $handle, array $deps = [], $args = [] ) : void {
        $_args = [
            'ver'       => CCPEAW_VERSION,
            'folder'    => "js",
            'in_footer' => true,
            'type'      => 'enqueue',
        ];
        $args = wp_parse_args( $args, $_args );
        $assetsPath = CCPEAW_PATH . "assets/{$args['folder']}/{$handle}.asset.php";
        $filePath = CCPEAW_ASSETS . "/{$args['folder']}/{$handle}.js";
        if ( file_exists( $assetsPath ) ) {
            $assets = (include $assetsPath);
            if ( defined( 'WP_ENVIRONMENT_TYPE' ) && WP_ENVIRONMENT_TYPE === 'local' ) {
                $args['ver'] = $assets['version'];
            }
            $deps = wp_parse_args( $deps, $assets['dependencies'] );
        }
        if ( $args['type'] === 'enqueue' ) {
            wp_enqueue_script(
                "ccpeaw-" . $handle,
                $filePath,
                $deps,
                $args['ver'],
                $args['in_footer']
            );
        } elseif ( $args['type'] === 'register' ) {
            wp_register_script(
                "ccpeaw-" . $handle,
                $filePath,
                $deps,
                $args['ver'],
                $args['in_footer']
            );
        }
    }

    private function r_script( string $handle, array $deps = [], $args = [] ) {
        $args['type'] = 'register';
        $this->script( $handle, $deps, $args );
    }

    /**
     * Enqueue admin scripts and styles
     *
     * @param string $hook Current admin page hook
     * @return void
     */
    public function adminEnqueue( string $hook ) : void {
        $this->common_scripts( $hook );
        $this->script( 'settings', [
            'ccpeaw-common',
            'wp-util',
            'select2',
            'ccpeaw-sweetalert'
        ] );
        $this->style( 'settings' );
        $this->r_style( 'admin' );
        if ( Helpers::getSetting( 'pvEnable' ) ) {
            $this->script( 'pv-admin' );
            wp_localize_script( 'ccpeaw-pv-admin', 'ccpeaw_pv_var', [
                'placeholder_image' => esc_url( CCPEAW_ASSETS . '/admin/images/product-variation/placeholder.svg' ),
                'upload_image'      => esc_url( CCPEAW_ASSETS . '/admin/images/product-variation/upload.svg' ),
                'remove_image'      => esc_url( CCPEAW_ASSETS . '/admin/images/product-variation/remove.svg' ),
            ] );
        }
    }

    /**
     * Enqueue common scripts and styles
     *
     * @param string $hook Current page hook
     * @param string $context Context (admin or frontend)
     * @return void
     */
    public function common_scripts( string $hook, string $context = 'admin' ) : void {
        if ( $context === 'admin' ) {
            wp_enqueue_media();
        }
        $this->style( 'common' );
        $this->script( 'common', ['jquery', 'wp-util'] );
        $this->script( 'sweetalert', ['jquery'], [
            'folder' => 'plugins',
        ] );
        $this->style( 'animate.min', [], [
            'folder' => 'plugins',
        ] );
        wp_localize_script( 'ccpeaw-common', 'ccpeaw', $this->getLocalizeData( $hook, $context ) );
    }

    /**
     * Enqueue frontend scripts and styles
     *
     * @return void
     */
    public function frontendEnqueue() : void {
        $this->common_scripts( '', 'frontend' );
        $this->style( 'frontend' );
        // $this->style('menu.min', [], ['folder' => 'css/frontend']);
        $this->style( 'slick.min', [], [
            'folder' => 'plugins',
        ] );
        $this->script( 'slick.min', ['jquery'], [
            'folder' => 'plugins',
        ] );
        $this->r_script( 'product-video-popup__premium_only', ['jquery', 'wp-util', 'ccpeaw-sweetalert'] );
        $this->script( 'product-slider', ['jquery', 'ccpeaw-slick.min'] );
        $this->script( 'pv-script', ['jquery', 'wp-util'] );
        wp_localize_script( 'ccpeaw-pv-script', 'ccpeaw_pv', $this->getPVLocalizeData() );
        $this->script( 'quick-view', [
            'jquery',
            'wp-util',
            'ccpeaw-pv-script',
            'wc-add-to-cart-variation'
        ] );
        $this->script( 'saved-shared', ['jquery', 'wp-util'] );
        $this->script( 'frontend-swatches', ['jquery', 'wp-util'] );
        $this->script( 'wishlist-handler', ['jquery', 'wp-util'] );
        $this->menuCartEnqueue();
        $this->script( 'slick-viewed-products', ['jquery', 'wp-util', 'ccpeaw-slick.min'] );
        $this->script( 'currency-switcher', ['jquery', 'wp-util'] );
        $this->r_script( 'custom-quantity', ['jquery', 'wp-util'] );
    }

    /**
     * Get general localize data
     *
     * @param string $hook Current page hook
     * @param string $context Context (admin or frontend)
     * @return array
     */
    private function getLocalizeData( string $hook, string $context ) : array {
        $data = [
            'admin_url'      => admin_url(),
            'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
            'nonce'          => wp_create_nonce( 'ccpeaw' ),
            'siteUrl'        => site_url(),
            'pluginUrl'      => CCPEAW_URL,
            'isAdmin'        => is_admin(),
            'version'        => CCPEAW_VERSION,
            'pluginName'     => CCPEAW_NAME,
            'assetUrl'       => CCPEAW_ASSETS,
            'loader'         => CCPEAW_ASSETS . '/images/spinner.svg',
            'isPro'          => ccpeaw_fs()->is_paying_or_trial(),
            'liveEditorLink' => admin_url( 'customize.php' ) . '?autofocus',
        ];
        if ( class_exists( 'WooCommerce' ) ) {
            $data['cartPage'] = wc_get_cart_url();
            $data['checkoutPage'] = wc_get_checkout_url();
            $data['productSliderSettings'] = base64_encode( json_encode( $this->getSliderLocalizeData() ) );
            $data['recentViewSlider'] = $this->getRecentViewedProductsSettings();
            $data['quickViewSettings'] = $this->getQuickViewSettings();
        }
        return apply_filters(
            'eaw_localize_data',
            $data,
            $hook,
            $context
        );
    }

    /**
     * Get product variation localize data
     *
     * @return array
     */
    private function getPVLocalizeData() : array {
        $imageSettings = Helpers::getSetting( 'imageSettings' ) ?? [];
        return [
            'lazy_load' => ( !empty( $imageSettings['lazyLoad'] ) ? 'yes' : 'no' ),
        ];
    }

    /**
     * Get slider localize data
     *
     * @return array
     */
    private function getSliderLocalizeData() : array {
        if ( !is_product() ) {
            return [];
        }
        // Define mapping of Slick Slider settings to plugin setting keys and defaults
        $settingsMap = [
            'adaptiveHeight'           => [
                'key' => 'enableAutoHeight',
            ],
            'autoplay'                 => [
                'key' => 'enableSliderAutoPlay',
            ],
            'autoplaySpeed'            => [
                'key' => 'galleryAutoPlaySpeed',
            ],
            'arrows'                   => [
                'key' => 'gallerySliderArrows',
            ],
            'centerMode'               => [
                'key' => 'sliderCenterMode',
            ],
            'centerPadding'            => [
                'key' => 'sliderCenterPadding',
            ],
            'dots'                     => [
                'key' => 'gallerySliderDots',
            ],
            'draggable'                => [
                'key' => 'gallerySliderDraggable',
            ],
            'fade'                     => [
                'key' => 'enableSliderFadeEffect',
            ],
            'focusOnSelect'            => [
                'key' => 'sliderFocusOnSelect',
            ],
            'infinite'                 => [
                'key' => 'enableSliderLoop',
            ],
            'lazyLoad'                 => [
                'key' => 'galleryLazyLoad',
            ],
            'pauseOnHover'             => [
                'key' => 'galleryPauseOnHover',
            ],
            'pauseOnDotsHover'         => [
                'key' => 'galleryPauseOnDotsHover',
            ],
            'pauseOnFocus'             => [
                'key' => 'galleryPauseOnFocus',
            ],
            'slidesToShow'             => [
                'key' => 'gallerySlidesToShow',
            ],
            'slidesToScroll'           => [
                'key' => 'gallerySlidesToScroll',
            ],
            'speed'                    => [
                'key' => 'gallerySpeed',
            ],
            'swipe'                    => [
                'key' => 'gallerySwipe',
            ],
            'touchMove'                => [
                'key' => 'sliderTouchMove',
            ],
            'vertical'                 => [
                'key' => 'galleryVertical',
            ],
            'tabletSlidesToShow'       => [
                'key' => 'gTabletSlidesToShow',
            ],
            'tabletSlidesToScroll'     => [
                'key' => 'gTabletSlidesToScroll',
            ],
            'tabletSliderArrows'       => [
                'key' => 'gTabletSliderArrows',
            ],
            'tabletSliderDots'         => [
                'key' => 'gTabletSliderDots',
            ],
            'smallSlidesToShow'        => [
                'key' => 'gSmallSlidesToShow',
            ],
            'smallSlidesToScroll'      => [
                'key' => 'gSmallSlidesToScroll',
            ],
            'smallSliderArrows'        => [
                'key' => 'gSmallSliderArrows',
            ],
            'mallSliderDots'           => [
                'key' => 'gSmallSliderDots',
            ],
            'exSmallSlidesToShow'      => [
                'key' => 'gExSmallSlidesToShow',
            ],
            'exSmallSlidesToScroll'    => [
                'key' => 'gExSmallSlidesToScroll',
            ],
            'exSmallSliderArrows'      => [
                'key' => 'gExSmallSliderArrows',
            ],
            'exSmallSliderDots'        => [
                'key' => 'gExSmallSliderDots',
            ],
            'galleryThumb'             => [
                'key' => 'enableGalleryThumbnail',
            ],
            'enableGalleryThumbArrows' => [
                'key' => 'enableGalleryThumbnailArrows',
            ],
            'galleryLayout'            => [
                'key' => 'galleryLayoutType',
            ],
        ];
        $data = [];
        // Fetch and process each setting
        foreach ( $settingsMap as $slickKey => $config ) {
            $value = Helpers::getSetting( $config['key'] );
            if ( isset( $value ) ) {
                $data[$slickKey] = $value;
            }
        }
        $progress = Helpers::getSetting( 'selectPaginationType' );
        if ( isset( $progress ) ) {
            $data['paginationType'] = $progress;
        }
        return $data;
    }

    /**
     * Retrieve settings for the recently viewed products slider.
     *
     * @return array An associative array of slider settings.
     */
    public function getRecentViewedProductsSettings() : array {
        // Check if the current page is a product page
        if ( !is_product() ) {
            return [];
        }
        // Define mapping of Slick Slider settings to plugin setting keys
        $settingsMap = [
            'slidesToShow'  => [
                'key' => 'vpPdSlideToShow',
            ],
            'infinite'      => [
                'key' => 'vpSliderInfinity',
            ],
            'autoplay'      => [
                'key' => 'vpSliderAuto',
            ],
            'autoplaySpeed' => [
                'key' => 'vpSliderSpeed',
            ],
            'pauseOnHover'  => [
                'key' => 'vpSliderPause',
            ],
            'dots'          => [
                'key' => 'vpDots',
            ],
            'arrows'        => [
                'key' => 'vpArrows',
            ],
        ];
        $data = [];
        // Fetch and process each setting from the plugin's configuration
        foreach ( $settingsMap as $slickKey => $config ) {
            $value = Helpers::getSetting( $config['key'] );
            if ( isset( $value ) ) {
                $data[$slickKey] = $value;
            }
        }
        return $data;
    }

    /**
     * Enqueue customizer preview scripts
     *
     * @return void
     */
    public function customize_preview_init() : void {
        $this->script( 'customize-preview', ['jquery', 'flexslider'] );
        //TODO:
        wp_localize_script( 'ccpeaw-customize-preview', 'eawPreviewVars', [
            'ajax_url'  => admin_url( 'admin-ajax.php' ),
            'languages' => [],
            'nonce'     => wp_create_nonce( 'ccpeaw' ),
        ] );
    }

    /**
     * Enqueue customizer control scripts and styles
     *
     * @return void
     */
    public function customize_controls_enqueue_scripts() : void {
        $this->style( 'cart-icons.min', [], [
            'folder' => 'css/frontend',
        ] );
        $this->style( 'back-icons', [], [
            'folder' => 'css/frontend',
        ] );
        $this->style( 'cart-icons-atc.min', [], [
            'folder' => 'css/frontend',
        ] );
        $this->style( 'customize-preview', [], [
            'folder' => 'css/frontend',
        ] );
        $this->script( 'customize-settings', ['jquery'] );
        $design = Design::getInstance();
        wp_localize_script( 'ccpeaw-customize-settings', 'eawPreviewVars', [
            'ajax_url'           => admin_url( 'admin-ajax.php' ),
            'languages'          => $design->languages,
            'nonce'              => wp_create_nonce( 'ccpeaw' ),
            'select_product_url' => $design->select_product_url,
            'cart_url'           => esc_js( wc_get_page_permalink( 'cart' ) ),
            'checkout_url'       => esc_js( wc_get_page_permalink( 'checkout' ) ),
            'shop_url'           => esc_js( wc_get_page_permalink( 'shop' ) ),
        ] );
    }

    /**
     * Enqueue menu cart scripts and styles
     *
     * @return void
     */
    public function menuCartEnqueue() : void {
        $settings = AppSettings::getInstance();
        if ( !is_customize_preview() && !$settings->getParams( 'mcEnable' ) && empty( $settings->getParams( 'mcMenuDisplay' ) ) ) {
            return;
        }
        //TODO: Maybe need to remove this
        $this->style( 'cart-icons.min', [], [
            'folder' => 'css/frontend',
        ] );
        $this->style( 'menu-cart.min', [], [
            'folder' => 'css/frontend',
        ] );
        $this->r_script( 'menu-cart.min', ['jquery'], [
            'is_footer' => false,
        ] );
        if ( !is_customize_preview() ) {
            $menuCart = MenuCart::getInstance();
            wp_add_inline_style( 'ccpeaw-menu-cart.min', $menuCart->get_inline_css() );
        }
    }

    public function getQuickViewSettings() {
        $settingsMap = [
            'enableQuickView'        => [
                'key' => 'enableQuickView',
            ],
            'slideToShow'            => [
                'key' => 'quickViewSlidesToShow',
            ],
            'quickViewDisplayEffect' => [
                'key' => 'quickViewDisplayEffect',
            ],
            'quickViewLayoutType'    => [
                'key' => 'quickViewLayoutType',
            ],
        ];
        $data = [];
        // Fetch and process each setting from the plugin's configuration
        foreach ( $settingsMap as $slickKey => $config ) {
            $value = Helpers::getSetting( $config['key'] );
            if ( isset( $value ) ) {
                $data[$slickKey] = $value;
            }
        }
        return $data;
    }

}
