<?php
/**
 * Wishlist Feature for Product Display.
 *
 * @package Product_Display.
 */

// Exit if accessed directly.
if ( ! defined('ABSPATH') ) {
	exit;
}

/**
 * Class PRODDISP_Compare.
 *
 * This class handles the compare functionality for product display.
 */
class PRODDISP_Wishlist {
	/**
	 * The single instance of the class.
	 */
	protected static $_instance = null;

	/**
	 * Main Instance.
	 */
	public static function get_instance() {
		if ( is_null(self::$_instance) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * Constructor.
	 */
	public function __construct() {
		// New AJAX actions
		add_action('wp_ajax_proddisp_add_to_wishlist', array( $this, 'add_to_wishlist' ));
		add_action('wp_ajax_nopriv_proddisp_add_to_wishlist', array( $this, 'add_to_wishlist' ));
		add_action('wp_ajax_proddisp_remove_from_wishlist', array( $this, 'remove_from_wishlist' ));
		add_action('wp_ajax_nopriv_proddisp_remove_from_wishlist', array( $this, 'remove_from_wishlist' ));
		add_action('wp_ajax_proddisp_toggle_wishlist', array( $this, 'toggle_wishlist' ));
		add_action('wp_ajax_nopriv_proddisp_toggle_wishlist', array( $this, 'toggle_wishlist' ));
		add_action('wp_ajax_proddisp_get_wishlist', array( $this, 'get_wishlist' ));
		add_action('wp_ajax_nopriv_proddisp_get_wishlist', array( $this, 'get_wishlist' ));
		add_action('wp_ajax_proddisp_add_to_cart', array( $this, 'ajax_add_to_cart' ));
		add_action('wp_ajax_nopriv_proddisp_add_to_cart', array( $this, 'ajax_add_to_cart' ));

		// Register shortcode for wishlist page.
		add_shortcode('product_wishlist', array( $this, 'wishlist_shortcode' ));
		add_action('wp_footer', array( $this, 'render_wishlist_modal' ));
		add_action('wp_enqueue_scripts', array( $this, 'enqueue_scripts' ));

		// Initialize WooCommerce hooks immediately since we're now called at wp_loaded
		$this->init_woocommerce_hooks();
	}

	/**
	 * Initialize WooCommerce hooks for wishlist buttons.
	 */
	public function init_woocommerce_hooks() {
		if ( ! class_exists('WooCommerce') ) {
			return;
		}

		// Check if wishlist is enabled
		if ( ! PRODDISP_Wishlist_Settings::is_wishlist_enabled() ) {
			return;
		}

		$settings = PRODDISP_Wishlist_Settings::get_frontend_settings();

		// Add wishlist button to single product page
		if ( $settings['show_on_product_page'] ) {
			add_action('woocommerce_single_product_summary', array( $this, 'display_wishlist_button_single' ), 35);
		}

		// Add wishlist button to shop/archive pages
		if ( $settings['show_on_shop_page'] ) {
			add_action('woocommerce_after_shop_loop_item', array( $this, 'display_wishlist_button_loop' ), 15);
		}
	}

	/**
	 * Enqueue scripts and styles for wishlist.
	 */
	public function enqueue_scripts() {
		// Check if wishlist is enabled
		if ( ! PRODDISP_Wishlist_Settings::is_wishlist_enabled() ) {
			return;
		}

		// Load on frontend pages (not admin)
		if ( is_admin() ) {
			return;
		}

		// Always load base wishlist assets when wishlist is enabled
		// This ensures floating button and modal work on all pages

		// Enqueue local FontAwesome for icons (consistent with main plugin)
		wp_enqueue_style('wcps-font-awesome');

		wp_enqueue_style(
			'proddisp-wishlist-style',
			PRODDISP_PLUGIN_URL . 'assets/build/css/wcps-wishlist-style.min.css',
			array( 'wcps-font-awesome' ),
			'1.0.0'
		);

		wp_enqueue_script(
			'proddisp-wishlist',
			PRODDISP_PLUGIN_URL . 'assets/build/js/wcps-wishlist.min.js',
			array( 'jquery' ),
			'1.0.0',
			true
		);

		// Enqueue additional assets if floating button is enabled
		if ( PRODDISP_Wishlist_Settings::is_floating_button_enabled() ) {
			// Enqueue sidebar CSS for floating button
			wp_enqueue_style(
				'proddisp-wishlist-sidebar-style',
				PRODDISP_PLUGIN_URL . 'assets/build/css/wcps-wishlist-sidebar-style.min.css',
				array( 'proddisp-wishlist-style' ),
				'1.0.0'
			);

			// Enqueue sidebar JavaScript for floating button functionality
			wp_enqueue_script(
				'proddisp-wishlist-sidebar',
				PRODDISP_PLUGIN_URL . 'assets/build/js/wcps-wishlist-sidebar.min.js',
				array( 'jquery', 'proddisp-wishlist' ),
				'1.0.0',
				true
			);

			// Localize script with settings for floating button
			$wishlist_settings = PRODDISP_Wishlist_Settings::get_frontend_settings();
			wp_localize_script('proddisp-wishlist-sidebar', 'proddisp_wishlist_settings', $wishlist_settings);
		}

		wp_localize_script('proddisp-wishlist', 'proddisp_params', array(
			'ajax_url' => admin_url('admin-ajax.php'),
			'nonce' => wp_create_nonce('wcps-nonce'),
			'currency_symbol' => get_woocommerce_currency_symbol(),
			'wishlist_page_url' => $this->get_wishlist_page_url(),
		));

		// Localize wishlist settings for frontend use
		$wishlist_settings = PRODDISP_Wishlist_Settings::get_frontend_settings();
		wp_localize_script('proddisp-wishlist', 'proddisp_wishlist_settings', $wishlist_settings);
	}

	/**
	 * Get wishlist page URL.
	 *
	 * @return string Wishlist page URL.
	 */
	private function get_wishlist_page_url() {
		$settings = PRODDISP_Wishlist_Settings::get_frontend_settings();

		if ( ! empty( $settings['wishlist_page_id'] ) ) {
			$page_url = get_permalink( $settings['wishlist_page_id'] );
			if ( $page_url ) {
				return $page_url;
			}
		}

		// Fallback to a default wishlist page or current page
		return home_url( '/wishlist/' );
	}

	/**
	 * Display wishlist button on single product page.
	 */
	public function display_wishlist_button_single() {
		global $product;

		if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
			return;
		}

		echo '<div class="proddisp-wishlist-single-wrapper">';
		echo wp_kses_post( $this->render_wishlist_button_wc( $product ) );
		echo '</div>';
	}

	/**
	 * Display wishlist button on shop/archive pages.
	 */
	public function display_wishlist_button_loop() {
		global $product;

		if ( ! $product || ! is_a( $product, 'WC_Product' ) ) {
			return;
		}

		echo '<div class="proddisp-wishlist-loop-wrapper">';
		echo wp_kses_post( $this->render_wishlist_button_wc( $product ) );
		echo '</div>';
	}

	/**
	 * Render the wishlist button for WooCommerce products.
	 *
	 * @param WC_Product $product WooCommerce product object.
	 * @return string HTML for the wishlist button.
	 */
	public function render_wishlist_button_wc( $product ) {
		$product_id = $product->get_id();
		$in_wishlist = $this->is_in_wishlist($product_id);
		$settings = PRODDISP_Wishlist_Settings::get_frontend_settings();

		$button_class = $in_wishlist ? 'proddisp-wishlist-button in-wishlist' : 'proddisp-wishlist-button';
		$button_class .= ' ' . esc_attr($settings['wishlist_button_shape']);

		$button_text = $in_wishlist ? $settings['wishlist_button_text_remove'] : $settings['wishlist_button_text'];
		$button_title = $in_wishlist ? $settings['wishlist_button_text_remove'] : $settings['wishlist_button_text'];

		// Build inline styles.
		$styles = array();
		if ( $in_wishlist ) {
			$styles[] = 'background-color: ' . esc_attr($settings['wishlist_button_color']);
			$styles[] = 'color: ' . esc_attr($settings['wishlist_button_text_color']);
			$styles[] = 'border-color: ' . esc_attr($settings['wishlist_button_color']);
		} else {
			$styles[] = 'background-color: transparent';
			$styles[] = 'color: ' . esc_attr($settings['wishlist_button_color']);
			$styles[] = 'border-color: ' . esc_attr($settings['wishlist_button_border_color']);
		}
		$style_attr = 'style="' . esc_attr( implode('; ', $styles) ) . '"';

		$output = '<a href="#" class="' . esc_attr($button_class) . '" data-product-id="' . esc_attr($product_id) . '" title="' . esc_attr($button_title) . '" ' . $style_attr . '>';

		// Add icon if enabled.
		if ( $settings['wishlist_button_style'] === 'icon' || $settings['wishlist_button_style'] === 'both' ) {
			$heart_icon = $in_wishlist ? '♥' : '♡';
			$output .= '<span class="proddisp-icon-heart">' . esc_html( $heart_icon ) . '</span>';
		}

		// Add text if enabled
		if ( $settings['wishlist_button_style'] === 'text' || $settings['wishlist_button_style'] === 'both' ) {
			$output .= '<span class="proddisp-button-text">' . esc_html($button_text) . '</span>';
		}

		$output .= '</a>';

		return $output;
	}

	/**
	 * Render the wishlist button for a product.
	 *
	 * @param Product_Display $product Product object.
	 * @return string HTML for the wishlist button.
	 */
	public function render_wishlist_button( $product ) {
		$product_id = $product->get_id();
		$in_wishlist = $this->is_in_wishlist($product_id);

		$button_class = $in_wishlist ? 'wcps-wishlist-button in-wishlist' : 'wcps-wishlist-button';
		$button_text = $in_wishlist ? __('Remove from Wishlist', 'product-display') : __('Add to Wishlist', 'product-display');
		$button_title = $in_wishlist ? __('Remove from Wishlist', 'product-display') : __('Add to Wishlist', 'product-display');

		$output = '<a href="#" class="' . esc_attr($button_class) . '" data-product-id="' . esc_attr($product_id) . '" title="' . esc_attr($button_title) . '">';
		$output .= '<span class="wcps-icon wcps-icon-heart"></span>';
		$output .= '<span class="wcps-button-text">' . esc_html($button_text) . '</span>';
		$output .= '</a>';

		return $output;
	}

	/**
	 * Check if a product is in wishlist.
	 *
	 * @param int $product_id Product ID.
	 * @return bool True if in wishlist.
	 */
	public function is_in_wishlist( $product_id ) {
		$wishlist_items = $this->get_wishlist_items();
		return in_array($product_id, $wishlist_items);
	}

	/**
	 * Get wishlist items from cookie or user meta.
	 *
	 * @return array Array of product IDs.
	 */
	public function get_wishlist_items() {
		$wishlist_items = array();

		// For logged in users, store in user meta.
		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();
			$wishlist_items = get_user_meta($user_id, 'proddisp_wishlist_items', true);

			if ( ! is_array($wishlist_items) ) {
				$wishlist_items = array();
			}
		}
		// For guests, use cookies.
		else {
			if ( isset($_COOKIE['proddisp_wishlist_items']) ) {
				$wishlist_items = explode(',', sanitize_text_field(wp_unslash($_COOKIE['proddisp_wishlist_items'])));
				$wishlist_items = array_map('absint', $wishlist_items);
				$wishlist_items = array_filter($wishlist_items);
			}
		}

		return $wishlist_items;
	}

	/**
	 * Toggle product in wishlist via AJAX.
	 */
	public function toggle_wishlist() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;

		if ( ! $product_id ) {
			wp_send_json_error(array( 'message' => __('Invalid product ID', 'product-display') ));
		}

		$wishlist_items = $this->get_wishlist_items();
		$in_wishlist = in_array($product_id, $wishlist_items);

		// If product is in wishlist, remove it.
		if ( $in_wishlist ) {
			$wishlist_items = array_diff($wishlist_items, array( $product_id ));
			$message = __('Product removed from wishlist', 'product-display');
			if ( class_exists('PRODDISP_Wishlist_Analytics') ) {
				PRODDISP_Wishlist_Analytics::record_event( $product_id, 'remove' );
			}
		}
		// If product is not in wishlist, add it.
		else {
			$wishlist_items[] = $product_id;
			$message = __('Product added to wishlist', 'product-display');
			if ( class_exists('PRODDISP_Wishlist_Analytics') ) {
				PRODDISP_Wishlist_Analytics::record_event( $product_id, 'add' );
			}
		}

		// Save wishlist items.
		$this->save_wishlist_items($wishlist_items);

		wp_send_json_success(array(
			'message' => $message,
			'count' => count($wishlist_items),
			'in_wishlist' => ! $in_wishlist, // Toggle the state.
		));
	}

	/**
	 * Add product to wishlist via AJAX.
	 */
	public function add_to_wishlist() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;

		if ( ! $product_id ) {
			wp_send_json_error(array( 'message' => __('Invalid product ID', 'product-display') ));
		}

		$wishlist_items = $this->get_wishlist_items();

		if ( ! in_array($product_id, $wishlist_items) ) {
			$wishlist_items[] = $product_id;
			$this->save_wishlist_items($wishlist_items);
			if ( class_exists('PRODDISP_Wishlist_Analytics') ) {
				PRODDISP_Wishlist_Analytics::record_event( $product_id, 'add' );
			}
		}

		wp_send_json_success(array(
			'message' => __('Product added to wishlist', 'product-display'),
			'count' => count($wishlist_items),
		));
	}

	/**
	 * Remove product from wishlist via AJAX.
	 */
	public function remove_from_wishlist() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;

		if ( ! $product_id ) {
			wp_send_json_error(array( 'message' => __('Invalid product ID', 'product-display') ));
		}

		$wishlist_items = $this->get_wishlist_items();

		if ( in_array($product_id, $wishlist_items) ) {
			$wishlist_items = array_diff($wishlist_items, array( $product_id ));
			$this->save_wishlist_items($wishlist_items);
			if ( class_exists('PRODDISP_Wishlist_Analytics') ) {
				PRODDISP_Wishlist_Analytics::record_event( $product_id, 'remove' );
			}
		}

		wp_send_json_success(array(
			'message' => __('Product removed from wishlist', 'product-display'),
			'count' => count($wishlist_items),
		));
	}

	/**
	 * Save wishlist items.
	 *
	 * @param array $items Array of product IDs.
	 */
	private function save_wishlist_items( $items ) {
		$items = array_map('absint', $items);
		$items = array_filter($items);

		// For logged in users, save to user meta.
		if ( is_user_logged_in() ) {
			$user_id = get_current_user_id();
			update_user_meta($user_id, 'proddisp_wishlist_items', $items);
		}
		// For guests, save to cookie.
		else {
			setcookie(
				'proddisp_wishlist_items',
				implode(',', $items),
				time() + ( 86400 * 30 ), // 30 days.
				'/'
			);
		}
	}

	/**
	 * Get wishlist items via AJAX.
	 */
	public function get_wishlist() {
		check_ajax_referer('wcps-nonce', 'nonce');

		$wishlist_items = $this->get_wishlist_items();

		ob_start();
		$this->render_wishlist_products($wishlist_items);
		$wishlist_html = ob_get_clean();

		wp_send_json_success(array(
			'html' => $wishlist_html,
			'count' => count($wishlist_items),
		));
	}

	/**
	 * Render wishlist products.
	 *
	 * @param array $product_ids Array of product IDs.
	 */
	public function render_wishlist_products( $product_ids ) {
		if ( empty($product_ids) ) {
			echo '<div class="wcps-wishlist-empty">';
			echo '<div class="wcps-wishlist-empty-icon"><span class="wcps-icon wcps-icon-heart-empty"></span></div>';
			echo '<h3>' . esc_html__('Your wishlist is empty', 'product-display') . '</h3>';
			echo '<p>' . esc_html__('Start adding products you love to your wishlist!', 'product-display') . '</p>';
			echo '</div>';
			return;
		}

		$products = array();
		foreach ( $product_ids as $product_id ) {
			$product = wc_get_product($product_id);
			if ( $product ) {
				$products[] = $product;
			}
		}

		if ( empty($products) ) {
			echo '<div class="wcps-wishlist-empty">';
			echo '<h3>' . esc_html__('No valid products in your wishlist', 'product-display') . '</h3>';
			echo '</div>';
			return;
		}

		?>
		<div class="wcps-wishlist-products">
			<?php foreach ( $products as $product ) { ?>
				<div class="wcps-wishlist-product" data-product_id="<?php echo esc_attr($product->get_id()); ?>">
					<div class="wcps-wishlist-product-image">
						<a href="<?php echo esc_url(get_permalink($product->get_id())); ?>">
							<?php echo wp_kses_post($product->get_image('medium')); ?>
						</a>
						<button class="wcps-wishlist-remove-item" data-product_id="<?php echo esc_attr($product->get_id()); ?>" title="<?php esc_attr_e('Remove from wishlist', 'product-display'); ?>">
							<span class="wcps-icon wcps-icon-close"></span>
						</button>
					</div>
					<div class="wcps-wishlist-product-content">
						<h3 class="wcps-wishlist-product-title">
							<a href="<?php echo esc_url(get_permalink($product->get_id())); ?>">
								<?php echo esc_html($product->get_name()); ?>
							</a>
						</h3>
						<div class="wcps-wishlist-product-price">
							<?php echo wp_kses_post($product->get_price_html()); ?>
						</div>
						<?php if ( $product->is_in_stock() ) { ?>
							<div class="wcps-wishlist-product-stock in-stock">
								<span class="wcps-stock-icon"></span>
								<?php esc_html_e('In Stock', 'product-display'); ?>
							</div>
						<?php } else { ?>
							<div class="wcps-wishlist-product-stock out-of-stock">
								<span class="wcps-stock-icon"></span>
								<?php esc_html_e('Out of Stock', 'product-display'); ?>
							</div>
						<?php } ?>
						<div class="wcps-wishlist-product-actions">
							<?php if ( $product->is_purchasable() && $product->is_in_stock() ) { ?>
								<button class="wcps-wishlist-add-to-cart" data-product_id="<?php echo esc_attr($product->get_id()); ?>">
									<span class="wcps-icon wcps-icon-cart"></span>
									<?php esc_html_e('Add to Cart', 'product-display'); ?>
								</button>
							<?php } ?>
							<button class="wcps-wishlist-remove-item" data-product_id="<?php echo esc_attr($product->get_id()); ?>">
								<span class="wcps-icon wcps-icon-trash"></span>
								<?php esc_html_e('Remove', 'product-display'); ?>
							</button>
						</div>
					</div>
				</div>
			<?php } ?>
		</div>
		<?php
	}

	/**
	 * AJAX handler for Add to Cart
	 */
	public function ajax_add_to_cart() {
		// Validate nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wcps-nonce' ) ) {
			wp_send_json_error([ 'message' => __( 'Invalid security token', 'product-display' ) ]);
		}

		$product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
		$quantity = isset($_POST['quantity']) ? absint($_POST['quantity']) : 1;

		if ( ! $product_id ) {
			wp_send_json_error([ 'message' => __( 'Invalid product ID', 'product-display' ) ]);
		}

		// Add to cart
		$added = WC()->cart->add_to_cart( $product_id, $quantity );

		if ( $added ) {
			// Get updated cart fragments
			ob_start();
			woocommerce_mini_cart();
			$mini_cart = ob_get_clean();

			$fragments = apply_filters( 'woocommerce_add_to_cart_fragments', array(
				'div.widget_shopping_cart_content' => '<div class="widget_shopping_cart_content">' . $mini_cart . '</div>',
			) );

			wp_send_json_success([
				'message' => __( 'Product added to cart!', 'product-display' ),
				'fragments' => $fragments,
				'cart_hash' => WC()->cart->get_cart_hash(),
			]);
		} else {
			wp_send_json_error([ 'message' => __( 'Could not add to cart.', 'product-display' ) ]);
		}
	}

	/**
	 * Wishlist page shortcode.
	 *
	 * @param array $atts Shortcode attributes.
	 * @return string Shortcode output [proddisp_wishlist].
	 */
	public function wishlist_shortcode( $atts ) {
		$atts = shortcode_atts(array(
			'title' => __('My Wishlist', 'product-display'),
		), $atts, 'proddisp_wishlist');

		ob_start();

		echo '<div class="wcps-wishlist-page">';
		echo '<h1>' . esc_html($atts['title']) . '</h1>';

		$wishlist_items = $this->get_wishlist_items();
		$this->render_wishlist_products($wishlist_items);

		echo '</div>';

		return ob_get_clean();
	}

	public function render_wishlist_modal() {
		// Only render on frontend pages when wishlist is enabled
		if ( is_admin() || ! PRODDISP_Wishlist_Settings::is_wishlist_enabled() ) {
			return;
		}

		// Render floating button if enabled (sidebar JS will enhance it if sidebar is loaded)
		if ( PRODDISP_Wishlist_Settings::is_floating_button_enabled() ) {
			$this->render_floating_button();
		}
		?>
		<div id="wcps-wishlist-modal" class="wcps-modal wishlist-modal-container" style="display: none;">
			<div class="wcps-modal-content">
				<div class="wcps-modal-header">
					<h2><?php esc_html_e('My Wishlist', 'product-display'); ?></h2>
					<span class="wcps-modal-close">&times;</span>
				</div>
				<div class="wcps-modal-body">
					<div id="wcps-wishlist-container">
						<!-- Wishlist items will be loaded here via AJAX. -->
					</div>
				</div>
				<div class="wcps-modal-footer">
					<?php
					// Get wishlist page URL if set.
					$wishlist_page_id = get_option('proddisp_wishlist_page_id');
					if ( $wishlist_page_id ) {
						?>
						<a href="<?php echo esc_url(get_permalink($wishlist_page_id)); ?>" class="button wcps-button-primary">
							<?php esc_html_e('View Wishlist Page', 'product-display'); ?>
						</a>
						<?php
					}
					?>
				</div>
			</div>
		</div>
		<?php
	}

	/**
	 * Render floating wishlist button.
	 */
	public function render_floating_button() {
		$settings = PRODDISP_Wishlist_Settings::get_frontend_settings();
		$wishlist_count = count( $this->get_wishlist_items() );

		$position_class = 'proddisp-floating-' . str_replace( '-', '_', $settings['floating_button_position'] );
		$style_class = 'proddisp-floating-' . $settings['floating_button_style'];
		$size_class = 'proddisp-floating-' . $settings['floating_button_size'];

		?>
		<div id="proddisp-floating-wishlist" class="proddisp-floating-wishlist <?php echo esc_attr( $position_class ); ?> <?php echo esc_attr( $style_class ); ?> <?php echo esc_attr( $size_class ); ?>" 
			 style="background-color: <?php echo esc_attr( $settings['floating_button_color'] ); ?>; color: <?php echo esc_attr( $settings['floating_button_text_color'] ); ?>;">
			<span class="proddisp-floating-icon">
				<i class="fas fa-heart"></i>
			</span>
			<?php if ( $wishlist_count > 0 ) : ?>
				<span class="proddisp-floating-count"><?php echo esc_html( $wishlist_count ); ?></span>
			<?php endif; ?>
		</div>
		<?php
	}
}
