<?php
/**
 * Product Type Registration
 *
 * Registers the donation product type with WooCommerce.
 *
 * @package DonorCore\WooCommerce
 */

namespace DonorCore\WooCommerce;

defined( 'ABSPATH' ) || exit;

/**
 * Product Type Registration Class
 */
class Product_Type_Registration {

	/**
	 * Initialize registration hooks.
	 */
	public function init() {
		add_filter( 'woocommerce_product_class', array( $this, 'product_class' ), 10, 2 );
		add_filter( 'product_type_selector', array( $this, 'add_product_type' ) );
		add_filter( 'woocommerce_product_data_tabs', array( $this, 'product_data_tabs' ) );
		add_action( 'woocommerce_product_data_panels', array( $this, 'product_data_panels' ) );
		add_action( 'woocommerce_process_product_meta_donation', array( $this, 'save_product_data' ) );
		
		// Hide donation products from shop.
		add_action( 'pre_get_posts', array( $this, 'hide_from_shop' ) );
	}

	/**
	 * Load the donation product class.
	 *
	 * @param string $classname Product class name.
	 * @param string $product_type Product type.
	 * @return string
	 */
	public function product_class( $classname, $product_type ) {
		if ( 'donation' === $product_type ) {
			$classname = 'DonorCore\WooCommerce\WC_Product_Donation';
		}
		return $classname;
	}

	/**
	 * Add donation to product type selector.
	 *
	 * @param array $types Existing product types.
	 * @return array
	 */
	public function add_product_type( $types ) {
		$types['donation'] = __( 'Donation', 'donorcore-donations' );
		return $types;
	}

	/**
	 * Add custom product data tab.
	 *
	 * @param array $tabs Existing tabs.
	 * @return array
	 */
	public function product_data_tabs( $tabs ) {
		$tabs['donation'] = array(
			'label'    => __( 'Donation Settings', 'donorcore-donations' ),
			'target'   => 'donation_product_data',
			'class'    => array( 'show_if_donation' ),
			'priority' => 21,
		);
		return $tabs;
	}

	/**
	 * Add product data panel content.
	 */
	public function product_data_panels() {
		global $post;
		?>
		<div id="donation_product_data" class="panel woocommerce_options_panel">
			<div class="options_group">
				<?php
				woocommerce_wp_text_input(
					array(
						'id'          => '_donorcore_min_donation',
						'label'       => __( 'Minimum Donation Amount', 'donorcore-donations' ),
						'desc_tip'    => true,
						'description' => __( 'Minimum amount a donor can contribute (optional).', 'donorcore-donations' ),
						'type'        => 'number',
						'custom_attributes' => array(
							'step' => '0.01',
							'min'  => '0',
						),
					)
				);

				woocommerce_wp_text_input(
					array(
						'id'          => '_donorcore_suggested_amounts',
						'label'       => __( 'Suggested Amounts', 'donorcore-donations' ),
						'desc_tip'    => true,
						'description' => __( 'Comma-separated amounts (e.g., 50,100,250,500).', 'donorcore-donations' ),
						'placeholder' => '50,100,250,500',
					)
				);

				woocommerce_wp_text_input(
					array(
						'id'          => '_donorcore_campaign_id',
						'label'       => __( 'Linked Campaign ID', 'donorcore-donations' ),
						'desc_tip'    => true,
						'description' => __( 'Campaign post ID (managed automatically).', 'donorcore-donations' ),
						'type'        => 'number',
						'custom_attributes' => array(
							'readonly' => 'readonly',
						),
					)
				);
				?>
			</div>
		</div>
		<?php
	}

	/**
	 * Save product data.
	 *
	 * @param int $post_id Product post ID.
	 */
	public function save_product_data( $post_id ) {
		// Check user permissions and nonce validation
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( isset( $_POST['woocommerce_meta_nonce'] ) && ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ), 'woocommerce_save_data' ) ) {
			return;
		}
		
		// Minimum donation amount.
		if ( isset( $_POST['_donorcore_min_donation'] ) ) {
			$min_donation = sanitize_text_field( wp_unslash( $_POST['_donorcore_min_donation'] ) );
			update_post_meta( $post_id, '_donorcore_min_donation', $min_donation );
		}

		// Suggested amounts.
		if ( isset( $_POST['_donorcore_suggested_amounts'] ) ) {
			$suggested = sanitize_text_field( wp_unslash( $_POST['_donorcore_suggested_amounts'] ) );
			
			// Convert comma-separated to JSON array.
			$amounts = array_map( 'floatval', array_filter( explode( ',', $suggested ) ) );
			update_post_meta( $post_id, '_donorcore_suggested_amounts', wp_json_encode( $amounts ) );
		}

		// Campaign ID.
		if ( isset( $_POST['_donorcore_campaign_id'] ) ) {
			$campaign_id = absint( $_POST['_donorcore_campaign_id'] );
			update_post_meta( $post_id, '_donorcore_campaign_id', $campaign_id );
		}
	}

	/**
	 * Hide donation products from shop pages.
	 *
	 * @param \WP_Query $query WordPress query.
	 */
	public function hide_from_shop( $query ) {
		if ( ! is_admin() && $query->is_main_query() && ( is_shop() || is_product_category() || is_product_tag() ) ) {
			$tax_query = $query->get( 'tax_query' ) ? $query->get( 'tax_query' ) : array();

			$tax_query[] = array(
				'taxonomy' => 'product_type',
				'field'    => 'slug',
				'terms'    => 'donation',
				'operator' => 'NOT IN',
			);

			$query->set( 'tax_query', $tax_query );
		}
	}
}
