<?php
/**
 * Makes a filter for the custom post type associats and its custom fields
 *
 * references:
 * basic start
 * https://www.advancedcustomfields.com/resources/creating-wp-archive-custom-field-filter/
 * 
 * checkbox adaptation query filter
 * https://barn2.com/blog/querying-posts-by-custom-field-acf/#array-based-fields
 *
 * @package Xarxaprod_wp_plugin
 */

// define the filter fields
// array of filters (field key => field name)
$GLOBALS['my_query_filters_associat'] = array(
  'associatfield' => 'xxp_associat_field', //disciplines
  'associatterritory' => 'xxp_associat_territory', //territori
  'associatservice' => 'xxp_associat_service', //serveis
  'associatcenter' => 'xxp_associat_center' //centre

);
$GLOBALS['my_query_filters_associat_dates'] = array(
  'associatapplybegin' => 'xxp_associat_apply_begin',
  'associatapplyend' => 'xxp_associat_apply_end'
  //'associatcall' => 'xxp_associat_call',
);

// action
add_action('pre_get_posts', 'my_pre_get_posts_associats',10,1);
if ( ! function_exists( 'my_pre_get_posts_associats' ) ){
  function my_pre_get_posts_associats( $query ) {
    
    // bail early if is in admin
    if( is_admin() ) { return; }
    
    // bail early if not main query or plugin $the_query_associat
    // - allows custom code / plugins to continue working
    if( !$query->is_main_query() ) return;
    $query->set( 'posts_per_page', -1);
    //$query->set( 'relation', 'AND');

    // loop over filters
    foreach( $GLOBALS['my_query_filters_associat'] as $key => $fieldname)
    {
      // continue if not found in url
      if( empty($_GET[ $fieldname ]) ) { continue; }

      // get original meta query
      $meta_query = []; //avoids infinite nesting
      $meta_query[] = $query->get('meta_query');

      // get the values for this filter
      // eg: http://domain.tdl/associat/?xxp_associat_target=autonoma,entitat-publica
      $filtervalues= explode(',', $_GET[ $fieldname ]);

      // loop retreived values from checkboxes and filter them 
      foreach( $filtervalues as $filteredvalue )
      {
        
      // add our meta query to the original meta queries
        $meta_query['relation'] = 'OR';
        $meta_query[] = array(
          'key'      =>  $fieldname,
          'value'    => $filteredvalue,
          'compare'  =>  'LIKE'
        );
      }
      // update the meta query arguments
      $query->set('meta_query', $meta_query);
      //$query->set('relation', 'AND');
    }
    //echo '<pre>' . var_export($query, true) . '</pre>';
    //echo '<pre>' . print_r($query,true) . '</pre>';
    //always return
    return;
  }
}