<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class QVIPP_Frontend {

	public $qvipp_plugin_dir_url;
	public $qvipp_options;
	public $qvipp_styles;

	public function __construct( $qvipp_plugin_dir_url ) {
		$this->qvipp_plugin_dir_url = esc_url( $qvipp_plugin_dir_url );
		$this->qvipp_options        = get_option( 'qvipp_options', array() );
		$this->qvipp_styles         = get_option( 'qvipp_styles', array() );

		$button_pos       = isset( $this->qvipp_options['qvipp_quick_view_btn_position'] ) ? sanitize_text_field( $this->qvipp_options['qvipp_quick_view_btn_position'] ) : '';
		$this->op_val     = get_option( 'qvipp_display_product_options', array() );
		$view_product_detail = ! empty( $this->qvipp_options['qvipp_view_product_detail'] );

		add_action( 'wp_enqueue_scripts', array( $this, 'qvipp_load_assets' ) );

		// Position hooks
		if ( 'after_image' === $button_pos ) {
			add_action( 'woocommerce_shop_loop_item_title', array( $this, 'qvipp_add_button' ), 1 );
		} elseif ( 'on_hover_image' === $button_pos ) {
			add_action( 'woocommerce_before_shop_loop_item_title', array( $this, 'qvipp_add_button' ), 9 );
		} elseif ( 'after_title' === $button_pos ) {
			add_action( 'woocommerce_shop_loop_item_title', array( $this, 'qvipp_add_button' ), 11 );
		} elseif ( 'before_add_to_cart' === $button_pos ) {
			add_action( 'woocommerce_after_shop_loop_item', array( $this, 'qvipp_add_button' ), 1 );
		}

		add_action( 'wp_footer', array( $this, 'qvipp_remodel_modal' ) );
		add_action( 'wp_ajax_qvipp_get_product', array( $this, 'qvipp_get_product' ) );
		add_action( 'wp_ajax_nopriv_qvipp_get_product', array( $this, 'qvipp_get_product' ) );

		add_action( 'qvipp_show_product_sale_flash', 'woocommerce_show_product_sale_flash' );

		// Show product images
		if ( is_array( $this->op_val ) && in_array( 'product_image', $this->op_val, true ) ) {
			add_action( 'qvipp_show_product_images', array( $this, 'qvipp_woocommerce_show_product_images' ) );
		}

		// Product data sections
		if ( in_array( 'product_title', (array) $this->op_val, true ) ) {
		    add_action( 'qvipp_product_data', 'woocommerce_template_single_title' );
		}
		if ( in_array( 'product_price', (array) $this->op_val, true ) ) {
			add_action( 'qvipp_product_data', 'woocommerce_template_single_price' );
		}
		if ( in_array( 'product_excerpt', (array) $this->op_val, true ) ) {
			add_action( 'qvipp_product_data', 'woocommerce_template_single_excerpt' );
		}
		if ( in_array( 'product_add_to_cart_btn', (array) $this->op_val, true ) ) {
			add_action( 'qvipp_product_data', 'woocommerce_template_single_add_to_cart' );
		}
		if ( in_array( 'product_meta', (array) $this->op_val, true ) ) {
		    add_action( 'qvipp_product_data', 'woocommerce_template_single_meta' );
		}
		if ( in_array( 'product_rating', (array) $this->op_val, true ) ) {
		    add_action( 'qvipp_product_data', 'woocommerce_template_single_rating' );
		}
		if ( $view_product_detail ) {
			add_action( 'qvipp_product_data', array( $this, 'qvipp_detail_button' ) );
		}
	}

	public function qvipp_detail_button() {
	    // fallback if option is missing or blank
	    $text_option = isset( $this->qvipp_options['qvipp_view_product_detail_text'] ) ? $this->qvipp_options['qvipp_view_product_detail_text'] : '';
	    $text = ! empty( $text_option ) 
	        ? sanitize_text_field( $text_option ) 
	        : esc_html__( 'View Product', 'quickview-instant-product-preview' );

	    $link = get_permalink();

	    printf(
	        '<a class="button qvipp_detail_button" style="padding:10px;margin-top:10px;" href="%s">%s</a>',
	        esc_url( $link ),
	        esc_html( $text )
	    );
	}

	public function qvipp_woocommerce_show_product_images() {
		global $post, $product;
		?>
		<div class="qvipp_images">
		<?php
		if ( has_post_thumbnail() ) {
			$attachment_count = count( $product->get_gallery_image_ids() );
			$gallery          = $attachment_count > 0 ? '[product-gallery]' : '';
			$props            = wc_get_product_attachment_props( get_post_thumbnail_id(), $post );
			$image            = get_the_post_thumbnail(
				$post->ID,
				apply_filters( 'single_product_large_thumbnail_size', 'shop_single' ),
				array(
					'title' => esc_attr( $props['title'] ),
					'alt'   => esc_attr( $props['alt'] ),
				)
			);
			echo apply_filters(
			    'woocommerce_single_product_image_html',
			    sprintf(
			        '<a href="%s" itemprop="image" class="qvipp_woocommerce-main-image qvipp_zoom" title="%s" data-rel="prettyPhoto%s">%s</a>',
			        esc_url( $props['url'] ),
			        esc_attr( $props['caption'] ),
			        esc_attr( $gallery ),  // escape gallery ID or string
			        wp_kses_post( $image ) // allow safe HTML for the image tag
			    ),
			    get_the_ID()
			);

		} else { ?>
			<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?>" alt="<?php echo esc_attr__( 'Placeholder', 'quickview-instant-product-preview' ); ?>" />
			<?php 
		}

		$attachment_ids = $product->get_gallery_image_ids();
		if ( $attachment_ids ) {
			$loop    = 0;
			$columns = apply_filters( 'woocommerce_product_thumbnails_columns', 3 );
			?>
			<div class="qvipp_thumbnails columns-<?php echo absint( $columns );?>">
				<?php 
				foreach ( $attachment_ids as $attachment_id ) {
					$image_link = wp_get_attachment_url( $attachment_id );
					if ( ! $image_link ) {
						continue;
					}
					$image_title   = esc_attr( get_the_title( $attachment_id ) );
					$image_caption = esc_attr( get_post_field( 'post_excerpt', $attachment_id ) );
					$image         = wp_get_attachment_image( $attachment_id, apply_filters( 'single_product_small_thumbnail_size', 'shop_thumbnail' ), false, array(
						'title' => $image_title,
						'alt'   => $image_title,
					) );
					echo sprintf( '<a href="%s" class="qvipp_thumbnail" title="%s">%s</a>',
						esc_url( $image_link ),
						$image_caption,
						$image
					);
					$loop++;
				}
				?>
			</div><?php } ?>
		</div> <?php 
	}

	public function qvipp_load_assets() {

	    // CSS
	    wp_enqueue_style(
	        'qvipp_remodal_default_css',
	        $this->qvipp_plugin_dir_url . 'assets/css/style.css',
	        [],
	        QVIPP_VERSION
	    );

	    wp_enqueue_style(
	        'qvipp_prettyphoto.min.css',
	        $this->qvipp_plugin_dir_url . '/assets/css/prettyPhoto.min.css',
	        array(),
	        QVIPP_VERSION
	    );

	    // PrettyPhoto init script (your own init code)
	    wp_register_script(
	        'qvipp-prettyphoto-init',
	        $this->qvipp_plugin_dir_url . 'assets/js/prettyPhoto.init.js',
	        [ 'jquery' ],
	        QVIPP_VERSION,
	        true
	    );

	    wp_enqueue_script(
	        'qvipp_prettyphoto.min.js',
	        $this->qvipp_plugin_dir_url . '/assets/js/jquery.prettyPhoto.min.js',
	        array('jquery'),
	        QVIPP_VERSION,
	        true
	    );

	    // Frontend JS
	    wp_register_script(
	        'qvipp_frontend_js',
	        $this->qvipp_plugin_dir_url . 'assets/js/frontend.js',
	        ['jquery'],
	        QVIPP_VERSION,
	        true
	    );

	    wp_localize_script(
	        'qvipp_frontend_js',
	        'qvipp_frontend_obj',
	        [
	            'qvipp_nonce'           => wp_create_nonce( 'qvipp_nonce' ),
	            'ajaxurl'               => admin_url( 'admin-ajax.php' ),
	            'qvipp_plugin_dir_url'  => $this->qvipp_plugin_dir_url,
	        ]
	    );

	    if ( ! wp_script_is( 'jquery', 'enqueued' ) ) {
	        wp_enqueue_script( 'jquery' );
	    }
	    wp_enqueue_script( 'qvipp_frontend_js' );

	    // Remodal JS
	    wp_register_script(
	        'qvipp_remodal_js',
	        $this->qvipp_plugin_dir_url . 'assets/js/remodal.js',
	        ['jquery'],
	        QVIPP_VERSION,
	        true
	    );
	    wp_enqueue_script( 'qvipp_remodal_js' );

	    // WooCommerce scripts
	    wp_enqueue_script( 'wc-add-to-cart-variation' );
	    wp_enqueue_script( 'thickbox' );

	    // Inline CSS based on saved styles
	    $styles = wp_parse_args( $this->qvipp_styles, [
	        'qvipp_close_btn'                 => '#000',
	        'qvipp_close_btn_bg'              => '#fff',
	        'qvipp_modal_bg'                  => '#fff',
	        'qvipp_navigation_txt'            => '#000',
	        'qvipp_navigation_bg'             => '#ccc',
	        'qvipp_product_detail_btn_color'  => '#21759b',
	        'qvipp_quick_view_btn_lable_color'=> '#21759b',
	    ] );

	    $close_btn = isset($styles['qvipp_close_btn']) ? sanitize_hex_color( $styles['qvipp_close_btn'] ) : '#000';
		$close_btn_bg = isset($styles['qvipp_close_btn_bg']) ? sanitize_hex_color( $styles['qvipp_close_btn_bg'] ) : '#fff';
		$modal_bg = isset($styles['qvipp_modal_bg']) ? sanitize_hex_color( $styles['qvipp_modal_bg'] ) : '#fff';
		$nav_txt = isset($styles['qvipp_navigation_txt']) ? sanitize_hex_color( $styles['qvipp_navigation_txt'] ) : '#000';
		$nav_bg = isset($styles['qvipp_navigation_bg']) ? sanitize_hex_color( $styles['qvipp_navigation_bg'] ) : '#eee';
		$quick_view_btn = isset($styles['qvipp_quick_view_btn_lable_color']) ? sanitize_hex_color( $styles['qvipp_quick_view_btn_lable_color'] ) : '#000';
		$detail_btn = isset($styles['qvipp_product_detail_btn_color']) ? sanitize_hex_color( $styles['qvipp_product_detail_btn_color'] ) : '#000';

	    $custom_css = "
		    .remodal .qvipp_remodal-close{color:{$close_btn};}
		    .remodal .qvipp_remodal-close:hover{background-color:{$close_btn_bg};}
		    .woocommerce .remodal{background-color:{$modal_bg};}
		    .qvipp_prev h4,.qvipp_next h4{color:{$nav_txt};}
		    .qvipp_prev,.qvipp_next{background:{$nav_bg};}
		    .woocommerce a.qvipp_quick_view{background-color:{$close_btn};}
		    a.button.qvipp_detail_button{background-color:{$detail_btn};}
		    a.qvipp_quick_view.button{background-color:{$quick_view_btn};}
		";

		wp_add_inline_style( 'qvipp_remodal_default_css', $custom_css );

	}

	public function qvipp_remodel_modal() {
		?>
		<div class="remodal" data-remodal-id="modal" role="dialog" aria-labelledby="modalTitle" aria-describedby="modalDesc">
			<button data-remodal-action="close" class="qvipp_remodal-close" aria-label="<?php esc_attr_e( 'Close', 'quickview-instant-product-preview' ); ?>"></button>
			<div id="qvipp_content"></div>
		</div>
		<?php
	}

	public function qvipp_add_button() {
		global $post;
		$button_label = isset( $this->qvipp_options['qvipp_button_lable'] ) ? sanitize_text_field( $this->qvipp_options['qvipp_button_lable'] ) : esc_html__( 'Quick View', 'quickview-instant-product-preview' );
		$button_pos   = isset( $this->qvipp_options['qvipp_quick_view_btn_position'] ) ? sanitize_text_field( $this->qvipp_options['qvipp_quick_view_btn_position'] ) : '';

		if ( 'on_hover_image' === $button_pos ) { ?>
			<div class="qvipp_btn" style="position:absolute;top:30%;width:100%;text-align:center;">
			<?php }
		printf(
			'<a data-product-id="%d" class="qvipp_quick_view button" style="padding:6px 10px 4px 10px;"><span>%s</span></a>',
			absint( $post->ID ),
			esc_html( $button_label )
		);
		if ( 'on_hover_image' === $button_pos ) { ?></div> 
			<?php
		}
	}

	public function qvipp_get_product() {
		global $woocommerce;
		$nonce = isset($_POST['qvipp_nonce']) ? sanitize_text_field( $_POST['qvipp_nonce'] ) : '';

	    if ( ! wp_verify_nonce( $nonce, 'qvipp_nonce' ) ) {
	        wp_send_json_error( [ 'message' => 'Invalid nonce' ], 403 );
	    }

		$product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
		if ( ! $product_id ) {
			wp_die();
		}

		wp( 'p=' . $product_id . '&post_type=product' );

		ob_start();
		
		while ( have_posts() ) {
			the_post();
			?>
			<script>
				var url = <?php echo wp_json_encode( $this->qvipp_plugin_dir_url . 'assets/js/prettyPhoto.init.js' ); ?>;
				jQuery.getScript(url);
				var wc_add_to_cart_variation_params = {"ajax_url":"\/wp-admin\/admin-ajax.php"};
				jQuery.getScript("<?php echo esc_url( $woocommerce->plugin_url() ); ?>/assets/js/frontend/add-to-cart-variation.min.js");
			</script>
			<div class="qvipp_product">
				<div id="product-<?php the_ID(); ?>" <?php post_class('product'); ?>>
					<?php do_action('qvipp_show_product_sale_flash'); ?>
					<?php do_action('qvipp_show_product_images'); ?>
					<div class="qvipp_summary entry-summary qvipp_scrollable">
						<div class="summary-content">
							<?php do_action( 'qvipp_product_data' ); ?>
						</div>
					</div>
					<div class="qvipp_scrollbar_bg"></div>
				</div>
			</div>
			<?php
		}
		echo ob_get_clean();
		exit;
	}
}
