<?php

namespace CodeConfig\EAW\App;

use CodeConfig\EAW\AppSettings;
use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;
defined( 'ABSPATH' ) || exit;
class WishList {
    use Singleton;
    private $settings;

    public function doHooks() {
        $this->settings = AppSettings::getInstance();
        if ( wp_is_block_theme() ) {
            return;
        }
        $position = $this->settings->getParams( 'wishlistBtnPos' ) ?? '';
        // Add base hooks
        add_filter( 'post_class', [$this, 'addCustomClassToProductCard'], 10 );
        add_action( 'woocommerce_after_shop_loop_item', [$this, 'renderWishlistButton'], 9999 );
        // Position-specific cart button hooks
        switch ( $position ) {
            case 'beforeCartBtn':
                add_action( 'woocommerce_before_add_to_cart_button', [$this, 'renderWishlistButton'], 10 );
                break;
            case 'afterCartBtn':
                add_action( 'woocommerce_after_add_to_cart_button', [$this, 'renderWishlistButton'], 10 );
                break;
        }
        // Account page support
        add_action( 'init', [$this, 'register_wishlist_endpoint'] );
        add_action( 'woocommerce_account_wishlist_endpoint', [$this, 'display_wishlist_content'] );
        add_filter( 'woocommerce_account_menu_items', [$this, 'add_wishlist_to_my_account_menu'] );
        // Wishlist styles
        add_action( 'wp_head', [$this, 'print_wishlist_styles'] );
        $wishlishedListPosition = $this->settings->getParams( 'viewWishlistPosition' );
        // Floating wishlist on footer
        if ( in_array( $wishlishedListPosition, ['right', 'left', 'bottom'], true ) ) {
            add_action( 'wp_footer', [$this, 'render_wishlist_products'] );
        }
        // Header menu integration
        if ( $wishlishedListPosition === 'headerMenu' && Helpers::getSetting( 'viewWishlistMenu' ) ) {
            add_filter(
                'wp_nav_menu_items',
                [$this, 'add_wishlist_to_header_menu'],
                10,
                2
            );
        }
        // Wishlist button overlay on image
        $imagePositions = [
            'aboveProductImg',
            'belowProductImg',
            'belowProductImgOnHover',
            'overProductContainerHover'
        ];
        if ( in_array( $position, $imagePositions, true ) ) {
            add_action( 'eaw_after_single_product_slider', [$this, 'renderWishlistButton'] );
        }
    }

    public function addCustomClassToProductCard( $classes ) {
        $classes[] = 'eaw-product-card-wrapper-wishlist';
        $classes[] = strtolower( $this->settings->getParams( 'wishlistBtnPos' ) );
        return $classes;
    }

    public function print_wishlist_styles() {
        $btn = Helpers::getSetting( 'wishListBtn' );
        if ( !is_array( $btn ) ) {
            return;
        }
        $css_vars = [
            '--eaw-wishlist-bg-clr'        => $btn['bgColor'] ?? '',
            '--eaw-wishlist-bg-hv-clr'     => $btn['bgHoverColor'] ?? '',
            '--eaw-wishlist-txt-clr'       => $btn['textColor'] ?? '',
            '--eaw-wishlist-txt-hv-clr'    => $btn['textHoverColor'] ?? '',
            '--eaw-wishlist-border-radius' => $btn['borderRadius'] ?? '',
            '--eaw-wishlist-font-size'     => $btn['fontSize'] ?? '',
            '--eaw-wishlist-padding'       => $btn['padding'] ?? '',
        ];
        echo '<style>:root {';
        foreach ( $css_vars as $var => $value ) {
            echo esc_html( $var ) . ':' . esc_attr( $value ) . ';';
        }
        echo '}</style>';
    }

    private function get_wishlist_display_devices() : string {
        $devices = Helpers::getSetting( 'wishlistDisplayDevices' ) ?? [];
        $classes = array_map( function ( $device ) {
            return 'eaw-display-wishlist-' . sanitize_html_class( strtolower( $device ) );
        }, $devices );
        return implode( ' ', $classes );
    }

    public function renderWishlistButton() {
        wp_enqueue_script( 'eaw-wishlist-handler' );
        $showOnShop = Helpers::getSetting( 'showWishlistOnShop' ) === '1';
        $showOnSingle = Helpers::getSetting( 'showWishlistOnSingleProduct' ) === '1';
        // Conditional display: skip if not enabled for current page
        if ( !$showOnShop && is_shop() || !$showOnSingle && is_product() ) {
            return;
        }
        // Also skip if we're not on product or shop page
        if ( !is_shop() && !is_product() ) {
            return;
        }
        $settings = Helpers::getSetting( 'wishListBtn' );
        if ( !is_array( $settings ) ) {
            return;
        }
        $user_id = get_current_user_id();
        $product_id = get_the_ID();
        if ( !$product_id ) {
            return;
        }
        $wishlist = get_user_meta( $user_id, 'ccpeaw_wishlist', true );
        $wishlist = ( is_array( $wishlist ) ? $wishlist : [] );
        $is_in_wishlist = in_array( $product_id, $wishlist );
        $icon = ( $is_in_wishlist && !empty( $settings['icon'] ) ? 'wishlist-2' : $settings['icon'] ?? '' );
        $text = ( $is_in_wishlist && empty( $settings['icon'] ) ? 'wishlist-2' : $settings['btnTxt'] ?? '' );
        $style_name = $settings['name'] ?? '';
        $position = esc_attr( 'eaw-position-' . strtolower( $this->settings->getParams( 'wishlistViewBtnPosHor' ) ) );
        $device_cls = esc_attr( $this->get_wishlist_display_devices() );
        ?>

    <div class="eaw-wishlist-wrapper-product <?php 
        echo esc_attr( $position );
        ?>">
        <div
            title="<?php 
        echo esc_attr( $text );
        ?>"
            class="eaw-wishlist eaw-preview-btn-wishlist eaw-preview-btn eaw-wishlist-handler eaw-<?php 
        echo esc_attr( $style_name );
        ?> <?php 
        echo esc_attr( $device_cls );
        ?>"
            data-productid="<?php 
        echo esc_attr( $product_id );
        ?>"
            data-userid="<?php 
        echo esc_attr( $user_id );
        ?>"
        >
            <span class="eaw-icon-<?php 
        echo esc_attr( $icon );
        ?>">
                <?php 
        if ( !empty( $text ) ) {
            echo esc_html( $text );
        }
        ?>
            </span>
        </div>
    </div>
    <?php 
    }

    public function register_wishlist_endpoint() {
        add_rewrite_endpoint( 'wishlist', EP_ROOT | EP_PAGES );
        remove_action( 'woocommerce_before_shop_loop_item', 'astra_woo_shop_thumbnail_wrap_start', 6 );
        remove_action( 'woocommerce_after_shop_loop_item', 'astra_woo_shop_thumbnail_wrap_end', 8 );
    }

    public function display_wishlist_content() {
        if ( !is_user_logged_in() ) {
            echo '<p>' . esc_html__( 'Please log in to view your wishlist.', 'essential-addons-for-woocommerce' ) . '</p>';
            return;
        }
        wp_enqueue_script( 'eaw-wishlist-handler' );
        $wishlist = Helpers::getWishlist();
        if ( !function_exists( 'ccpeaw_get_template' ) ) {
            echo '<p>' . esc_html__( 'Error: Template function missing.', 'essential-addons-for-woocommerce' ) . '</p>';
            return;
        }
        ccpeaw_get_template( 'wishlist/wishlist', [
            'wishlist' => $wishlist,
        ], 'content' );
    }

    public function add_wishlist_to_my_account_menu( $menu_links ) {
        if ( !Helpers::getSetting( 'enableViewWishlist' ) ) {
            return $menu_links;
        }
        $wishlist_text = Helpers::getSetting( 'wishlistMenuText' ) ?? __( 'Wishlist', 'essential-addons-for-woocommerce' );
        $new_links = [];
        foreach ( $menu_links as $key => $label ) {
            if ( 'customer-logout' === $key ) {
                $new_links['wishlist'] = $wishlist_text;
            }
            $new_links[$key] = $label;
        }
        return $new_links;
    }

    public function render_wishlist_products() {
        if ( !is_user_logged_in() ) {
            return;
        }
        echo '<div class="eaw-wishlist-display eaw-display-wishlist-' . esc_attr( Helpers::getSetting( 'viewWishlistPosition' ) ) . ' ' . esc_attr( $this->get_wishlist_display_devices() ) . '">';
        esc_html( $this->render_view_wishlist_button() );
        echo '</div>';
    }

    public function render_view_wishlist_button() {
        $user_id = get_current_user_id();
        $wishlist = get_user_meta( $user_id, 'ccpeaw_wishlist', true );
        $wishlist = ( is_array( $wishlist ) ? $wishlist : [] );
        if ( empty( $wishlist ) ) {
            return '';
        }
        $settings = Helpers::getSetting( 'wishListBtn' ) ?? [];
        $text = ( !empty( $settings['btnTxt'] ) ? __( 'View wishlist', 'essential-addons-for-woocommerce' ) : '' );
        $icon = $settings['icon'] ?? '';
        $style_name = $settings['name'] ?? '';
        ob_start();
        ?>
        <div title="<?php 
        echo esc_attr( $text );
        ?>" class="eaw-wishlist eaw-preview-btn-wishlist eaw-preview-btn eaw-wishlist-get-handler eaw-<?php 
        echo esc_attr( $style_name );
        ?>">
            <span class="eaw-icon-<?php 
        echo esc_attr( $icon );
        ?>">
                <?php 
        echo esc_html( $text );
        ?>
            </span>
        </div>
<?php 
        return ob_get_clean();
    }

    public function add_wishlist_to_header_menu( $items, $args ) {
        $menu_slug = Helpers::getSetting( 'viewWishlistMenu' );
        if ( !empty( $menu_slug ) && isset( $args->menu->slug ) && $args->menu->slug === $menu_slug ) {
            $wishlist_url = esc_url( site_url( '/my-account/wishlist' ) );
            $label = esc_html__( 'Wishlist', 'essential-addons-for-woocommerce' );
            $items .= '<li class="menu-item wishlist-menu-item ' . esc_attr( $this->get_wishlist_display_devices() ) . '"><a href="' . $wishlist_url . '">' . $label . '</a></li>';
        }
        return $items;
    }

}
