<?php
/**
 * WooCommerce Checkout Customizations
 *
 * Handles member information in checkout and orders
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/woocommerce
 * @since      1.0.0
 */

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

/**
 * Class MACM_Checkout
 *
 * Manages checkout and order customizations for dojo products
 *
 * @since 1.0.0
 */
class MACM_Checkout {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		// Save member data to order items.
		add_action( 'woocommerce_checkout_create_order_line_item', array( $this, 'add_member_to_order_item' ), 10, 4 );

		// Display member info in order details.
		add_action( 'woocommerce_order_item_meta_end', array( $this, 'display_member_in_order' ), 10, 4 );

		// Save to database when order is completed.
		add_action( 'woocommerce_order_status_completed', array( $this, 'save_product_member_association' ), 10, 1 );

		// Also save on processing status (for virtual/downloadable products).
		add_action( 'woocommerce_order_status_processing', array( $this, 'save_product_member_association' ), 10, 1 );
	}

	/**
	 * Add member data to order line item
	 *
	 * @since 1.0.0
	 * @param WC_Order_Item_Product $item          Order item.
	 * @param string                $cart_item_key Cart item key.
	 * @param array                 $values        Cart item values.
	 * @param WC_Order              $order         Order object.
	 */
	public function add_member_to_order_item( $item, $cart_item_key, $values, $order ) {
		if ( isset( $values['macm_member_id'] ) ) {
			$item->add_meta_data( '_macm_member_id', $values['macm_member_id'], true );
		}

		if ( isset( $values['macm_member_name'] ) ) {
			$item->add_meta_data( '_macm_member_name', $values['macm_member_name'], true );
		}
	}

	/**
	 * Display member information in order details
	 *
	 * @since 1.0.0
	 * @param int           $item_id   Order item ID.
	 * @param WC_Order_Item $item      Order item.
	 * @param WC_Order      $order     Order object.
	 * @param bool          $plain_text Plain text email.
	 */
	public function display_member_in_order( $item_id, $item, $order, $plain_text = false ) {
		$member_name = $item->get_meta( '_macm_member_name' );

		if ( $member_name ) {
			if ( $plain_text ) {
				echo "\n" . esc_html__( 'For Member:', 'martial-arts-club-manager' ) . ' ' . esc_html( $member_name );
			} else {
				echo '<div class="kcm-order-member-info">';
				echo '<strong>' . esc_html__( 'For Member:', 'martial-arts-club-manager' ) . '</strong> ';
				echo esc_html( $member_name );
				echo '</div>';
			}
		}
	}

	/**
	 * Save product-member association to database when order is completed
	 *
	 * @since 1.0.0
	 * @param int $order_id Order ID.
	 */
	public function save_product_member_association( $order_id ) {
		// Prevent duplicate processing.
		if ( 'yes' === get_post_meta( $order_id, '_macm_associations_saved', true ) ) {
			return;
		}

		$order = wc_get_order( $order_id );

		if ( ! $order ) {
			return;
		}

		foreach ( $order->get_items() as $item_id => $item ) {
			$member_id  = $item->get_meta( '_macm_member_id' );
			$product_id = $item->get_product_id();

			if ( $member_id && $product_id ) {
				// Save association to database.
				$data = array(
					'order_id'      => $order_id,
					'order_item_id' => $item_id,
					'product_id'    => $product_id,
					'member_id'     => $member_id,
					'quantity'      => $item->get_quantity(),
					'user_id'       => $order->get_user_id(),
				);

				$result = MACM_Product_Member::create( $data );

				if ( ! is_wp_error( $result ) ) {
					// Assign membership type to member if product has one configured.
					$this->assign_membership_type_to_member( $product_id, $member_id );
				}
			}
		}

		// Mark as processed.
		update_post_meta( $order_id, '_macm_associations_saved', 'yes' );
	}

	/**
	 * Assign membership type to member if product has one configured
	 *
	 * @since 1.0.17
	 * @param int $product_id Product ID.
	 * @param int $member_id  Member ID.
	 */
	private function assign_membership_type_to_member( $product_id, $member_id ) {
		// Get the membership type associated with this product.
		$membership_type_id = get_post_meta( $product_id, '_macm_membership_type_id', true );

		if ( empty( $membership_type_id ) ) {
			return; // No membership type configured for this product.
		}

		// Verify the membership type exists.
		$membership_type = MACM_Membership_Type::get( $membership_type_id );
		if ( ! $membership_type ) {
			return;
		}

		// Update the member's membership type.
		global $wpdb;

		// Invalidate member cache before update.
		wp_cache_delete( 'macm_member_' . $member_id, 'macm' );
		wp_cache_delete( 'macm_member_details_' . $member_id, 'macm' );

		$updated = $wpdb->update(
			$wpdb->prefix . 'macm_members',
			array( 'membership_type_id' => $membership_type_id ),
			array( 'id' => $member_id ),
			array( '%d' ),
			array( '%d' )
		);

		if ( false === $updated ) {
			do_action( 'macm_membership_type_update_failed', $member_id, $membership_type_id );
		}
	}
}

// Initialize.
new MACM_Checkout();
