<?php

namespace CodeConfig\EAW\App;

use CodeConfig\EAW\AppSettings;
use CodeConfig\EAW\Utils\Helpers;
use CodeConfig\EAW\Utils\Singleton;
defined( 'ABSPATH' ) || exit( 'No direct script access allowed' );
class QuickView {
    use Singleton;
    private $settings;

    public function doHooks() {
        $this->settings = AppSettings::getInstance();
        if ( wp_is_block_theme() ) {
            return;
        }
        add_filter( 'woocommerce_loop_add_to_cart_link', [$this, 'addToCartButton'], 10 );
        add_filter( 'post_class', [$this, 'addCustomClassToProductCard'], 10 );
        $this->registerProductContentHooks();
        $position = $this->settings->getParams( 'quickViewBtnPosition' ) ?? '';
        $positions = [
            'aboveProductImg',
            'belowProductImg',
            'belowProductImgOnHover',
            'overProductContainerHover',
            'center'
        ];
        if ( in_array( $position, $positions, true ) ) {
            add_action( 'eaw_after_single_product_slider', [$this, 'showQuickViewOnImage'] );
        }
    }

    public function showQuickViewOnImage() {
        printf( '<div class="eaw-quick-view-wrapper %s">%s</div>', esc_attr( $this->settings->getParams( 'quickViewBtnPositionHorizontal' ) ), esc_html( $this->renderQuickViewButton() ) );
    }

    private function registerProductContentHooks() {
        $elements = $this->settings->getParams( 'showElementOnQuickView' ) ?? [];
        $elements = ( is_array( $elements ) ? $elements : [] );
        $hooks = [
            'quickShowProductName'             => ['woocommerce_template_single_title', 5],
            'quickShowProductRating'           => ['woocommerce_template_single_rating', 10],
            'quickShowProductPrice'            => ['woocommerce_template_single_price', 15],
            'quickShowProductShortDescription' => ['woocommerce_template_single_excerpt', 20],
            'quickShowAddToCart'               => ['woocommerce_template_single_add_to_cart', 25],
            'quickShowProductMeta'             => ['woocommerce_template_single_meta', 30],
        ];
        foreach ( $hooks as $settingKey => [$callback, $priority] ) {
            if ( $settingKey === 'quickShowProductMeta' && get_post_type() === 'grouped' ) {
                continue;
            }
            if ( in_array( $settingKey, $elements, true ) ) {
                add_action( 'ccpeaw_product_content', $callback, $priority );
            }
        }
    }

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

    private function renderQuickViewButton() {
        $params = $this->settings->getParams( 'quickViewBtn' ) ?? [];
        $bgColor = esc_attr( $params['bgColor'] ?? '#000000' );
        $bgHoverColor = esc_attr( $params['bgHoverColor'] ?? '#000000' );
        $textColor = esc_attr( $params['textColor'] ?? '#ffffff' );
        $textHoverColor = esc_attr( $params['textHoverColor'] ?? '#ffffff' );
        $customIconUrl = esc_url( $params['customIconUrl'] ?? '' );
        $padding = esc_attr( $params['padding'] ?? '0px' );
        $borderRadius = esc_attr( $params['borderRadius'] ?? '0px' );
        $fontSize = esc_attr( $params['fontSize'] ?? '14px' );
        $custom_css = sprintf(
            ':root {
        --eaw-qv-bg-clr: %1$s;
        --eaw-qv-bg-hv-clr: %2$s;
        --eaw-qv-txt-clr: %3$s;
        --eaw-qv-txt-hv-clr: %4$s;
        --eaw-qv-icon-url: url(%5$s);
        --eaw-qv-padding: %6$s;
        --eaw-qv-border-radius: %7$s;
        --eaw-qv-font-size: %8$s;
    }',
            esc_attr( $bgColor ),
            esc_attr( $bgHoverColor ),
            esc_attr( $textColor ),
            esc_attr( $textHoverColor ),
            esc_url( $customIconUrl ),
            esc_attr( $padding ),
            esc_attr( $borderRadius ),
            esc_attr( $fontSize )
        );
        wp_add_inline_style( 'eaw-frontend-style', $custom_css );
        $iconPosition = $params['iconPosition'] ?? '';
        $iconClass = esc_attr( $params['icon'] ?? '' );
        $btnTxt = esc_html( $params['btnTxt'] ?? '' );
        $hasCustomIcon = !empty( $params['customIconUrl'] );
        $content = '';
        if ( $iconPosition === 'left' && !$hasCustomIcon ) {
            $content .= '<span class="eaw-icon eaw-icon-' . $iconClass . '"></span>';
        } elseif ( $hasCustomIcon ) {
            $content .= '<span class="eaw-icon custom-icon"></span>';
        } elseif ( !$iconPosition && !$hasCustomIcon ) {
            $content .= '<span class="eaw-icon eaw-icon-' . $iconClass . '"></span>';
        }
        if ( $btnTxt ) {
            $content .= '<span class="eaw-btn-text">' . $btnTxt . '</span>';
        }
        if ( $iconPosition === 'right' && !$hasCustomIcon ) {
            $content .= '<span class="eaw-icon eaw-icon-' . $iconClass . '"></span>';
        }
        $devices = $this->settings->getParams( 'quickViewDisplayDevices' ) ?? [];
        $deviceClasses = ( is_array( $devices ) ? array_map( fn( $d ) => 'eaw-display-' . strtolower( $d ), $devices ) : [] );
        $positionClass = ( in_array( $this->settings->getParams( 'quickViewBtnPosition' ), ['belowProductImgOnHover', 'belowProductImg', 'aboveProductImg'] ) ? '' : $this->settings->getParams( 'quickViewBtnPosition' ) );
        return sprintf(
            '<button class="eaw-preview-btn eaw-quick-view eaw-%s %s %s" data-wc-product-id="%d">%s</button>',
            esc_attr( $params['name'] ?? 'default' ),
            esc_attr( implode( ' ', $deviceClasses ) ),
            esc_attr( $positionClass ),
            esc_attr( get_the_ID() ),
            wp_kses_post( $content )
        );
    }

    public function addToCartButton( $html ) {
        $product = wc_get_product();
        if ( $this->settings->getParams( 'enableQuickView' ) && $product ) {
            $buttonHtml = $this->renderQuickViewButton();
            $position = $this->settings->getParams( 'quickViewBtnPosition' );
            switch ( $position ) {
                case 'belowCartBtn':
                case 'afterCartBtn':
                    return '<div class="eaw-quick-view-wrapper">' . $html . $buttonHtml . '</div>';
                case 'aboveCartBtn':
                case 'beforeCartBtn':
                    return '<div class="eaw-quick-view-wrapper">' . $buttonHtml . $html . '</div>';
            }
        }
        return $html;
    }

    public static function getPopUpContent() {
        check_ajax_referer( 'ccpeaw', 'eaw_nonce' );
        $productId = ( isset( $_POST['productId'] ) ? intval( wp_unslash( $_POST['productId'] ) ) : 0 );
        if ( !$productId ) {
            wp_send_json_error( [
                'success' => false,
                'message' => __( 'Product not found', 'essential-addons-for-woocommerce' ),
            ], 404 );
        }
        $product = wc_get_product( $productId );
        if ( !$product ) {
            wp_send_json_error( [
                'success' => false,
                'message' => __( 'Product not found', 'essential-addons-for-woocommerce' ),
            ], 404 );
        }
        $settingsKeys = ['showElementOnQuickView'];
        $displaySettings = array_reduce( $settingsKeys, function ( $carry, $key ) {
            $carry[$key] = Helpers::getSetting( $key );
            return $carry;
        }, [] );
        $galleryImages = array_map( 'wp_get_attachment_url', $product->get_gallery_image_ids() );
        if ( $product->is_type( 'variable' ) ) {
            foreach ( $product->get_children() as $variation_id ) {
                $variation = wc_get_product( $variation_id );
                if ( $variation && $variation->get_image_id() ) {
                    $galleryImages[] = wp_get_attachment_url( $variation->get_image_id() );
                }
            }
        }
        $featuredImage = ( wp_get_attachment_url( $product->get_image_id() ) ?: wc_placeholder_img_src() );
        $galleryImages = array_values( array_unique( array_filter( array_merge( [$featuredImage], $galleryImages ) ) ) );
        ob_start();
        ccpeaw_get_template( '/quick-view/product', [
            'productData'              => [
                'id'            => $product->get_id(),
                'productType'   => $product->get_type(),
                'featuredImage' => $featuredImage,
                'galleryImages' => $galleryImages,
            ],
            'DisplayQuickViewSettings' => $displaySettings,
        ], 'quick-view' );
        $html = ob_get_clean();
        wp_send_json_success( [
            'success' => true,
            'data'    => $html,
            'message' => __( 'Settings fetched successfully', 'essential-addons-for-woocommerce' ),
        ] );
    }

}
