<?php

$defaults = array(
	'data_source'		=> is_post_type_archive() ? 'main_query' : 'custom_query',
	'post_type' 		=> 'post',
	'order_by'  		=> 'date',
	'order'     		=> 'DESC',
	'offset'    		=> 0,
	'users'     		=> '',
	'exclude_current_post' => 'no',
);

$tab_group     = isset( $tab['group'] ) ? $tab['group'] : '';
$tab_defaults  = [];
$query_node_id = '';
$prefix        = '';

if ( 'dynamic' === $tab_group ) {
	$orig_tab_defaults = isset( $tab['defaults'] ) ? (array) $tab['defaults'] : array();
	$query_node_id     = isset( $tab['query_node_id'] ) ? $tab['query_node_id'] : '';
	$prefix            = empty( $query_node_id ) ? '' : '__' . $query_node_id . '__';

	foreach ( $orig_tab_defaults as $k => $v ) {
		$tab_defaults[ $prefix . $k ] = $v;
	}
}

$settings = (object) array_merge( $defaults, $tab_defaults, (array) $settings );

$settings = apply_filters( 'pp_cg_loop_settings', $settings );

do_action( 'pp_cg_loop_settings_before_form', $settings ); // e.g Add custom FLBuilder::render_settings_field()

?>
<div id="fl-builder-settings-section-source" class="fl-loop-data-source-select fl-builder-settings-section">
	<div class="fl-builder-settings-section-content">
		<table class="fl-form-table">
		<?php

		// Data Source
		FLBuilder::render_settings_field($prefix . 'data_source', array(
			'type'          => 'select',
			'label'         => __('Source', 'bb-powerpack'),
			'options'       => array(
				'custom_query'  => __('Custom Query', 'bb-powerpack'),
				'main_query'    => __('Main Query', 'bb-powerpack'),
			),
			'toggle'        => array(
				'custom_query'  => array(
					'sections'		=> array( 'query', 'filter', 'custom_field', 'post-filter' ),
					'fields'        => array( 'posts_per_page' )
				),
				'main_query'  => array(
					'sections'		=> array( 'post-filter' ),
				),
				'pods_relationship'	=> array(
					'sections'		=> array( 'query' ),
					'fields'        => array( 'posts_per_page' )
				),
				'acf_relationship'	=> array(
					'sections'			=> array('acf_relationship'),
					'fields'        	=> array( 'posts_per_page' )
				)
			)
		), $settings, $data);
		?>
		</table>
	</div>
</div>

<div class="fl-loop-data-source-acf fl-loop-data-source" data-source="acf_relationship">
	<div id="fl-builder-settings-section-acf_relationship" class="fl-builder-settings-section">
		<div class="fl-builder-settings-section-content">
			<table class="fl-form-table">
			<?php
			FLBuilder::render_settings_field('data_source_acf_relational_type', array(
				'type'		=> 'select',
				'label'		=> __( 'Type', 'bb-powerpack' ),
				'default'       => 'relationship',
				'options'       => array(
					'relationship'  => __( 'Relationship', 'bb-powerpack' ),
					'user'          => __( 'User', 'bb-powerpack' ),
				),
			), $settings);

			FLBuilder::render_settings_field('data_source_acf_relational_key', array(
				'type'          => 'text',
				'label'         => __( 'Key', 'bb-powerpack' ),
			), $settings);

			// Order
			FLBuilder::render_settings_field('data_source_acf_order', array(
				'type'    => 'select',
				'label'   => __( 'Order', 'bb-powerpack' ),
				'options' => array(
					'DESC' => __( 'Descending', 'bb-powerpack' ),
					'ASC'  => __( 'Ascending', 'bb-powerpack' ),
				),
			), $settings);

			// Order by
			FLBuilder::render_settings_field('data_source_acf_order_by', array(
				'type'    => 'select',
				'label'   => __( 'Order By', 'bb-powerpack' ),
				'default' => 'post__in',
				'options' => array(
					'author'         => __( 'Author', 'bb-powerpack' ),
					'comment_count'  => __( 'Comment Count', 'bb-powerpack' ),
					'date'           => __( 'Date', 'bb-powerpack' ),
					'modified'       => __( 'Date Last Modified', 'bb-powerpack' ),
					'ID'             => __( 'ID', 'bb-powerpack' ),
					'menu_order'     => __( 'Menu Order', 'bb-powerpack' ),
					'meta_value'     => __( 'Meta Value (Alphabetical)', 'bb-powerpack' ),
					'meta_value_num' => __( 'Meta Value (Numeric)', 'bb-powerpack' ),
					'rand'           => __( 'Random', 'bb-powerpack' ),
					'title'          => __( 'Title', 'bb-powerpack' ),
					'name'          => __( 'Slug', 'bb-powerpack' ),
					'post__in'       => __( 'Selection Order', 'bb-powerpack' ),
				),
				'toggle'  => array(
					'meta_value'     => array(
						'fields' => array( 'data_source_acf_order_by_meta_key' ),
					),
					'meta_value_num' => array(
						'fields' => array( 'data_source_acf_order_by_meta_key' ),
					),
				),
			), $settings);

			// Meta Key
			FLBuilder::render_settings_field('data_source_acf_order_by_meta_key', array(
				'type'  => 'text',
				'label' => __( 'Meta Key', 'bb-powerpack' ),
			), $settings);
			?>
			</table>
		</div>
	</div>
</div>

<div class="fl-custom-query fl-loop-data-source" data-source="custom_query">
	<div id="fl-builder-settings-section-query" class="fl-builder-settings-section fl-builder-settings-section-collapsed">
		<div class="fl-builder-settings-section-header">
			<button class="fl-builder-settings-title">
				<?php pp_builder_setting_form_section_icon(); ?>
				<?php _e('Custom Query', 'bb-powerpack'); ?>
			</button>
		</div>
		<div class="fl-builder-settings-section-content">
			<table class="fl-form-table">
			<?php
			// Post type
			FLBuilder::render_settings_field($prefix . 'post_type', array(
				'type'          => 'post-type',
				'label'         => __('Post Type', 'bb-powerpack'),
				'multi-select' => true,
			), $settings);

			// Order by
			FLBuilder::render_settings_field($prefix . 'order_by', array(
				'type'          => 'select',
				'label'         => __('Order By', 'bb-powerpack'),
				'options'       => array(
					'author'         => __('Author', 'bb-powerpack'),
					'comment_count'  => __('Comment Count', 'bb-powerpack'),
					'date'           => __('Date', 'bb-powerpack'),
					'modified'       => __('Date Last Modified', 'bb-powerpack'),
					'ID'             => __('ID', 'bb-powerpack'),
					'menu_order'     => __('Menu Order', 'bb-powerpack'),
					'meta_value'     => __('Meta Value (Alphabetical)', 'bb-powerpack'),
					'meta_value_num' => __('Meta Value (Numeric)', 'bb-powerpack'),
					'rand'        	 => __('Random', 'bb-powerpack'),
					'title'          => __('Title', 'bb-powerpack'),
					'post__in'       => __( 'Selection Order', 'bb-powerpack' ),
				),
				'toggle'		=> array(
					'meta_value' 	=> array(
						'fields'		=> array( 'order_by_meta_key' )
					),
					'meta_value_num' => array(
						'fields'		=> array( 'order_by_meta_key' )
					)
				)
			), $settings);

			// Meta Key
			FLBuilder::render_settings_field($prefix . 'order_by_meta_key', array(
				'type'          => 'text',
				'label'         => __('Meta Key', 'bb-powerpack'),
			), $settings);

			// Order
			FLBuilder::render_settings_field($prefix . 'order', array(
				'type'          => 'select',
				'label'         => __('Order', 'bb-powerpack'),
				'options'       => array(
					'DESC'          => __('Descending', 'bb-powerpack'),
					'ASC'           => __('Ascending', 'bb-powerpack'),
				)
			), $settings);

			// Offset
			FLBuilder::render_settings_field($prefix . 'offset', array(
				'type'          => 'text',
				'label'         => _x('Offset', 'How many posts to skip.', 'bb-powerpack'),
				'default'       => '0',
				'size'          => '4',
				'help'          => __('Skip this many posts that match the specified criteria.', 'bb-powerpack')
			), $settings);

			FLBuilder::render_settings_field($prefix . 'exclude_current_post', array(
				'type'					=> 'pp-switch',
				'label'					=> __('Exclude Current Post', 'bb-powerpack'),
				'default'				=> 'no',
				'options'				=> array(
					'yes'					=> __('Yes', 'bb-powerpack'),
					'no'					=> __('No', 'bb-powerpack')
				)
			), $settings);

			?>
			</table>
		</div>
	</div>
	<div id="fl-builder-settings-section-filter" class="fl-builder-settings-section fl-builder-settings-section-collapsed">
		<div class="fl-builder-settings-section-header">
			<button class="fl-builder-settings-title">
				<?php pp_builder_setting_form_section_icon(); ?>
				<?php _e('Filter', 'bb-powerpack'); ?>
			</button>
		</div>
		<div class="fl-builder-settings-section-content">
			<?php foreach(FLBuilderLoop::post_types() as $slug => $type) : ?>
				<table class="fl-form-table fl-custom-query-filter fl-custom-query-<?php echo $slug; ?>-filter fl-loop-builder-filter fl-loop-builder-<?php echo $slug; ?>-filter" <?php if($slug == $settings->{$prefix . 'post_type'}) echo 'style="display:table;"'; ?>>
				<?php

				// Posts
				FLBuilder::render_settings_field($prefix . 'posts_' . $slug, array(
					'type'          => 'suggest',
					'action'        => 'fl_as_posts',
					'data'          => $slug,
					'label'         => $type->label,
					/* translators: %s: post type label */
					'help'          => sprintf( __( 'Enter a list of %s.', 'bb-powerpack' ), $type->label ),
					'matching'      => true
				), $settings);

				// Taxonomies
				$taxonomies = FLBuilderLoop::taxonomies($slug);

				$field_settings = new stdClass;
				foreach ( $settings as $k => $setting ) {
					if ( false !== strpos( $k, 'tax_' . $slug ) ) {
						$field_settings->$k = $setting;
					}
				}

				foreach ( $taxonomies as $tax_slug => $tax ) {

					$field_key = 'tax_' . $slug . '_' . $tax_slug;

					if ( isset( $settings->$field_key ) ) {
						$field_settings->$field_key = $settings->$field_key;
					}

					FLBuilder::render_settings_field( $prefix . $field_key, array(
						'type'          => 'suggest',
						'action'        => 'fl_as_terms',
						'data'          => $tax_slug,
						'label'         => $tax->label,
						/* translators: %s: tax label */
						'help'          => sprintf( __( 'Enter a list of %s.', 'bb-powerpack' ), $tax->label ),
						'matching'      => true
					), $field_settings );
				}

				?>
				</table>
			<?php endforeach; ?>
			<table class="fl-form-table">
			<?php

			// Author
			FLBuilder::render_settings_field($prefix . 'users', array(
				'type'          => 'suggest',
				'action'        => 'fl_as_users',
				'label'         => __('Authors', 'bb-powerpack'),
				'help'          => __('Enter a comma separated list of authors usernames. Only posts with these authors will be shown.', 'bb-powerpack'),
				'matching'      => true
			), $settings);

			?>
			</table>
		</div>
	</div>
	<div id="fl-builder-settings-section-custom_field" class="fl-builder-settings-section fl-builder-settings-section-collapsed">
		<div class="fl-builder-settings-section-header">
			<button class="fl-builder-settings-title">
				<?php pp_builder_setting_form_section_icon(); ?>
				<?php _e( 'Custom Field Filter', 'bb-powerpack' ); ?>
			</button>
		</div>

		<div class="fl-builder-settings-section-content">
			<table class="fl-form-table">
			<?php
				FLBuilder::render_settings_field( $prefix . 'custom_field_relation', array(
					'type'    => 'select',
					'label'   => __( 'Relation', 'bb-powerpack' ),
					'default' => 'AND',
					'options' => array(
						'AND' => __( 'AND', 'bb-powerpack' ),
						'OR'  => __( 'OR', 'bb-powerpack' ),
					),
				), $settings);
				?>
			</table>
			<table class="fl-form-table">
			<?php
				FLBuilder::render_settings_field( $prefix . 'custom_field', array(
					'type'         => 'form',
					'help'         => __( 'Custom field key.', 'bb-powerpack' ),
					'label'        => __( 'Custom Field', 'bb-powerpack' ),
					'form'         => 'custom_fields_form',
					'default'      => array( 0 => '' ),
					'preview_text' => 'filter_meta_label',
					'multiple'     => true,
				), $settings);
				?>
			</table>
		</div>
	</div>
</div>

<?php
do_action( 'pp_cg_loop_settings_after_form', $settings ); // e.g Add custom FLBuilder::render_settings_field()
?>

<script type="text/javascript">
	;(function($) {
		<?php if ( 'fl-theme-layout' == get_post_type() ) {
			$post_type = '';
			$taxonomy = '';
			$location = FLThemeBuilderRulesLocation::get_preview_location( get_the_ID() );
			$location_frags = explode( ':', $location );

			if ( $location_frags[0] == 'post' ) {
				$post_type = $location_frags[1];
			}
			if ( $location_frags[0] == 'archive' ) {
				$post_type = $location_frags[1];
			}
			if ( $location_frags[0] == 'taxonomy' ) {
				$taxonomy = $location_frags[1];

				global $wp_taxonomies;
				$post_type_array = isset( $wp_taxonomies[ $taxonomy ] ) ? $wp_taxonomies[ $taxonomy ]->object_type : array();
				if ( ! empty( $post_type_array ) ) {
					$post_type = $post_type_array[0];
				}
			}
		?>
		function pp_update_taxonomies() {
			if ( 'main_query' !== $( 'select[name="<?php echo $prefix; ?>data_source"]' ).val() ) {
				return;
			}
			var post_grid_filters = $('select[name="<?php echo $prefix; ?>post_grid_filters"]');
			var post_taxonomies = $('select[name="<?php echo $prefix; ?>post_taxonomies[]"]');
			var selected_filter = <?php echo json_encode( $settings->post_grid_filters ); ?>;
			var selected_taxonomy = <?php echo json_encode( $settings->post_taxonomies ); ?>;
			var post_type = '<?php echo $post_type; ?>';
			// var post_type_field = $('.fl-builder-pp-content-grid-settings select[name="post_type"]');
			// post_type_field.find('option').removeAttr('selected');
			// post_type_field.find('option[value="'+post_type+'"]').attr('selected', 'selected');
			// post_type_field.trigger('change');
			if ( '' !== post_type ) {
				$.ajax({
					type: 'post',
					data: {
						action: 'pp_get_taxonomies',
						post_type: post_type,
						value: selected_taxonomy
					},
					url: ajaxurl,
					success: function(res) {
						if ( res !== 'undefined' || res !== '' ) {
							post_grid_filters.html(res);
							post_grid_filters.find('option').removeAttr('selected');
							post_grid_filters.find('option[value="'+selected_filter+'"]').attr('selected', 'selected');
							post_grid_filters.val(selected_filter);
							post_taxonomies.html(res);
							//post_taxonomies.find('option[value="'+selected_taxonomy+'"]').attr('selected', 'selected');
						}
					}
				});
			}
		}
		pp_update_taxonomies();

		$( 'select[name="<?php echo $prefix; ?>data_source"]' ).on( 'change', pp_update_taxonomies );
		<?php } ?>

		function pp_custom_query_taxonomies() {
			if ( 'custom_query' !== $( 'select[name="<?php echo $prefix; ?>data_source"]' ).val() ) {
				return;
			}
			var post_type_slug = $('select[name="<?php echo $prefix; ?>post_type[]"]').val();
			var post_grid_filters = $('select[name="<?php echo $prefix; ?>post_grid_filters"]');
			var post_taxonomies = $('select[name="<?php echo $prefix; ?>post_taxonomies[]"]');
			var selected_filter = <?php echo json_encode( $settings->post_grid_filters ); ?>;
			var selected_taxonomy = <?php echo json_encode( $settings->post_taxonomies ); ?>;
			$.ajax({
				type: 'post',
				data: {
					action: 'pp_get_taxonomies',
					post_type: post_type_slug,
					value: selected_taxonomy
				},
				url: ajaxurl,
				success: function(res) {
					if ( res !== 'undefined' || res !== '' ) {
						post_grid_filters.html(res);
						post_grid_filters.find('option').removeAttr('selected');
						post_grid_filters.find('option[value="'+selected_filter+'"]').attr('selected', 'selected');
						post_grid_filters.val(selected_filter);
						post_taxonomies.html(res);
						//post_taxonomies.find('option[value="'+selected_taxonomy+'"]').attr('selected', 'selected');
					}
				}
			});
		}

		pp_custom_query_taxonomies();

		$('select[name="<?php echo $prefix; ?>post_type[]"], select[name="<?php echo $prefix; ?>data_source"]').on('change', function() {
			pp_custom_query_taxonomies();
		});

		var onSourceChange = function() {
			var $form = $('.fl-builder-settings');

			$form.find( 'select[name="<?php echo $prefix; ?>data_source"]' ).on( 'change', function() {
				$form.attr( 'data-current-source', $(this).val() );
			} );
		};

		var initSettings = function() {
			var $form = $('.fl-builder-settings');

			$form.find( 'select[name="<?php echo $prefix; ?>data_source"]' ).on( 'change', onSourceChange );

			$form.attr( 'data-current-source', $form.find( 'select[name="<?php echo $prefix; ?>data_source"]' ).val() );

			$form.find( '#fl-field-<?php echo $prefix; ?>post_taxonomies .fl-field-description' ).removeClass('fl-field-description').wrap('<p class="fl-field-description" />');
		};

		initSettings();
	})(jQuery);
</script>
