<?php
/**
 * WooCommerce Product Customizations
 *
 * Handles "Dojo Product" functionality including:
 * - Product meta field for marking products as dojo products
 * - Member selector on product pages
 * - Add to cart validation
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/woocommerce
 * @since      1.0.0
 */

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

/**
 * Class MACM_Products
 *
 * Manages dojo product functionality
 *
 * @since 1.0.0
 */
class MACM_Products {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Admin: Add product meta field.
		add_action( 'woocommerce_product_options_general_product_data', array( $this, 'add_dojo_product_field' ) );
		add_action( 'woocommerce_process_product_meta', array( $this, 'save_dojo_product_field' ) );

		// Admin: Enqueue admin scripts.
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );

		// Frontend: Enqueue frontend styles.
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_styles' ) );

		// Frontend: Customize product page.
		add_action( 'woocommerce_before_add_to_cart_button', array( $this, 'add_member_selector' ) );

		// Shop/Archive: Customize add to cart button for dojo products.
		add_filter( 'woocommerce_loop_add_to_cart_button', array( $this, 'customize_loop_add_to_cart_button' ), 10, 2 );

		// Validation.
		add_filter( 'woocommerce_add_to_cart_validation', array( $this, 'validate_member_selection' ), 10, 3 );

		// Enqueue scripts.
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
	}

	/**
	 * Add "Dojo Product" checkbox to product edit page
	 *
	 * @since 1.0.0
	 */
	public function add_dojo_product_field() {
		global $post;

		// Ensure $post is valid.
		if ( ! $post || ! isset( $post->ID ) ) {
			return;
		}

		echo '<div class="options_group">';

		woocommerce_wp_checkbox(
			array(
				'id'          => '_is_dojo_product',
				'label'       => __( 'Dojo Product', 'martial-arts-club-manager' ),
				'description' => __( 'Check this if the product requires member association (e.g., memberships, equipment, uniforms)', 'martial-arts-club-manager' ),
				'desc_tip'    => false,
			)
		);

		// Get membership types for dropdown.
		$membership_types = MACM_Membership_Type::get_types_for_select( true );
		$selected_type    = get_post_meta( $post->ID, '_macm_membership_type_id', true );

		// Add empty option.
		$membership_options = array( '' => __( '-- No Membership Type --', 'martial-arts-club-manager' ) ) + $membership_types;

		woocommerce_wp_select(
			array(
				'id'          => '_macm_membership_type_id',
				'label'       => __( 'Assign Membership Type', 'martial-arts-club-manager' ),
				'description' => __( 'When this product is purchased, assign this membership type to the associated member. Leave blank for no assignment.', 'martial-arts-club-manager' ),
				'desc_tip'    => true,
				'options'     => $membership_options,
				'value'       => $selected_type,
			)
		);

		echo '</div>';
	}

	/**
	 * Save "Dojo Product" meta field
	 *
	 * @since 1.0.0
	 * @param int $post_id Product post ID.
	 */
	public function save_dojo_product_field( $post_id ) {
		// Start output buffering to prevent any output from breaking redirects.
		if ( ! ob_get_level() ) {
			ob_start();
		}

		// Verify this is a product post type.
		$post_type = get_post_type( $post_id );
		if ( ! $post_type || 'product' !== $post_type ) {
			if ( ob_get_level() ) {
				ob_end_clean();
			}
			return;
		}

		// Check if this is an autosave.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			if ( ob_get_level() ) {
				ob_end_clean();
			}
			return;
		}

		// Check user permissions.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			if ( ob_get_level() ) {
				ob_end_clean();
			}
			return;
		}

		// Verify nonce (WooCommerce sets this).
		$nonce = isset( $_POST['woocommerce_meta_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['woocommerce_meta_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'woocommerce_save_data' ) ) {
			if ( ob_get_level() ) {
				ob_end_clean();
			}
			return;
		}

		// Save dojo product setting.
		$is_dojo_product = isset( $_POST['_is_dojo_product'] ) ? 'yes' : 'no';
		update_post_meta( $post_id, '_is_dojo_product', $is_dojo_product );

		// Save membership type association.
		if ( isset( $_POST['_macm_membership_type_id'] ) ) {
			$membership_type_id = sanitize_text_field( wp_unslash( $_POST['_macm_membership_type_id'] ) );

			if ( ! empty( $membership_type_id ) && is_numeric( $membership_type_id ) ) {
				update_post_meta( $post_id, '_macm_membership_type_id', absint( $membership_type_id ) );
			} else {
				delete_post_meta( $post_id, '_macm_membership_type_id' );
			}
		} else {
			// If the field is not in POST, delete the meta.
			delete_post_meta( $post_id, '_macm_membership_type_id' );
		}

		// Clean output buffer if we started one.
		if ( ob_get_level() ) {
			ob_end_clean();
		}
	}

	/**
	 * Check if a product is a dojo product
	 *
	 * @since 1.0.0
	 * @param int $product_id Product ID.
	 * @return bool True if dojo product, false otherwise.
	 */
	public static function is_dojo_product( $product_id ) {
		return 'yes' === get_post_meta( $product_id, '_is_dojo_product', true );
	}

	/**
	 * Customize add to cart button on shop/archive pages for dojo products
	 *
	 * @since 1.0.21
	 * @param string     $button  Default button HTML.
	 * @param WC_Product $product Product object.
	 * @return string Modified button HTML.
	 */
	public function customize_loop_add_to_cart_button( $button, $product ) {
		// Check if this is a dojo product.
		if ( ! self::is_dojo_product( $product->get_id() ) ) {
			return $button;
		}

		// Get product permalink.
		$product_url = get_permalink( $product->get_id() );

		// Create custom button that links to product page, wrapped in centered div.
		$button = sprintf(
			'<div class="kcm-dojo-product-button-wrapper" style="text-align: center;"><a href="%s" class="button product_type_simple kcm-dojo-product-button" rel="nofollow">%s</a></div>',
			esc_url( $product_url ),
			esc_html__( 'Select Member to Buy', 'martial-arts-club-manager' )
		);

		return $button;
	}

	/**
	 * Add member selector before add to cart button
	 *
	 * @since 1.0.0
	 */
	public function add_member_selector() {
		global $product;

		if ( ! $product || ! self::is_dojo_product( $product->get_id() ) ) {
			return;
		}

		// Check if user is logged in.
		if ( ! is_user_logged_in() ) {
			$this->display_login_message();
			return;
		}

		// Get user's members.
		$user_id = get_current_user_id();
		$members = MACM_Member::get_by_user( $user_id );

		if ( empty( $members ) ) {
			$this->display_no_members_message();
			return;
		}

		// Display member selector.
		$this->display_member_selector( $members );
	}

	/**
	 * Display login required message
	 *
	 * @since 1.0.0
	 */
	private function display_login_message() {
		$login_url = wp_login_url( get_permalink() );
		?>
		<div class="kcm-product-notice kcm-login-required">
			<p>
				<strong><?php esc_html_e( 'Login Required', 'martial-arts-club-manager' ); ?></strong><br>
				<?php
				echo wp_kses_post(
					sprintf(
						/* translators: 1: opening link tag with URL, 2: link text "logged in", 3: closing link tag */
						__( 'You must be %1$s%2$s%3$s to purchase this product.', 'martial-arts-club-manager' ),
						'<a href="' . esc_url( $login_url ) . '">',
						esc_html__( 'logged in', 'martial-arts-club-manager' ),
						'</a>'
					)
				);
				?>
			</p>
		</div>
		<?php
		// Enqueue inline styles using WordPress-compliant method.
		$login_notice_styles = '
			.kcm-product-notice {
				background: #f8d7da;
				border: 1px solid #f5c6cb;
				color: #721c24;
				padding: 15px;
				margin: 20px 0;
				border-radius: 4px;
			}
			.kcm-login-required .button,
			.kcm-product-notice + .button {
				display: none !important;
			}
		';
		wp_add_inline_style( 'kcm-woocommerce', $login_notice_styles );
		?>
		<?php
	}

	/**
	 * Display "no members" message
	 *
	 * @since 1.0.0
	 */
	private function display_no_members_message() {
		$my_account_url = wc_get_page_permalink( 'myaccount' );
		?>
		<div class="kcm-product-notice kcm-no-members">
			<p>
				<strong><?php esc_html_e( 'Member Required', 'martial-arts-club-manager' ); ?></strong><br>
				<?php
				echo wp_kses_post(
					sprintf(
						/* translators: 1: opening link tag with URL, 2: link text "add a member to your account", 3: closing link tag */
						__( 'You must %1$s%2$s%3$s to purchase this product.', 'martial-arts-club-manager' ),
						'<a href="' . esc_url( $my_account_url ) . '">',
						esc_html__( 'add a member to your account', 'martial-arts-club-manager' ),
						'</a>'
					)
				);
				?>
			</p>
		</div>
		<?php
		// Enqueue inline styles using WordPress-compliant method.
		$no_members_styles = '
			.kcm-no-members .button,
			.kcm-product-notice + .button {
				display: none !important;
			}
		';
		wp_add_inline_style( 'kcm-woocommerce', $no_members_styles );
		?>
		<?php
	}

	/**
	 * Display member selector dropdown
	 *
	 * @since 1.0.0
	 * @param array $members Array of member objects.
	 */
	private function display_member_selector( $members ) {
		?>
		<div class="kcm-member-selector">
			<label for="macm_member_id">
				<?php esc_html_e( 'Select Member', 'martial-arts-club-manager' ); ?>
				<span class="required">*</span>
			</label>
			<p class="kcm-member-description">
				<?php esc_html_e( 'This product will be associated with the selected member.', 'martial-arts-club-manager' ); ?>
			</p>
			<select name="macm_member_id" id="macm_member_id" required>
				<option value=""><?php esc_html_e( '-- Select a Member --', 'martial-arts-club-manager' ); ?></option>
				<?php foreach ( $members as $member ) : ?>
					<option value="<?php echo esc_attr( $member->id ); ?>">
						<?php
						echo esc_html( $member->full_name );
						if ( ! empty( $member->belt_color ) ) {
							echo ' (' . esc_html( ucfirst( $member->belt_color ) ) . ' Belt)';
						}
						?>
					</option>
				<?php endforeach; ?>
			</select>
			<?php wp_nonce_field( 'macm_member_selection', 'macm_member_nonce' ); ?>
		</div>

		<?php
		// Enqueue inline styles using WordPress-compliant method.
		$member_selector_styles = '
			.kcm-member-selector {
				margin: 20px 0;
				padding: 15px;
				background: #F4F4F2;
				border: 1px solid #D1D5DB;
				border-radius: 4px;
			}
			.kcm-member-selector label {
				display: block;
				font-weight: bold;
				margin-bottom: 5px;
			}
			.kcm-member-selector .required {
				color: #B11226;
			}
			.kcm-member-description {
				font-size: 0.9em;
				color: #6B7280;
				margin: 0 0 10px 0;
			}
			.kcm-member-selector select {
				width: 100%;
				padding: 10px;
				font-size: 1em;
				border: 1px solid #D1D5DB;
				border-radius: 4px;
			}
		';
		wp_add_inline_style( 'kcm-woocommerce', $member_selector_styles );
		?>
		<?php
	}

	/**
	 * Validate member selection before adding to cart
	 *
	 * @since 1.0.0
	 * @param bool $passed     Whether validation passed.
	 * @param int  $product_id Product ID.
	 * @param int  $quantity   Quantity.
	 * @return bool Whether validation passed.
	 */
	public function validate_member_selection( $passed, $product_id, $quantity ) {
		// Check if this is a dojo product.
		if ( ! self::is_dojo_product( $product_id ) ) {
			return $passed;
		}

		// Check if user is logged in.
		if ( ! is_user_logged_in() ) {
			wc_add_notice( __( 'You must be logged in to purchase this product.', 'martial-arts-club-manager' ), 'error' );
			return false;
		}

		// Check if member is selected.
		$member_id = isset( $_POST['macm_member_id'] ) ? absint( wp_unslash( $_POST['macm_member_id'] ) ) : 0;

		// Verify our member selection nonce - required for dojo products.
		$macm_nonce = isset( $_POST['macm_member_nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['macm_member_nonce'] ) )
			: '';

		if ( ! wp_verify_nonce( $macm_nonce, 'macm_member_selection' ) ) {
			wc_add_notice( __( 'Security check failed. Please try again.', 'martial-arts-club-manager' ), 'error' );
			return false;
		}
		if ( empty( $member_id ) ) {
			wc_add_notice( __( 'Please select a member for this product.', 'martial-arts-club-manager' ), 'error' );
			return false;
		}

		// Validate member exists.
		$member = MACM_Member::get( $member_id );
		if ( ! $member ) {
			wc_add_notice( __( 'Invalid member selected.', 'martial-arts-club-manager' ), 'error' );
			return false;
		}

		// Verify member belongs to current user.
		$user_id = get_current_user_id();
		if ( (int) $member->user_id !== $user_id ) {
			wc_add_notice( __( 'You can only select your own members.', 'martial-arts-club-manager' ), 'error' );
			return false;
		}

		return $passed;
	}

	/**
	 * Enqueue admin scripts for product edit page
	 *
	 * @since 1.0.17
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_scripts( $hook ) {
		// Only load on product edit page.
		if ( 'post.php' === $hook || 'post-new.php' === $hook ) {
			global $post;
			if ( $post && isset( $post->post_type ) && 'product' === $post->post_type ) {
				wp_enqueue_script(
					'kcm-admin-product',
					plugins_url( 'assets/js/admin-product.js', dirname( __DIR__ ) ),
					array( 'jquery' ),
					MACM_VERSION,
					true
				);
			}
		}
	}

	/**
	 * Enqueue frontend styles for WooCommerce pages
	 *
	 * @since 1.0.174
	 */
	public function enqueue_frontend_styles() {
		// Only enqueue on product pages and shop pages.
		if ( is_product() || is_shop() || is_product_category() || is_product_tag() || is_cart() || is_checkout() ) {
			wp_enqueue_style(
				'kcm-woocommerce',
				plugins_url( 'assets/css/woocommerce.css', dirname( __DIR__ ) ),
				array(),
				MACM_VERSION,
				'all'
			);
		}
	}

	/**
	 * Enqueue frontend scripts
	 *
	 * @since 1.0.0
	 */
	public function enqueue_scripts() {
		if ( is_product() ) {
			wp_enqueue_style(
				'kcm-woocommerce',
				plugins_url( 'assets/css/woocommerce.css', dirname( __DIR__ ) ),
				array(),
				MACM_VERSION
			);

			wp_enqueue_script(
				'kcm-woocommerce',
				plugins_url( 'assets/js/woocommerce.js', dirname( __DIR__ ) ),
				array( 'jquery' ),
				MACM_VERSION,
				true
			);
		}
	}
}

// Initialize.
new MACM_Products();
