<?php
/**
 * WooCommerce My Account Customization
 *
 * Handles custom fields in My Account area
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/woocommerce
 * @since      1.0.0
 */

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

/**
 * Class MACM_My_Account
 *
 * Customizes WooCommerce My Account area with additional fields
 *
 * @since 1.0.0
 */
class MACM_My_Account {

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		$this->init_hooks();
	}

	/**
	 * Register all hooks related to My Account
	 *
	 * @since 1.0.0
	 */
	private function init_hooks() {
		// Add mobile number field to account details.
		add_action( 'woocommerce_edit_account_form', array( $this, 'add_mobile_number_field' ) );

		// Validate mobile number field.
		add_action( 'woocommerce_save_account_details_errors', array( $this, 'validate_mobile_number' ), 10, 1 );

		// Save mobile number field.
		add_action( 'woocommerce_save_account_details', array( $this, 'save_mobile_number' ), 10, 1 );

		// Add custom links to My Account navigation.
		add_filter( 'woocommerce_account_menu_items', array( $this, 'add_custom_menu_items' ), 10, 1 );
		add_filter( 'woocommerce_get_endpoint_url', array( $this, 'custom_endpoint_urls' ), 10, 4 );
	}

	/**
	 * Add mobile number field to account details form
	 *
	 * @since 1.0.0
	 */
	public function add_mobile_number_field() {
		$user_id       = get_current_user_id();
		$mobile_number = get_user_meta( $user_id, 'macm_mobile_number', true );
		?>

		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="macm_mobile_number"><?php esc_html_e( 'Mobile Number', 'martial-arts-club-manager' ); ?></label>
			<input type="tel"
					class="woocommerce-Input woocommerce-Input--text input-text"
					name="macm_mobile_number"
					id="macm_mobile_number"
					value="<?php echo esc_attr( $mobile_number ); ?>"
					placeholder="<?php esc_attr_e( 'Optional', 'martial-arts-club-manager' ); ?>" />
			<span><em><?php esc_html_e( 'Your contact mobile number for club communications.', 'martial-arts-club-manager' ); ?></em></span>
		</p>

		<?php
	}

	/**
	 * Validate mobile number field
	 *
	 * @since 1.0.0
	 * @param WP_Error $errors Error object.
	 */
	public function validate_mobile_number( $errors ) {
		// Verify WooCommerce nonce (account details form).
		$nonce = isset( $_POST['save-account-details-nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['save-account-details-nonce'] ) )
			: '';
		if ( ! wp_verify_nonce( $nonce, 'save_account_details' ) ) {
			return;
		}

		// Validate mobile number if provided.
		$mobile = isset( $_POST['macm_mobile_number'] )
			? sanitize_text_field( wp_unslash( $_POST['macm_mobile_number'] ) )
			: '';

		if ( ! empty( $mobile ) ) {
			// Check if mobile contains only numbers, spaces, +, -, (, ).
			if ( ! preg_match( '/^[\d\s\+\-\(\)]+$/', $mobile ) ) {
				$errors->add(
					'mobile_number_error',
					__( 'Please enter a valid mobile number.', 'martial-arts-club-manager' )
				);
			}

			// Check length.
			if ( strlen( $mobile ) > 20 ) {
				$errors->add(
					'mobile_number_error',
					__( 'Mobile number must be less than 20 characters.', 'martial-arts-club-manager' )
				);
			}
		}
	}

	/**
	 * Save mobile number field
	 *
	 * @since 1.0.0
	 * @param int $user_id User ID.
	 */
	public function save_mobile_number( $user_id ) {
		// Verify WooCommerce nonce (account details form).
		$nonce = isset( $_POST['save-account-details-nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['save-account-details-nonce'] ) )
			: '';
		if ( ! wp_verify_nonce( $nonce, 'save_account_details' ) ) {
			return;
		}

		// Save mobile number.
		$mobile_number = isset( $_POST['macm_mobile_number'] )
			? sanitize_text_field( wp_unslash( $_POST['macm_mobile_number'] ) )
			: '';

		if ( ! empty( $mobile_number ) ) {
			update_user_meta( $user_id, 'macm_mobile_number', $mobile_number );
		} else {
			// Delete if empty.
			delete_user_meta( $user_id, 'macm_mobile_number' );
		}
	}

	/**
	 * Add custom menu items to My Account
	 *
	 * @since 1.0.0
	 * @param array $items Existing menu items.
	 * @return array Modified menu items.
	 */
	public function add_custom_menu_items( $items ) {
		// Get page IDs.
		$training_videos_page_id = get_option( 'macm_training_videos_page_id' );
		$members_area_page_id    = get_option( 'macm_members_area_page_id' );

		// Only add menu items if pages exist.
		$new_items = array();

		// Keep items before logout.
		foreach ( $items as $key => $label ) {
			if ( 'customer-logout' === $key ) {
				break;
			}
			$new_items[ $key ] = $label;
		}

		// Add custom menu items with unique keys.
		// These keys will be intercepted by custom_endpoint_urls() to return the actual page URLs.
		if ( $training_videos_page_id ) {
			$new_items['kcm-training-videos'] = __( 'Training Videos', 'martial-arts-club-manager' );
		}

		if ( $members_area_page_id ) {
			$new_items['kcm-members-area'] = __( 'Members Area', 'martial-arts-club-manager' );
		}

		// Add logout at the end.
		$new_items['customer-logout'] = $items['customer-logout'];

		return $new_items;
	}

	/**
	 * Override endpoint URLs to use direct page links instead
	 *
	 * @since 1.0.0
	 * @param string $url Default URL.
	 * @param string $endpoint Endpoint slug.
	 * @param string $value Endpoint value.
	 * @param string $permalink Permalink.
	 * @return string Modified URL.
	 */
	public function custom_endpoint_urls( $url, $endpoint, $value, $permalink ) {
		// Check if this is one of our custom endpoints.
		if ( 'kcm-training-videos' === $endpoint ) {
			$page_id = get_option( 'macm_training_videos_page_id' );
			if ( $page_id ) {
				return get_permalink( $page_id );
			}
		}

		if ( 'kcm-members-area' === $endpoint ) {
			$page_id = get_option( 'macm_members_area_page_id' );
			if ( $page_id ) {
				return get_permalink( $page_id );
			}
		}

		return $url;
	}
}
