<?php

function pop_pmproIsWpUserProfileScreen() {
	if ( ! is_admin() ) {
		return false;
	}

	global $pagenow;
	return in_array( (string) $pagenow, [ 'profile.php', 'user-edit.php' ], true );
}

function pop_pmproAddCheckoutInvoiceFields() {
	global $pmpro_countries;
	
	$pop_pmproInvoiceFields = [];
	$is_wp_user_profile = pop_pmproIsWpUserProfileScreen();
	$isPeppolContext = \WcElectronInvoice\Integrations::isPeppolContext();
	$disable_tax_code = \WcElectronInvoice\Admin\Settings\OptionPage::init()->getOptions( 'invoice_disable_cf' );
	$global_section_url = '#pop-global-invoice-fields';
	$global_section_msg = sprintf(
		'%s <a href="%s">%s</a>',
		'<span class="dashicons dashicons-info-outline" aria-hidden="true"></span> ' . esc_html__( 'This provider section is read-only in this screen.', WC_EL_INV_TEXTDOMAIN ),
		esc_url( $global_section_url ),
		esc_html__( 'Go to POP Invoice Fields section', WC_EL_INV_TEXTDOMAIN )
	);

	$fields = apply_filters( 'wc_el_inv-billing_fields', [] );

    // @todo migliorare questo codice capendo il motivo per cui il filtro non torna i fields
    if ( empty( $fields ) ) {
        $fields = include_once \WcElectronInvoice\Plugin::getPluginDirPath( '/inc/billingFields.php' );
    }

	$pop_mandatory_fields = [];
	if ( pmpro_is_checkout() ) {
		$current_billing_invoice_type = $_REQUEST['billing_invoice_type'] ?? '';
		$tax_code_required = ! (
			'on' === $disable_tax_code
			&& 'private' !== $current_billing_invoice_type
		);

			$pop_mandatory_fields = [
				'billing_invoice_type' => true,
				'billing_vat_number'   => in_array( $current_billing_invoice_type, [ 'company', 'freelance' ] ),
				'billing_tax_code'     => $tax_code_required,
				'billing_sdi_type'     => in_array( $current_billing_invoice_type, [ 'company', 'freelance' ] ),
				'billing_company'      => in_array( $current_billing_invoice_type, [ 'company' ] ),
			];
				if ($isPeppolContext) {
					unset($pop_mandatory_fields['billing_sdi_type']);
					unset($pop_mandatory_fields['billing_tax_code']);
				}

		global $pmpro_error_fields;

		foreach ( $pop_mandatory_fields as $field_name => $is_mandatory ) {
			if ( $is_mandatory && empty( $_REQUEST[ $field_name ] ) ) {
				$pmpro_error_fields[] = $field_name;
			}
		}
	}

	foreach ( $fields as $field_name => $field ) {
		if ($isPeppolContext && in_array($field_name, [ 'billing_sdi_type', 'billing_tax_code' ], true)) {
			continue;
		}

		if ( $field_name === 'billing_vat_number' ) {
			$required = false;
			if ( isset( $pop_mandatory_fields['billing_company'] ) ) {
				$required = $pop_mandatory_fields['billing_company'];
			}
			$pop_pmproInvoiceFields[] = new PMPro_Field (
				'billing_company',
				'text',
				array(
					'profile'        => true,
					'required'       => $is_wp_user_profile ? false : $required,
					'class'          => 'input',
					'label'          => __( 'Name of the company', WC_EL_INV_TEXTDOMAIN ),
					'memberslistcsv' => true,
					'attributes'     => $is_wp_user_profile ? [ 'disabled' => 'disabled' ] : [],
				)
			);
		}

		$field['hint']           = $field['description'];
		$field['profile']        = true;
		$field['memberslistcsv'] = true;
		$field['required']       = $is_wp_user_profile ? false : ( $pop_mandatory_fields[ $field_name ] ?? false );
		if ( $is_wp_user_profile ) {
			$field['attributes'] = [ 'disabled' => 'disabled' ];
		}

		$field['class'] = (array) $field['class'];
		$field['class'] = implode( ' ', array_filter( $field['class'] ) );

		if ( isset( $field['default'] ) ) {
			$field['default'] = apply_filters( "wc_el_inv-{$field_name}_default", $field['default'] );
		}

		// todo: during checkout, I sould change the required values to true depending on the billing_invoice_type (private, freelance, company).
		//  so javascript will only hide/show fields accordingly. and make validation.
		$pop_pmproInvoiceFields[] = new PMPro_Field(
			$field_name,
			$field['type'],
			$field
		);
	}

	// move billing_company field before billing_vat_number. use array_search and array_slice or similar.
	/*
	$pop_pmproInvoiceFields = array_merge(
		array_slice( $pop_pmproInvoiceFields, 0, array_search( 'billing_vat_number', array_keys( $pop_pmproInvoiceFields ) ), true ),
		array( 'billing_company' => $pop_pmproInvoiceFields['billing_company'] ),
		array_slice( $pop_pmproInvoiceFields, array_search( 'billing_vat_number', array_keys( $pop_pmproInvoiceFields ) ), null, true )
	);
	*/

	// admin only address fields
	if ( is_admin() ) {
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_baddress1", "text", array(
			"label"    => __( 'Billing Address 1', 'paid-memberships-pro' ),
			"size"     => 40,
			"profile"  => true,
			"required" => false,
		) );
		/*
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_baddress2", "text", array(
			"label"    => __( 'Billing Address 2', 'paid-memberships-pro' ),
			"size"     => 40,
			"profile"  => true,
			"required" => false
		) );
		*/
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_bcity", "text", array(
			"label"    => __( 'Billing City', 'paid-memberships-pro' ),
			"size"     => 40,
			"profile"  => true,
			"required" => false
		) );
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_bstate", "text", array(
			"label"    => __( 'Billing State', 'paid-memberships-pro' ),
			"size"     => 10,
			"profile"  => true,
			"required" => false
		) );
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_bzipcode", "text", array(
			"label"    => __( 'Billing Postal Code', 'paid-memberships-pro' ),
			"size"     => 10,
			"profile"  => true,
			"required" => false
		) );
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_bcountry", "select", array(
			"label"    => __( 'Billing Country', 'paid-memberships-pro' ),
			"profile"  => true,
			"required" => false,
			"options"  => array_merge( array( "" => "- choose one -" ), $pmpro_countries )
		) );
		$pop_pmproInvoiceFields[] = new PMPro_Field( "pmpro_bphone", "text", array(
			"label"    => __( 'Billing Phone', 'paid-memberships-pro' ),
			"size"     => 40,
			"profile"  => true,
			"required" => false
		) );
	}
	
	// define the field group
	$field_group = pmpro_get_field_group_by_name( 'pop-invoice-fields' );

	//add the fields into a new checkout_boxes area of the checkout page
	foreach ( $pop_pmproInvoiceFields as $field ) {
		// add to the field group
		pmpro_add_user_field( 'pop-invoice-fields', $field );
	}

	$field_group->label       = __( 'Invoice Fields', 'paid-memberships-pro' );
	$field_group->description = __( 'These fields are used by POP to collect billing information for the user\'s invoices.', WC_EL_INV_TEXTDOMAIN );
	if ( $is_wp_user_profile ) {
		$field_group->description .= ' ' . wp_kses_post( $global_section_msg );
	}
}

/**
 * Register fields for the admin member edit page.
 * On fields saving, the fields are loaded on admin_init, instead of a later hook.
 * So, we should hook the fields to the admin_init hook, before the pmpro_checkout_boxes_fields run.
 */
add_action( 'admin_init', 'pop_pmproAddCheckoutInvoiceFields', 1 );

/**
 * Register fields for the checkout page, just after the pmpro_checkout_boxes_fields run (at priority = 10)
 * Doing this later, we can show our fields after the pmpro_checkout_boxes_fields fields.
 */
add_action( 'pmpro_checkout_boxes', function () {
	// dont show checkout fields for free (one time) and free-forever (recurring levels).
	$level = pmpro_getLevelAtCheckout();
	if ( $level->initial_payment <= 0 && ( ! pmpro_isLevelRecurring( $level ) || $level->billing_amount <= 0 ) ) {
		return;
	}

	// wp_enqueue_script( 'pop-pmpro-invoice-fields', WC_EL_INV_URL . 'assets/js/pmpro-invoiceFields.js', [ 'jquery' ], WC_EL_INV_VERSION, true );
	pop_pmproAddCheckoutInvoiceFields();
}, 20 );

function pop_pmproShowInvoiceFieldsAtCheckout() {
	$field_group = pmpro_get_field_group_by_name( 'pop-invoice-fields' );
	$field_group->display( [
		'markup'               => 'card',
		'scope'                => 'checkout',
		'prefill_from_request' => true,
		'show_required'        => true,
	] );
}

add_action( 'pmpro_checkout_after_payment_information_fields', 'pop_pmproShowInvoiceFieldsAtCheckout' );
