<?php
if ( ! function_exists( 'wpj_get_acf_field_data' ) ) {
	function wpj_get_acf_field_data( $page = '', $meta_key = '', $default_value = '', $return = 'label' ) {
		if ( function_exists( 'get_field' ) ) {
			if ( $page == 'request' ) {
				$fields = get_field( 'request_fields', wpj_get_option( 'wpjobster_new_request_page_id' ) );

			} elseif ( $page == 'job' ) {
				$fields = get_field( 'job_fields', wpj_get_option( 'wpjobster_post_new_page_id' ) );

			} else {
				$fields = get_field( $page, wpj_get_option( 'wpjobster_user_profile_page_id' ) );

			}

			if ( $fields ) {
				foreach ( $fields as $key => $field ) {
					if ( $return == 'label' && ! empty( $field['acf_fc_layout'] ) && $field['acf_fc_layout'] == $meta_key ) {
						return $field['label'];

					} elseif ( $return == 'slug' && ! empty( $field['acf_fc_layout'] ) && $field['acf_fc_layout'] == $meta_key ) {
						return $field['slug'];

					} elseif ( $return == 'field' && $field['acf_fc_layout'] == $meta_key ) {
						return $field;

					}
				}
			}

			return $default_value;

		}

		return false;
	}
}

if ( ! function_exists( 'wpj_generate_array_tab_fields' ) ) {
	function wpj_generate_array_tab_fields( $page = '', $page_id = '' ) {
		if ( function_exists( 'get_field' ) ) {
			// check if the flexible content field has rows of data
			if ( function_exists( 'have_rows' ) && have_rows( $page . '_fields', $page_id ) ) {
				$fields = [];

				// create a multidimensional array to structure our data
				$fields_array = get_field_object( $page . '_fields', $page_id );

				// set up the first element for the fields without tabs
				array_push( $fields );

				$fields[0]['tab_fields'] = [];

				foreach ( $fields_array['value'] as $field ) {
					if ( $field['acf_fc_layout'] == $page . '_tab_separator' ) {
						// prepare tab with empty array for the fields
						$field['tab_fields'] = [];

						// insert tab
						array_push( $fields, $field );

					} else {
						// insert fields at the end for display, including all the errors
						end( $fields );

						$tab_key = key( $fields ); // get last tab's key

						array_push( $fields[$tab_key]['tab_fields'], $field );

					} // END if tab/input
				}

				return $fields;
			}

		}

		return false;
	}
}