<?php
/**
 * WooCommerce Registration Customization
 *
 * Handles custom registration fields and user role assignment
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/woocommerce
 * @since      1.0.0
 */

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

/**
 * Class MACM_Registration
 *
 * Customizes WooCommerce registration process with additional fields
 * and assigns default membership role to new users.
 *
 * @since 1.0.0
 */
class MACM_Registration {

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

	/**
	 * Register all hooks related to registration
	 *
	 * @since 1.0.0
	 */
	private function init_hooks() {
		// Add custom fields to registration form.
		add_action( 'woocommerce_register_form_start', array( $this, 'add_registration_fields' ) );

		// Validate custom fields.
		add_filter( 'woocommerce_registration_errors', array( $this, 'validate_registration_fields' ), 10, 3 );

		// Save custom fields.
		add_action( 'woocommerce_created_customer', array( $this, 'save_registration_fields' ), 10, 3 );
	}

	/**
	 * Add custom fields to WooCommerce registration form
	 *
	 * Adds first name, last name, and mobile number fields
	 *
	 * @since 1.0.0
	 */
	public function add_registration_fields() {
		// Get previously submitted values for repopulating after validation errors.
		// Verify WooCommerce register nonce if present (form resubmission after error).
		$nonce_valid = false;
		$nonce       = isset( $_POST['woocommerce-register-nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['woocommerce-register-nonce'] ) )
			: '';
		if ( ! empty( $nonce ) && wp_verify_nonce( $nonce, 'woocommerce-register' ) ) {
			$nonce_valid = true;
		}

		$first_name    = $nonce_valid && isset( $_POST['first_name'] ) ? sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) : '';
		$last_name     = $nonce_valid && isset( $_POST['last_name'] ) ? sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) : '';
		$mobile_number = $nonce_valid && isset( $_POST['mobile_number'] ) ? sanitize_text_field( wp_unslash( $_POST['mobile_number'] ) ) : '';
		?>
		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="reg_first_name"><?php esc_html_e( 'First Name', 'martial-arts-club-manager' ); ?>&nbsp;<span class="required">*</span></label>
			<input type="text"
					class="woocommerce-Input woocommerce-Input--text input-text"
					name="first_name"
					id="reg_first_name"
					value="<?php echo esc_attr( $first_name ); ?>"
					required />
		</p>

		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="reg_last_name"><?php esc_html_e( 'Last Name', 'martial-arts-club-manager' ); ?>&nbsp;<span class="required">*</span></label>
			<input type="text"
					class="woocommerce-Input woocommerce-Input--text input-text"
					name="last_name"
					id="reg_last_name"
					value="<?php echo esc_attr( $last_name ); ?>"
					required />
		</p>

		<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
			<label for="reg_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="mobile_number"
					id="reg_mobile_number"
					value="<?php echo esc_attr( $mobile_number ); ?>"
					placeholder="<?php esc_attr_e( 'Optional', 'martial-arts-club-manager' ); ?>" />
		</p>
		<?php
	}

	/**
	 * Validate custom registration fields
	 *
	 * @since 1.0.0
	 * @param WP_Error $errors      Error object.
	 * @param string   $username    Username.
	 * @param string   $email       Email address.
	 * @return WP_Error
	 */
	public function validate_registration_fields( $errors, $username, $email ) {
		// Verify WooCommerce registration nonce.
		$nonce = isset( $_POST['woocommerce-register-nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['woocommerce-register-nonce'] ) )
			: '';
		if ( ! wp_verify_nonce( $nonce, 'woocommerce-register' ) ) {
			return $errors;
		}

		// Sanitize and validate first name.
		$first_name = isset( $_POST['first_name'] ) ? sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) : '';

		if ( empty( $first_name ) ) {
			$errors->add(
				'first_name_error',
				__( 'First name is required.', 'martial-arts-club-manager' )
			);
		} elseif ( strlen( $first_name ) > 50 ) {
			$errors->add(
				'first_name_error',
				__( 'First name must be less than 50 characters.', 'martial-arts-club-manager' )
			);
		}

		// Sanitize and validate last name.
		$last_name = isset( $_POST['last_name'] ) ? sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) : '';

		if ( empty( $last_name ) ) {
			$errors->add(
				'last_name_error',
				__( 'Last name is required.', 'martial-arts-club-manager' )
			);
		} elseif ( strlen( $last_name ) > 50 ) {
			$errors->add(
				'last_name_error',
				__( 'Last name must be less than 50 characters.', 'martial-arts-club-manager' )
			);
		}

		// Validate mobile number if provided.
		$mobile = isset( $_POST['mobile_number'] ) ? sanitize_text_field( wp_unslash( $_POST['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' )
				);
			}
		}

		return $errors;
	}

	/**
	 * Save custom registration fields to user meta
	 *
	 * Also assigns the default basic member role to new users
	 *
	 * @since 1.0.0
	 * @param int    $customer_id Customer ID.
	 * @param array  $new_customer_data Customer data.
	 * @param string $password_generated Whether password was generated.
	 */
	public function save_registration_fields( $customer_id, $new_customer_data, $password_generated ) {
		// Verify WooCommerce registration nonce.
		$nonce = isset( $_POST['woocommerce-register-nonce'] )
			? sanitize_text_field( wp_unslash( $_POST['woocommerce-register-nonce'] ) )
			: '';
		if ( ! wp_verify_nonce( $nonce, 'woocommerce-register' ) ) {
			return;
		}

		// Save first name.
		$first_name = isset( $_POST['first_name'] ) ? sanitize_text_field( wp_unslash( $_POST['first_name'] ) ) : '';
		if ( ! empty( $first_name ) ) {
			update_user_meta( $customer_id, 'first_name', $first_name );
		}

		// Save last name.
		$last_name = isset( $_POST['last_name'] ) ? sanitize_text_field( wp_unslash( $_POST['last_name'] ) ) : '';
		if ( ! empty( $last_name ) ) {
			update_user_meta( $customer_id, 'last_name', $last_name );
		}

		// Save mobile number if provided.
		$mobile_number = isset( $_POST['mobile_number'] ) ? sanitize_text_field( wp_unslash( $_POST['mobile_number'] ) ) : '';
		if ( ! empty( $mobile_number ) ) {
			update_user_meta( $customer_id, 'macm_mobile_number', $mobile_number );
		}

		// Assign default role (basic member).
		$user = new WP_User( $customer_id );

		// Remove default customer role.
		$user->remove_role( 'customer' );

		// Add basic member role.
		$user->add_role( 'macm_basic_member' );

		// Also keep customer role for WooCommerce compatibility.
		$user->add_role( 'customer' );

		// Registration completed successfully.
	}
}
