<?php

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

/**
 * BWFAN_Birthday class
 */
class BWFAN_Birthday {

	private static $ins = null;

	public function __construct() {
		add_filter( 'bwfan_admin_settings_schema', [ $this, 'add_admin_setting_schema' ] );
		add_filter( 'bwfan_default_global_settings', [ $this, 'add_default_birthday_label' ] );

		/** placing birthday field on checkout form **/
		add_action( 'woocommerce_before_checkout_form', [ $this, 'bwfan_placing_birthday_field' ] );
		add_action( 'woocommerce_checkout_order_processed', [ $this, 'update_order_meta' ], 99 );

		/** handling of birthday field on wc my account form */
		add_action( 'woocommerce_edit_account_form', [ $this, 'add_birthday_field_on_wc_my_account' ] );
		add_action( 'woocommerce_save_account_details', [ $this, 'update_birthday_details_user_meta' ] );

		/** handling birthday field on my profile page */
		add_action( 'show_user_profile', [ $this, 'show_birthday_field_on_my_profile' ], 15 );
		add_action( 'edit_user_profile', [ $this, 'show_birthday_field_on_my_profile' ], 15 );
		add_action( 'personal_options_update', array( $this, 'update_birthday_details_user_meta' ) );
		add_action( 'edit_user_profile_update', array( $this, 'update_birthday_details_user_meta' ) );

		/** showing fields on funnelkit checkout page **/
		add_filter( 'wfacp_advanced_fields', [ $this, 'attach_dob_field_checkout_form' ] );
		add_filter( 'wfacp_html_fields_bwfan_birthday_date', '__return_false' );
		add_action( 'process_wfacp_html', [ $this, 'showing_birthday_field_on_aerocheckout_page' ], 10, 3 );
		add_filter( 'wfacp_widget_fields_classes', [ $this, 'add_field_width_option' ], 10, 3 );

		/** birthday field functionality on funnelkit optin form */
		add_action( 'plugins_loaded', array( $this, 'load_optin_form_birthday_field' ) );
		add_filter( 'wffn_get_optin_default_fields', [ $this, 'add_birthday_field_optin_form' ] );
		add_action( 'wffn_optin_form_submit', array( $this, 'optin_form_submit' ), 999, 2 );

		/** css */
		add_action( 'wp_head', array( $this, 'bwfan_add_compatible_css_for_themes' ) );

		/** DOB field on thank you page */
		add_shortcode( 'bwfan_thank_you_birthday_collection_form', array( $this, 'birthday_field_on_thankyou' ) );
		add_action( 'wp_ajax_nopriv_save_birthday_on_thankyou', array( $this, 'save_birthday_on_thankyou' ) );
		add_action( 'wp_ajax_save_birthday_on_thankyou', array( $this, 'save_birthday_on_thankyou' ) );

		/** Validate birthday if field is required */
		add_action( 'woocommerce_after_checkout_validation', array( $this, 'validate_birthday' ), 999, 2 );

		/** Display dob field on single order in admin */
		add_filter( 'wfacp_admin_order_field', [ $this, 'display_dob_wfacp_field' ], 10, 2 );
	}

	/**
	 * Birthday field on aerocheckout frontend
	 *
	 * @param $field
	 * @param $key
	 * @param $args
	 *
	 * @return void
	 */
	public function showing_birthday_field_on_aerocheckout_page( $field, $key, $args ) {
		if ( 'bwfan_birthday_date' !== $key ) {
			return;
		}

		/** wfacp-modern-label */
		$label_position = wfacp_template()->get_field_label_position();
		$wfacp_id       = WFACP_Common::get_id();

		$birthday_label    = isset( $args['label'] ) ? $args['label'] : '';
		$placeholder_label = isset( $args['placeholder'] ) && ! empty( $args['placeholder'] ) ? $args['placeholder'] : '';
		$class             = isset( $args['class'] ) && ! empty( $args['class'] ) ? implode( ' ', $args['class'] ) : '';
		$label_class       = isset( $args['label_class'] ) && ! empty( $args['label_class'] ) ? implode( ' ', $args['label_class'] ) : '';
		$input_class       = isset( $args['input_class'] ) && ! empty( $args['input_class'] ) ? implode( ' ', $args['input_class'] ) : '';
		$required          = isset( $args['required'] ) ? $args['required'] : false;

		echo '<div class="wfacp_bwfan_birthday_date_field" style="display:inline;">';
		include __DIR__ . '/template/birthday-field.php';
		echo '</div>';
	}

	/**
	 *  on the basis of placement hooking the field
	 */
	public function bwfan_placing_birthday_field() {
		if ( ! $this->is_native_checkout() ) {
			return;
		}

		$hook            = false;
		$global_settings = BWFAN_Common::get_global_settings();

		if ( ! isset( $global_settings['bwfan_dob_field'] ) || empty( $global_settings['bwfan_dob_field'] ) ) {
			return;
		}

		$field_position = isset( $global_settings['bwfan_birthday_field_position'] ) && ! empty( $global_settings['bwfan_birthday_field_position'] ) ? $global_settings['bwfan_birthday_field_position'] : 'after_billing_details';
		switch ( $field_position ) {
			case 'after_order_notes':
				$hook = 'woocommerce_after_order_notes';
				break;
			case 'before_order_notes':
				$hook = 'woocommerce_before_order_notes';
				break;
			case 'after_billing_details':
				if ( ! is_user_logged_in() && WC()->checkout()->is_registration_enabled() ) {
					$hook = 'woocommerce_after_checkout_registration_form';
				} else {
					$hook = 'woocommerce_after_checkout_billing_form';
				}
				break;
		}

		add_action( $hook, [ $this, 'add_dob_field_checkout_form' ] );
	}

	/**
	 * Checks if native WC checkout
	 *
	 * @return bool
	 */
	public function is_native_checkout() {
		global $post;
		if ( is_null( $post ) ) {
			return false;
		}

		if ( $post->post_status !== 'publish' || ( class_exists( 'WFACP_Common' ) && $post->post_type === WFACP_Common::get_post_type_slug() ) || 0 !== did_action( 'wfacp_after_checkout_page_found' ) ) {
			return false;
		}

		$meta_exist = get_post_meta( $post->ID, '_is_aero_checkout_page', true );

		return empty( $meta_exist );
	}

	/**
	 * Display date of birth field in FunnelKit Checkout
	 *
	 * @return void
	 */
	public function add_dob_field_checkout_form() {
		$birthday_label = '';
		$class          = '';
		$label_class    = '';
		$input_class    = '';
		$label_position = '';
		$wfacp_id       = 0;

		include __DIR__ . '/template/birthday-field.php';
	}

	/**
	 * Add date of birth field in FunnelKit Checkout admin
	 *
	 * @param $fields
	 *
	 * @return mixed
	 */
	public function attach_dob_field_checkout_form( $fields ) {
		$fields['bwfan_birthday_date'] = [
			'type'                => 'wfacp_html',
			'class'               => [ 'bwfan_birthday_date' ],
			'id'                  => 'bwfan_birthday_date',
			'field_type'          => 'advanced',
			'label'               => __( 'Date of Birth', 'wp-marketing-automations-pro' ),
			'created_by'          => 'bwfanbirthday',
			'is_wfacp_field'      => true,
			'required'            => false,
			'show_required_field' => true
		];

		return $fields;
	}

	/** updating birthday field in order meta **/
	/**
	 * @param $order_id
	 *
	 * @return void
	 */
	public function update_order_meta( $order_id ) {
		$birthday_date = filter_input( INPUT_POST, 'bwfan_birthday_date' );
		if ( empty( $birthday_date ) ) {
			return;
		}

		$birthday_date = BWFCRM_Contact::get_date_value( $birthday_date );
		$order         = wc_get_order( $order_id );

		$order->update_meta_data( 'bwfan_birthday_date', $birthday_date );
		$order->save();

		$billing_email = $order->get_billing_email();
		$contact       = new BWFCRM_Contact( $billing_email );
		if ( ! $contact->is_contact_exists() ) {
			return;
		}

		$contact->set_field_by_slug( 'dob', $birthday_date );
		$contact->save_fields();

		$user_id = $order->get_user_id() ? $order->get_user_id() : $contact->contact->get_wpid();
		if ( empty( $user_id ) ) {
			return;
		}

		update_user_meta( $user_id, 'bwfan_birthday_date', $birthday_date );
	}

	/**
	 * @param $optin_page_id
	 * @param $posted_data
	 *
	 * @return void
	 */
	public function optin_form_submit( $optin_page_id, $posted_data ) {
		/** Birthday field is not present */
		if ( ! isset( $posted_data['optin_birthday'] ) || empty( $posted_data['optin_birthday'] ) ) {
			return;
		}

		$contact = isset( $posted_data['cid'] ) ? $posted_data['cid'] : ( isset( $posted_data['optin_email'] ) ? $posted_data['optin_email'] : '' );
		if ( empty( $contact ) ) {
			return;
		}

		$bwfcrm_contact = new BWFCRM_Contact( $contact );
		if ( ! $bwfcrm_contact->is_contact_exists() ) {
			return;
		}

		$birthday_date = BWFCRM_Contact::get_date_value( $posted_data['optin_birthday'] );

		$bwfcrm_contact->set_field_by_slug( 'dob', $birthday_date );
		$bwfcrm_contact->save_fields();

		if ( empty( $bwfcrm_contact->contact->get_wpid() ) ) {
			return;
		}

		update_user_meta( $bwfcrm_contact->contact->get_wpid(), 'bwfan_birthday_date', $birthday_date );
	}

	/**
	 * Add date of birth field in FunnelKit Optin
	 *
	 * @return void
	 */
	public function load_optin_form_birthday_field() {
		if ( ! class_exists( 'WFFN_Optin_Form_Field' ) ) {
			return;
		}

		require_once( __DIR__ . '/template/birthday-optin-field.php' ); //phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable
	}

	/**
	 * add css for both native and funnel checkout
	 * @return void
	 */
	public function bwfan_add_compatible_css_for_themes() {
		if ( ! bwfan_is_woocommerce_active() || ! is_checkout() ) {
			return;
		}

		// loading css only for astra theme
		if ( defined( 'ASTRA_THEME_VERSION' ) ) {
			?>
            <style>
                .theme-astra input[type=date] {
                    padding: 0.75rem;
                    border: 1px solid var(--ast-border-color);
                }

                body #wfacp-e-form .wfacp_main_form.woocommerce input[type=date] {
                    width: 100%;
                }
            </style>
			<?php
		}
	}

	public function add_birthday_field_optin_form( $output ) {
		$output['basic']['wfop_optin_birthday'] = [
			'label'       => __( 'Date of Birth', 'wp-marketing-automations-pro' ),
			'type'        => 'optin_birthday',
			'required'    => false,
			'class'       => array( 'form-row-wide' ),
			'priority'    => 10,
			'id'          => 'wfop_optin_birthday',
			'placeholder' => 'Birthday',
			'width'       => 'wffn-sm-100'
		];

		return $output;
	}

	/**
	 * @param $settings_schema
	 *
	 * @return array|mixed
	 */
	public function add_admin_setting_schema( $settings_schema ) {
		$birthdate_text  = __( "Birthdate", 'wp-marketing-automations-pro' );
		$Submit_btn_text = __( "Save", 'wp-marketing-automations-pro' );
		$birthday_field  = array(
			array(
				'id'          => 'bwfan_dob_field_funnelkit_checkout',
				'type'        => 'text',
				'class'       => 'bwfan_dob_field ',
				'required'    => false,
				'show'        => false,
				'toggler'     => array(),
				'wrap_before' => "<br/><h3>" . __( 'FunnelKit Checkout', 'wp-marketing-automations-pro' ) . "</h3><p><i>" . __( 'FunnelKit Checkout provides Date of Birth field in its field editor. Go to Checkout > Fields and drag the Date of Birth field.', 'wp-marketing-automations-pro' ) . "</i></p>",
			),
			array(
				'id'          => 'bwfan_dob_field_funnelkit_checkout',
				'type'        => 'text',
				'class'       => 'bwfan_dob_field ',
				'required'    => false,
				'show'        => false,
				'toggler'     => array(),
				'wrap_before' => "<br/><h3>" . __( 'FunnelKit Optin', 'wp-marketing-automations-pro' ) . "</h3><p><i>" . __( 'FunnelKit Optin provides Date of Birth field in its field editor. Go to Optin > Fields and drag the Date of Birth field.', 'wp-marketing-automations-pro' ) . "</i></p>",
			),
			array(
				'id'            => 'bwfan_dob_field',
				'label'         => __( 'Enable Field', 'wp-marketing-automations-pro' ),
				'type'          => 'checkbox',
				'class'         => 'bwfan_dob_field ',
				'checkboxlabel' => __( "Enable Date of Birth field on WooCommerce checkout", 'wp-marketing-automations-pro' ),
				'required'      => false,
				'show'          => true,
				'wrap_before'   => '<br/><h3>' . __( 'WooCommerce Checkout', 'wp-marketing-automations-pro' ) . '</h3>',
				'toggler'       => array(),
			),
			array(
				'id'          => 'bwfan_birthday_field_label',
				'label'       => __( 'Field Label', 'wp-marketing-automations-pro' ),
				'type'        => 'text',
				'class'       => 'bwfan_birthday_field_label',
				'required'    => false,
				'placeholder' => __( 'Enter field\'s label', 'wp-marketing-automations-pro' ),
				'show'        => true,
				'toggler'     => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			),
			array(
				'id'            => 'bwfan_dob_required',
				'label'         => __( 'Required', 'wp-marketing-automations-pro' ),
				'type'          => 'checkbox',
				'class'         => 'bwfan_dob_required ',
				'checkboxlabel' => __( "Make date of birth field required", 'wp-marketing-automations-pro' ),
				'required'      => false,
				'show'          => true,
				'toggler'       => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			),
			array(
				'id'          => 'bwfan_birthday_field_position',
				'label'       => __( 'Field Position', 'wp-marketing-automations-pro' ),
				'type'        => 'select',
				'placeholder' => 'Select Position',
				'multiple'    => false,
				'class'       => 'bwfan_birthday_field_position',
				'options'     => array(
					array(
						'value' => 'after_billing_details',
						'label' => __( 'After Billing Details', 'wp-marketing-automations-pro' ),
					),
					array(
						'value' => 'before_order_notes',
						'label' => __( 'Before Order Notes', 'wp-marketing-automations-pro' ),
					),
					array(
						'value' => 'after_order_notes',
						'label' => __( 'After Order Notes', 'wp-marketing-automations-pro' ),
					),
				),
				'required'    => false,
				'show'        => true,
				'toggler'     => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			),
			array(
				'id'            => 'bwfan_dob_field_my_account',
				'label'         => __( 'Enable Field', 'wp-marketing-automations-pro' ),
				'type'          => 'checkbox',
				'class'         => 'bwfan_dob_field ',
				'checkboxlabel' => __( "Enable Date of Birth field on My Account", 'wp-marketing-automations-pro' ),
				'required'      => false,
				'show'          => true,
				'toggler'       => array(),
				'wrap_before'   => '<br/><h3>' . __( 'WooCommerce My Account', 'wp-marketing-automations-pro' ) . '</h3>',
			),
			array(
				'id'          => 'bwfan_my_account_birthday_field_label',
				'label'       => __( 'Field Label', 'wp-marketing-automations-pro' ),
				'type'        => 'text',
				'class'       => 'bwfan_birthday_field_label',
				'required'    => false,
				'placeholder' => __( 'Enter field\'s label', 'wp-marketing-automations-pro' ),
				'show'        => true,
				'toggler'     => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field_my_account',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			),
			array(
				'id'            => 'bwfan_dob_field_thankyou',
				'label'         => __( 'Enable Shortcode', 'wp-marketing-automations-pro' ),
				'type'          => 'checkbox',
				'class'         => 'bwfan_dob_field ',
				'checkboxlabel' => __( "Enable Date of Birth collection form shortcode on the Thank you page", 'wp-marketing-automations-pro' ),
				'required'      => false,
				'show'          => true,
				'toggler'       => array(),
				'wrap_before'   => '<br/><h3>' . __( 'WooCommerce Thank You', 'wp-marketing-automations-pro' ) . '</h3>',
			),
			array(
				'id'        => 'bwfan_dob_field_shortcode',
				'type'      => 'copier',
				'hint'      => __( "Place this shortcode on the Thank you page to show the form. Will work only on the thank you page.", 'wp-marketing-automations-pro' ),
				'required'  => false,
				'copy_text' => '[bwfan_thank_you_birthday_collection_form label="' . $birthdate_text . '" button="' . $Submit_btn_text . '"]',
				'toggler'   => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field_thankyou',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			),
			array(
				'id'          => 'bwfan_dob_ty_success_msg',
				'label'       => __( 'Success Message', 'wp-marketing-automations-pro' ),
				'type'        => 'text',
				'class'       => 'bwfan_dob_ty_success_msg',
				'required'    => false,
				'placeholder' => __( 'Success message', 'wp-marketing-automations-pro' ),
				'show'        => true,
				'toggler'     => array(
					'fields'   => array(
						array(
							'id'    => 'bwfan_dob_field_thankyou',
							'value' => true,
						),
					),
					'relation' => 'OR',
				),
			)
		);

		$birthday_reminder_fields = array(
			'key'     => 'birthday_reminder',
			'label'   => __( 'Birthday Reminder', 'wp-marketing-automations-pro' ),
			'heading' => __( 'Date Of Birth Field Settings', 'wp-marketing-automations-pro' ),
			'fields'  => $birthday_field
		);

		// fetching the position of advanced field in the tabs array
		$keys  = array_column( $settings_schema[0]['tabs'], 'key' );
		$index = array_search( 'advanced', $keys );
		$pos   = false === $index ? count( $settings_schema[0]['tabs'] ) : $index;

		// pushing birthday field before advanced field
		$new_ordered_tabs = array_merge( array_slice( $settings_schema[0]['tabs'], 0, $pos ), array( $birthday_reminder_fields ), array_slice( $settings_schema[0]['tabs'], $pos ) );

		// overriding the tabs array with new array
		$settings_schema[0]['tabs'] = $new_ordered_tabs;

		return $settings_schema;
	}

	/**
	 * Provide default values to the new settings
	 *
	 * @param $global_settings
	 *
	 * @return mixed
	 */
	public function add_default_birthday_label( $global_settings ) {
		$global_settings['bwfan_birthday_field_label']            = __( 'Date of Birth', 'wp-marketing-automations-pro' );
		$global_settings['bwfan_my_account_birthday_field_label'] = __( 'Date of Birth', 'wp-marketing-automations-pro' );
		$global_settings['bwfan_dob_ty_success_msg']              = __( 'Thank you for submitting your Birthdate!', 'wp-marketing-automations-pro' );

		return $global_settings;
	}

	/**
	 * showing birthday field on wc my account page
	 *
	 * @return void
	 */
	public function add_birthday_field_on_wc_my_account() {
		$global_settings = BWFAN_Common::get_global_settings();
		/** If dob field is not enable on my-account page */
		if ( ! isset( $global_settings['bwfan_dob_field_my_account'] ) || empty( $global_settings['bwfan_dob_field_my_account'] ) ) {
			return;
		}

		$birthday_label = isset( $global_settings['bwfan_my_account_birthday_field_label'] ) ? $global_settings['bwfan_my_account_birthday_field_label'] : 'Date of Birth';
		$class          = '';
		$label_class    = '';
		$input_class    = '';
		$label_position = '';

		echo '<div class="wfacp_bwfan_birthday_field_wrap">';
		include __DIR__ . '/template/birthday-field.php';
		echo '</div>';
	}

	/**
	 * updating birthday in user meta and in autonami contact
	 *
	 * @param $user_id
	 *
	 * @return void
	 */
	public function update_birthday_details_user_meta( $user_id ) {
		$bwfan_birthday = filter_input( INPUT_POST, 'bwfan_birthday_date' );
		if ( empty( $bwfan_birthday ) ) {
			return;
		}

		$bwfan_birthday = BWFCRM_Contact::get_date_value( $bwfan_birthday );

		update_user_meta( $user_id, 'bwfan_birthday_date', $bwfan_birthday );

		$email = filter_input( INPUT_POST, 'account_email' );
		if ( empty( $email ) ) {
			// this is for edit profile
			$email = filter_input( INPUT_POST, 'email' );
		}

		$contact = new BWFCRM_Contact( $email );

		if ( ! $contact->is_contact_exists() ) {
			return;
		}

		$contact->set_field_by_slug( 'dob', $bwfan_birthday );
		$contact->save_fields();
	}

	/**
	 * showing birthday field on my account
	 *
	 * @param $user
	 *
	 * @return void
	 */
	public function show_birthday_field_on_my_profile( $user ) {
		$global_settings = BWFAN_Common::get_global_settings();

		if ( ! isset( $global_settings['bwfan_dob_field'] ) || empty( $global_settings['bwfan_dob_field'] ) ) {
			return;
		}

		$birthday_label = ! empty( $global_settings['bwfan_birthday_field_label'] ) ? $global_settings['bwfan_birthday_field_label'] : __( 'Date of Birth', 'wp-marketing-automations-pro' );

		$contact = new BWFCRM_Contact( $user->user_email );
		/** Get DOB from contact */
		$dob = $contact->get_field_by_slug( 'dob' );
		/** Get Dob from user meta */
		$user_dob = get_user_meta( $user->ID, 'bwfan_birthday_date', true );
		$user_dob = empty( $dob ) ? $user_dob : $dob;

		$max = current_time( 'Y-m-d', 1 );
		$min = BWFAN_PRO_Common::get_birthday_min_value();
		?>
        <table class="form-table">
            <tr>
                <th><?php esc_html_e( $birthday_label ); ?></label></th>
                <td>
                    <input type="date" name="bwfan_birthday_date" id="bwfan_birthday_date" value="<?php esc_attr_e( $user_dob ); ?>" class="regular-text" max="<?php echo $max; ?>" <?php echo $min; ?>/>
                </td>
            </tr>
        </table>
		<?php
	}

	/**
	 * @param $attr
	 *
	 * @return false|string|void
	 */
	public function birthday_field_on_thankyou( $attr ) {
		$global_settings = BWFAN_Common::get_global_settings();
		if ( ! isset( $global_settings['bwfan_dob_field_thankyou'] ) || empty( $global_settings['bwfan_dob_field_thankyou'] ) ) {
			return;
		}

		$label  = isset( $attr['label'] ) && ! empty( $attr['label'] ) ? trim( $attr['label'] ) : '';
		$button = isset( $attr['button'] ) ? $attr['button'] : "Save";

		$order_id = filter_input( INPUT_GET, 'order_id' );

		/** matching of order and its key */
		$order = wc_get_order( $order_id );
		if ( empty( $order_id ) || ! $order instanceof WC_Order ) {
			return;
		}
		$key       = $order->get_order_key();
		$order_key = filter_input( INPUT_GET, 'key' );
		if ( empty( $order_key ) || ( $key !== strval( $order_key ) ) ) {
			return;
		}

		$cid     = $order->get_meta( '_woofunnel_cid' );
		$contact = new BWFCRM_Contact( $cid );

		$dob_value = ( $contact instanceof BWFCRM_Contact && $contact->is_contact_exists() ) ? $contact->get_field_by_slug( 'dob' ) : '';

		$max = current_time( 'Y-m-d', 1 );
		$min = BWFAN_PRO_Common::get_birthday_min_value();
		ob_start();
		?>
        <div class="bwfan-tyb-wrap">
			<?php echo $label ? '<div class="bwfan-tyb-label"><label>' . $label . '</label></div>' : ''; ?>
            <div class="bwfan-tyb-field">
                <input type="date" name="bwfan_ty_field_dob" id="bwfan-tyb-field" value="<?php esc_attr_e( $dob_value ) ?>" placeholder="<?php echo $label; ?>" class="regular-text" max="<?php echo $max; ?>" <?php echo $min; ?> />
                <span class="bwfan-tyb-btn button-primary button" id="bwfan-tyb-save-btn"><?php echo esc_attr( $button ); ?></span>
            </div>
            <input type="hidden" id="bwfan-order-id" name="bwfan_order_id" value="<?php echo $order_id; ?>">
            <input type="hidden" id="bwfan-cid" name="bwfan_cid" value="<?php echo $cid; ?>">
            <input type="hidden" id="bwfan-tyb-nonce" name="bwfan_tyb_nonce" value="<?php echo wp_create_nonce( 'bwfan_tyb_nonce' ); ?>">
            <div class="bwfan-tyb-response"><span class="bwfan-tyb-msg"></span></div>
        </div>
		<?php
		return ob_get_clean();
	}

	/**
	 * Ajax callback for save birthday
	 *
	 * @return void
	 */
	public function save_birthday_on_thankyou() {
		BWFAN_PRO_Common::nocache_headers();
		$global_settings = BWFAN_Common::get_global_settings();

		$result = [
			'status' => 2,
			'msg'    => __( "Some error occurred.", "wp-marketing-automations-pro" ),
		];

		$nonce = filter_input( INPUT_POST, 'nonce' );
		if ( empty( $nonce ) || ! wp_verify_nonce( $nonce, 'bwfan_tyb_nonce' ) ) {
			$result['msg'] = __( "Security verification failed.", "wp-marketing-automations-pro" );
			wp_send_json( $result );
		}

		if ( ! isset( $global_settings['bwfan_dob_field_thankyou'] ) || empty( $global_settings['bwfan_dob_field_thankyou'] ) ) {
			$result['msg'] = __( "Shortcode settings are not enabled.", "wp-marketing-automations-pro" );
			wp_send_json( $result );
		}

		$birthday = filter_input( INPUT_POST, 'birthday' );
		if ( empty( $birthday ) ) {
			$result['msg'] = __( "Date of birth is required.", "wp-marketing-automations-pro" );
			wp_send_json( $result );
		}

		$cid      = filter_input( INPUT_POST, 'cid' );
		$order_id = filter_input( INPUT_POST, 'order_id' );

		if ( empty( $order_id ) && empty( $cid ) ) {
			$result['msg'] = __( "Required data is missing.", "wp-marketing-automations-pro" );
			wp_send_json( $result );
		}

		$success_msg = isset( $global_settings['bwfan_dob_ty_success_msg'] ) ? $global_settings['bwfan_dob_ty_success_msg'] : '';

		if ( intval( $cid ) > 0 ) {
			$contact = $this->save_content_dob( $cid, $birthday, 1 );
			if ( true === $contact ) {
				$result['status'] = 1;
				$result['msg']    = $success_msg;
				wp_send_json( $result );
			}
		}

		if ( intval( $order_id ) > 0 ) {
			$contact = $this->save_content_dob( $order_id, $birthday, 2 );
			if ( true === $contact ) {
				$result['status'] = 1;
				$result['msg']    = $success_msg;
				wp_send_json( $result );
			}
		}

		wp_send_json( $result );
	}

	/**
	 * @param $value - cid, order id, order obj
	 * @param $dob
	 * @param $type - 1 cid, 2 order id, 3 order obj
	 *
	 * @return bool
	 */
	protected function save_content_dob( $value, $dob = '', $type = '1' ) {
		if ( empty( $value ) && empty( $type ) && empty( $dob ) ) {
			return false;
		}

		/** Type 1 - cid */
		if ( 1 === intval( $type ) ) {
			$crm_contact = new BWFCRM_Contact( $value );
			if ( empty( $crm_contact ) || ! $crm_contact->is_contact_exists() ) {
				return false;
			}

			return $this->save_dob( $crm_contact, $dob );
		}

		/** Type 2 - order id */
		if ( 2 === intval( $type ) ) {
			$order = wc_get_order( $value );
			if ( ! $order instanceof WC_Order ) {
				return false;
			}

			$cid = $order->get_meta( '_woofunnel_cid' );
			if ( empty( $cid ) ) {
				return $this->save_content_dob( $order, $dob, 3 );
			}

			return $this->save_content_dob( $cid, $dob, 1 );
		}

		/**
		 * Type 3 - order obj
		 * Order doesn't contain the cid
		 */
		if ( 3 === intval( $type ) ) {
			/** @var WC_Order $value */
			$email = $value->get_billing_email();
			if ( empty( $email ) || ! is_email( $email ) ) {
				return false;
			}
			$ins = WooFunnels_DB_Updater::get_instance();
			$ins->woofunnels_wc_order_create_contact( $value->get_id(), [], $value );

			$order = wc_get_order( $value->get_id() );
			if ( ! $order instanceof WC_Order ) {
				return false;
			}

			$cid = $order->get_meta( '_woofunnel_cid' );
			if ( empty( $cid ) ) {
				return false;
			}

			return $this->save_content_dob( $cid, $dob, 1 );
		}

		return false;
	}

	/**
	 * @param $crm_contact BWFCRM_Contact
	 * @param $dob
	 *
	 * @return bool
	 */
	protected function save_dob( $crm_contact, $dob ) {
		try {
			$crm_contact->set_field_by_slug( 'dob', $dob );
			$crm_contact->save_fields();
		} catch ( Error $e ) {
			return false;
		}

		return true;
	}

	public static function get_instance() {
		if ( is_null( self::$ins ) ) {
			self::$ins = new self();
		}

		return self::$ins;
	}

	/**
	 * Validate Birthday field if required on wc checkout
	 *
	 * @param $fields
	 * @param $errors
	 *
	 * @return void
	 */
	public function validate_birthday( $fields, $errors ) {
		$global_settings = BWFAN_Common::get_global_settings();
		$required        = isset( $global_settings['bwfan_dob_required'] ) ? $global_settings['bwfan_dob_required'] : false;
		if ( empty( $required ) ) {
			return;
		}

		/** Check if funnelkit checkout */
		$wfacp_id = class_exists( 'WFACP_Common' ) ? WFACP_Common::get_id() : 0;
		if ( $wfacp_id > 0 ) {
			return;
		}

		$birthday_label = ! empty( $global_settings['bwfan_birthday_field_label'] ) ? $global_settings['bwfan_birthday_field_label'] : __( 'Date of Birth', 'wp-marketing-automations-pro' );
		if ( empty( filter_input( INPUT_POST, 'bwfan_birthday_date' ) ) ) {
			$errors->add( 'validation', '<strong>' . $birthday_label . '</strong> is a required field.' );
		}
	}

	/**
	 * Add field width options in page editors for FK checkout
	 *
	 * @param $options
	 * @param $field
	 * @param $class_list
	 *
	 * @return mixed
	 */
	public function add_field_width_option( $options, $field, $class_list ) {
		if ( ! isset( $field['id'] ) || 'bwfan_birthday_date' !== $field['id'] ) {
			return $options;
		}

		return $class_list;
	}

	/**
	 * @param $field
	 * @param $field_key
	 *
	 * @return mixed
	 */
	public function display_dob_wfacp_field( $field, $field_key ) {
		if ( 'wfacp_bwfan_birthday_date' !== $field_key ) {
			return $field;
		}

		$order = wc_get_order( intval( filter_input( INPUT_GET, 'id' ) ) );
		if ( ! $order instanceof WC_Order ) {
			return $field;
		}

		$wfacp_id        = wfacp_get_order_meta( $order, '_wfacp_post_id' );
		$c_fields        = WFACP_Common::get_checkout_fields( $wfacp_id );
		$advanced_fields = isset( $c_fields['advanced'] ) ? $c_fields['advanced'] : [];
		if ( empty( $advanced_fields ) || ! isset( $advanced_fields['bwfan_birthday_date'] ) ) {
			return $field;
		}

		$field['type'] = "text";

		return $field;
	}
}

BWFAN_Birthday::get_instance();
