<?php

function wiaas_db_update_add_organization_info_ui_fields() {

    $ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-organization-info.json' );

    $ui_json = json_decode( $ui_json, true );

	_wiaas_import_field_group($ui_json);
}

function wiaas_db_update_add_user_organization_ui_fields() {

    $ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-user-organization.json' );

    $ui_json = json_decode( $ui_json, true );

	_wiaas_import_field_group($ui_json);
}

function wiaas_db_update_add_reference_ui_field() {

	$ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-reference.json' );

	$ui_json = json_decode( $ui_json, true );

	_wiaas_import_field_group($ui_json);
}

function wiaas_db_update_add_general_ui_fields() {

	$ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-general.json' );

	$ui_json = json_decode( $ui_json, true );

	_wiaas_import_field_group($ui_json);
}

function wiaas_db_update_add_product_properties_ui_fields() {

	$ui_json = file_get_contents( dirname( __FILE__ ) . '/data/wiaas-ui-field-product-properties.json' );

	$ui_json = json_decode( $ui_json, true );

	_wiaas_import_field_group($ui_json);
}


// private helper function

function _wiaas_import_field_group($json) {
	// vars
	$ids = array();
	$keys = array();


	// populate keys
	foreach( $json as $field_group ) {

		// append key
		$keys[] = $field_group['key'];

	}


	// look for existing ids
	foreach( $keys as $key ) {

		// attempt find ID
		$field_group = _acf_get_field_group_by_key( $key );


		// bail early if no field group
		if( !$field_group ) continue;


		// append
		$ids[ $key ] = $field_group['ID'];

	}


	// enable local
	acf_enable_local();


	// reset local (JSON class has already included .json field groups which may conflict)
	acf_reset_local();


	// add local field groups
	foreach( $json as $field_group ) {

		// add field group
		acf_add_local_field_group( $field_group );

	}


	// loop over keys
	foreach( $keys as $key ) {

		// vars
		$field_group = acf_get_local_field_group( $key );


		// attempt get id
		$id = acf_maybe_get( $ids, $key );

		if( $id ) {

			$field_group['ID'] = $id;

		}


		// append fields
		if( acf_have_local_fields($key) ) {

			$field_group['fields'] = acf_get_local_fields( $key );

		}


		// import
		acf_import_field_group( $field_group );

	}
}
