<?php
/**
 * Wishlist Settings Handler for Product Display Admin.
 *
 * @package Product_Display
 */

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

/**
 * Class PRODDISP_Wishlist_Settings
 *
 * Handles wishlist settings for the admin interface.
 */
class PRODDISP_Wishlist_Settings {

	/**
	 * 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() {
		add_action( 'wp_ajax_proddisp_get_wishlist_settings', array( $this, 'get_wishlist_settings' ) );
		add_action( 'wp_ajax_proddisp_save_wishlist_settings', array( $this, 'save_wishlist_settings' ) );
		add_action( 'wp_ajax_proddisp_get_wishlist_data', array( $this, 'get_wishlist_data' ) );
		add_action( 'wp_ajax_nopriv_proddisp_get_wishlist_data', array( $this, 'get_wishlist_data' ) );
	}

	/**
	 * Get wishlist settings via AJAX.
	 */
	public function get_wishlist_settings() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid security token', 'product-display' ) ) );
		}

		$default_settings = array(
			'enable_wishlist' => false,
			'enable_floating_button' => false,
			'floating_button_position' => 'bottom-right',
			'show_on_shop_page' => true,
			'show_on_product_page' => true,
			'guest_wishlist_expiry' => 30,
			'wishlist_page_id' => '',
			'floating_button_style' => 'circle',
			'floating_button_color' => '#e91e63',
			'floating_button_text_color' => '#ffffff',
			'floating_button_size' => 'medium',
			'sidebar_width' => 400,
			'enable_quantity_controls' => true,
			'enable_total_calculation' => true,
			'show_product_images' => true,
			'redirect_after_add' => false,
			'auto_remove_after_cart' => false,
			// Wishlist Button Settings
			'wishlist_button_style' => 'both',
			'wishlist_button_shape' => 'rounded',
			'wishlist_button_color' => '#e91e63',
			'wishlist_button_text_color' => '#ffffff',
			'wishlist_button_border_color' => '#e91e63',
			'wishlist_button_text' => 'Add to Wishlist',
			'wishlist_button_text_remove' => 'Remove from Wishlist',
		);

		$saved_settings = get_option( 'proddisp_wishlist_settings', array() );
		$settings = wp_parse_args( $saved_settings, $default_settings );

		wp_send_json_success( $settings );
	}

	/**
	 * Save wishlist settings via AJAX.
	 */
	public function save_wishlist_settings() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'proddisp_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid security token', 'product-display' ) ) );
		}

		// Check user capabilities
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'product-display' ) ) );
		}

		$settings_json = isset( $_POST['settings'] ) ? sanitize_text_field( wp_unslash( $_POST['settings'] ) ) : '';

		if ( empty( $settings_json ) ) {
			wp_send_json_error( array( 'message' => __( 'No settings data provided', 'product-display' ) ) );
		}

		$settings = json_decode( $settings_json, true );

		if ( json_last_error() !== JSON_ERROR_NONE ) {
			wp_send_json_error( array( 'message' => __( 'Invalid settings data format', 'product-display' ) ) );
		}

		// Sanitize settings
		$sanitized_settings = $this->sanitize_settings( $settings );

		// Save settings
		$saved = update_option( 'proddisp_wishlist_settings', $sanitized_settings );

		if ( $saved ) {
			wp_send_json_success( array(
				'message' => __( 'Wishlist settings saved successfully', 'product-display' ),
				'settings' => $sanitized_settings,
			) );
		} else {
			// Check if settings are already the same (update_option returns false if no change)
			$existing_settings = get_option( 'proddisp_wishlist_settings', array() );
			$is_same = ( $existing_settings === $sanitized_settings );
			
			if ( $is_same ) {
				wp_send_json_success( array(
					'message' => __( 'Settings are already up to date', 'product-display' ),
					'settings' => $sanitized_settings,
				) );
			} else {
				wp_send_json_error( array( 'message' => __( 'Failed to save settings', 'product-display' ) ) );
			}
		}
	}

	/**
	 * Sanitize wishlist settings.
	 *
	 * @param array $settings Raw settings array.
	 * @return array Sanitized settings.
	 */
	private function sanitize_settings( $settings ) {
		$sanitized = array();

		// Boolean settings
		$boolean_keys = array(
			'enable_wishlist',
			'enable_floating_button',
			'show_on_shop_page',
			'show_on_product_page',
			'enable_quantity_controls',
			'enable_total_calculation',
			'show_product_images',
			'redirect_after_add',
			'auto_remove_after_cart',
		);

		foreach ( $boolean_keys as $key ) {
			$sanitized[ $key ] = isset( $settings[ $key ] ) ? (bool) $settings[ $key ] : false;
		}

		// String settings
		$string_keys = array(
			'floating_button_position' => 'bottom-right',
			'floating_button_style' => 'circle',
			'floating_button_size' => 'medium',
			'wishlist_button_style' => 'both',
			'wishlist_button_shape' => 'rounded',
			'wishlist_button_text' => 'Add to Wishlist',
			'wishlist_button_text_remove' => 'Remove from Wishlist',
		);

		foreach ( $string_keys as $key => $default ) {
			$sanitized[ $key ] = isset( $settings[ $key ] ) ? sanitize_text_field( $settings[ $key ] ) : $default;
		}

		// Color settings
		$color_keys = array(
			'floating_button_color' => '#e91e63',
			'floating_button_text_color' => '#ffffff',
			'wishlist_button_color' => '#e91e63',
			'wishlist_button_text_color' => '#ffffff',
			'wishlist_button_border_color' => '#e91e63',
		);

		foreach ( $color_keys as $key => $default ) {
			if ( isset( $settings[ $key ] ) ) {
				$color = sanitize_hex_color( $settings[ $key ] );
				$sanitized[ $key ] = $color ? $color : $default;
			} else {
				$sanitized[ $key ] = $default;
			}
		}

		// Numeric settings
		$sanitized['guest_wishlist_expiry'] = isset( $settings['guest_wishlist_expiry'] ) ?
			max( 1, min( 365, absint( $settings['guest_wishlist_expiry'] ) ) ) : 30;

		$sanitized['sidebar_width'] = isset( $settings['sidebar_width'] ) ?
			max( 300, min( 600, absint( $settings['sidebar_width'] ) ) ) : 400;

		$sanitized['wishlist_page_id'] = isset( $settings['wishlist_page_id'] ) ?
			absint( $settings['wishlist_page_id'] ) : '';

		return $sanitized;
	}

	/**
	 * Get wishlist data for frontend via AJAX.
	 */
	public function get_wishlist_data() {
		// Verify nonce
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wcps-nonce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid security token', 'product-display' ) ) );
		}

		$wishlist_instance = PRODDISP_Wishlist::get_instance();
		$wishlist_items = $wishlist_instance->get_wishlist_items();

		$products_data = array();
		$total_price = 0;

		foreach ( $wishlist_items as $product_id ) {
			$product = wc_get_product( $product_id );

			if ( ! $product ) {
				continue;
			}

			$product_data = array(
				'id' => $product_id,
				'name' => $product->get_name(),
				'price' => $product->get_price(),
				'price_html' => $product->get_price_html(),
				'image' => wp_get_attachment_image_src( $product->get_image_id(), 'thumbnail' ),
				'permalink' => get_permalink( $product_id ),
				'in_stock' => $product->is_in_stock(),
				'is_purchasable' => $product->is_purchasable(),
				'quantity' => 1, // Default quantity
				'type' => $product->get_type(),
			);

			// Handle variable products
			if ( $product->is_type( 'variable' ) ) {
				$variations = $product->get_available_variations();
				$product_data['variations'] = array();

				foreach ( $variations as $variation ) {
					$variation_obj = wc_get_product( $variation['variation_id'] );
					if ( $variation_obj ) {
						$product_data['variations'][] = array(
							'id' => $variation['variation_id'],
							'attributes' => $variation['attributes'],
							'price' => $variation_obj->get_price(),
							'price_html' => $variation_obj->get_price_html(),
							'in_stock' => $variation_obj->is_in_stock(),
						);
					}
				}
			}

			$products_data[] = $product_data;

			if ( is_numeric( $product->get_price() ) ) {
				$total_price += floatval( $product->get_price() );
			}
		}

		wp_send_json_success( array(
			'products' => $products_data,
			'count' => count( $products_data ),
			'total_price' => $total_price,
			'total_price_html' => wc_price( $total_price ),
			'currency_symbol' => get_woocommerce_currency_symbol(),
		) );
	}

	/**
	 * Get wishlist settings for frontend use.
	 *
	 * @return array Wishlist settings.
	 */
	public static function get_frontend_settings() {
		$default_settings = array(
			'enable_wishlist' => false,
			'enable_floating_button' => false,
			'floating_button_position' => 'bottom-right',
			'show_on_shop_page' => true,
			'show_on_product_page' => true,
			'floating_button_style' => 'circle',
			'floating_button_color' => '#e91e63',
			'floating_button_text_color' => '#ffffff',
			'floating_button_size' => 'medium',
			'sidebar_width' => 400,
			'enable_quantity_controls' => true,
			'enable_total_calculation' => true,
			'show_product_images' => true,
			'auto_remove_after_cart' => false,
			// Wishlist Button Settings
			'wishlist_button_style' => 'both',
			'wishlist_button_shape' => 'rounded',
			'wishlist_button_color' => '#e91e63',
			'wishlist_button_text_color' => '#ffffff',
			'wishlist_button_border_color' => '#e91e63',
			'wishlist_button_text' => 'Add to Wishlist',
			'wishlist_button_text_remove' => 'Remove from Wishlist',
		);

		$saved_settings = get_option( 'proddisp_wishlist_settings', array() );
		return wp_parse_args( $saved_settings, $default_settings );
	}

	/**
	 * Check if wishlist is enabled.
	 *
	 * @return bool True if wishlist is enabled.
	 */
	public static function is_wishlist_enabled() {
		$settings = self::get_frontend_settings();
		$enabled = isset($settings['enable_wishlist']) ? $settings['enable_wishlist'] : false;
		return $enabled;
	}

	/**
	 * Check if floating button is enabled.
	 *
	 * @return bool True if floating button is enabled.
	 */
	public static function is_floating_button_enabled() {
		$settings = self::get_frontend_settings();
		return $settings['enable_wishlist'] && $settings['enable_floating_button'];
	}

	/**
	 * Check if wishlist should be shown on current page.
	 *
	 * @return bool True if wishlist should be shown.
	 */
	public static function should_show_on_current_page() {
		if ( ! self::is_wishlist_enabled() ) {
			return false;
		}

		$settings = self::get_frontend_settings();

		if ( is_shop() || is_product_category() || is_product_tag() ) {
			return $settings['show_on_shop_page'];
		}

		if ( is_product() ) {
			return $settings['show_on_product_page'];
		}

		return false;
	}
}

// Initialize the class
PRODDISP_Wishlist_Settings::get_instance();
