<?php
/**
 * @package WordPress
 * @subpackage Campoal
 */


/**
 * Search petition results
 *
 * @since Campoal 1.0.0
 */
if( !function_exists('conikal_search_petitions') ): 
    function conikal_search_petitions($post_id = '', $country_selected = false) {
        global $campoal_options;
        global $paged;
        global $current_user;
        
        $sortby_default = isset($campoal_options['conikal_sortby_default_field']) ? $campoal_options['conikal_sortby_default_field'] : 'date';
        $order_default = isset($campoal_options['conikal_order_default_field']) ? $campoal_options['conikal_order_default_field'] : 'DESC';
        $minimum_signature      = isset($campoal_options['conikal_minimum_signature_field']) ? $campoal_options['conikal_minimum_signature_field'] : 0;
        $show_petition_closed   = isset($campoal_options['conikal_show_petition_closed_field']) ? $campoal_options['conikal_show_petition_closed_field'] : 1;
        $posts_per_page_setting = isset($campoal_options['conikal_petitions_per_page_field']) ? $campoal_options['conikal_petitions_per_page_field'] : '';
        $posts_per_page         = $posts_per_page_setting != '' ? $posts_per_page_setting : 10;

        $country_selection_mode = isset($campoal_options['conikal_country_selection_mode_field']) ? $campoal_options['conikal_country_selection_mode_field'] : 0;
        $filter_by_country      = isset($campoal_options['conikal_filter_by_country_field']) ? $campoal_options['conikal_filter_by_country_field'] : 0;

        // if no country select param will use user selection instead
        if (empty($country_selected)) {
            $country_selected       = conikal_get_country_selected($current_user);
        }

        // if no post if param will use get data instead
        if (!$post_id) {
            $post_id            = isset($_GET['post_id']) ? sanitize_text_field($_GET['post_id']) : '';
        }

        $search_key             = isset($_GET['search_key']) ? sanitize_text_field($_GET['search_key']) : '';
        $search_category        = isset($_GET['search_category']) && $_GET['search_category'] != '' ? sanitize_text_field($_GET['search_category']) : 0;
        $search_category        = $search_category != 0 ? array_filter(explode(',', $search_category)) : 0;
        $search_topics          = (isset($_GET['search_topics']) && $_GET['search_topics'] != '' ? sanitize_text_field($_GET['search_topics']) : 0);
        $search_topics          = $search_topics != 0 ? array_filter(explode(',', $search_topics)) : 0;
        $search_address         = isset($_GET['search_address']) ? sanitize_text_field($_GET['search_address']) : '';
        $search_country         = isset($_GET['search_country']) && $_GET['search_country'] != '' ? sanitize_text_field($_GET['search_country']) : '';
        $search_neighborhood    = isset($_GET['search_neighborhood']) && $_GET['search_neighborhood'] != '' ? sanitize_text_field($_GET['search_neighborhood']) : '';      
        $search_state           = isset($_GET['search_state']) && $_GET['search_state'] != '' ? sanitize_text_field($_GET['search_state']) : '';
        $search_city            = isset($_GET['search_city']) && $_GET['search_city'] != '' ? sanitize_text_field($_GET['search_city']) : '';
        $search_save            = isset($_GET['search_save']) ? sanitize_text_field($_GET['search_save']) : 'off';
        $search_hide            = isset($_GET['search_hide']) ? sanitize_text_field($_GET['search_hide']) : 'off';
        $search_invert          = isset($_GET['search_invert']) ? sanitize_text_field($_GET['search_invert']) : 'off';

        $order                  = isset($_GET['order']) && !empty($_GET['order']) ? sanitize_text_field($_GET['order']) : $order_default;
        $orderby                = isset($_GET['orderby']) && !empty($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : $sortby_default;

        if (!isset($_GET['search_key']) && !isset($_GET['search_address']) && !isset($_GET['search_neighborhood']) && !isset($_GET['search_city']) && !isset($_GET['search_state']) && !isset($_GET['search_country']) && !isset($_GET['search_category']) && !isset($_GET['search_topics'])) {
            $search_key             = get_post_meta($post_id, 'search_key', true);
            $search_key             = $search_key ? $search_key : '';
            $search_address         = get_post_meta($post_id, 'search_address', true);
            $search_address         = $search_address ? $search_address : '';
            $search_neighborhood    = get_post_meta($post_id, 'search_neighborhood', true);
            $search_neighborhood    = $search_neighborhood ? $search_neighborhood : '';
            $search_city            = get_post_meta($post_id, 'search_city', true);
            $search_city            = $search_city ? $search_city : '';
            $search_state           = get_post_meta($post_id, 'search_state', true);
            $search_state           = $search_state ? $search_state : '';
            $search_country         = get_post_meta($post_id, 'search_country', true);
            $search_country         = $search_country ? $search_country : '';
            $search_category        = get_post_meta($post_id, 'search_category', true);
            $search_category        = $search_category ? $search_category : '0';
            $search_topics          = get_post_meta($post_id, 'search_topics', true);
            $search_topics          = $search_topics ? $search_topics : '0';
            $search_invert          = get_post_meta($post_id, 'search_invert', true);
            $search_invert          = $search_invert ? $search_invert : 'off';
        } else {
            // save search page
            $search_fields = array(
                'search_key'            => $search_key,
                'search_address'        => $search_address,
                'search_neighborhood'   => $search_neighborhood,
                'search_city'           => $search_city,
                'search_state'          => $search_state,
                'search_country'        => $search_country,
                'search_category'       => $search_category,
                'search_topics'         => $search_topics
            );
            conikal_save_search($post_id, $search_save, $search_hide, $search_invert, $search_fields);
        }

        $search_compare = 'IN';
        if ($search_invert == 'on') {
            $search_compare = 'NOT IN';
        }

        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'posts_per_page'    => $posts_per_page,
            'paged'             => $paged,
            'post_type'         => 'petition',
            'post_status'       => 'publish',
            's'                 => $search_key,
            'order'             => $order,
            'orderby'           => conikal_meta_key_ordering_filter($orderby),
        );

        // add meta key or supporters ordering
        if ($orderby == 'supporters') {
            $args['meta_key'] = 'petition_sign';
        }
        if ($orderby == 'views') {
            $args['meta_key'] = 'post_views_count';
        }

        if($search_category != 0 && $search_topics != 0) {
            $args['tax_query'] = array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'petition_category',
                    'field'    => 'id',
                    'terms'    => $search_category,
                    'operator' => $search_compare
                ),
                array(
                    'taxonomy' => 'petition_topics',
                    'field'    => 'name',
                    'terms'    => $search_topics,
                    'operator' => $search_compare
                ),
            );
        } elseif($search_category != 0) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'petition_category',
                    'field'    => 'id',
                    'terms'    => $search_category,
                    'operator' => $search_compare
                ),
            );
        } elseif($search_topics != 0) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'petition_topics',
                    'field'    => 'name',
                    'terms'    => $search_topics,
                    'operator' => $search_compare
                ),
            );
        }

        $args['meta_query'] = array('relation' => 'AND');

        if ($minimum_signature != 0) {
            array_push($args['meta_query'], array(
                'key'     => 'petition_sign',
                'value'   => $minimum_signature,
                'type'    => 'NUMERIC',
                'compare' => '>='
            ));
        }

        if ($show_petition_closed == 0) {
            array_push($args['meta_query'], array(
                'key'     => 'petition_status',
                'value'   => 2,
                'type'    => 'NUMERIC',
                'compare' => '!='
            ));
        }

        if($search_country != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_country',
                'value'   => $search_country,
                'compare' => $search_compare
            ));
        } elseif ($country_selection_mode && $filter_by_country && $country_selected != 'WORLD') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_country',
                'value'   => $country_selected,
                'compare' => 'IN'
            ));
        }

        if($search_state != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_state',
                'value'   => $search_state,
                'compare' => $search_compare
            ));
        }

        if($search_city != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_city',
                'value'   => $search_city,
                'compare' => $search_compare
            ));
        }

        if($search_neighborhood != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_neighborhood',
                'value'   => $search_neighborhood,
                'compare' => $search_compare
            ));
        }

        $query = new WP_Query($args);

        wp_reset_query();
        wp_reset_postdata();

        return $query;
    }
endif;


/**
 * Save search params on all pettions page
 *
 * @since Campoal 1.0.0
 */
if( !function_exists('conikal_save_search') ): 
    function conikal_save_search($post_id, $search_save = 'off', $search_hide = 'off', $search_invert = 'off', $search_fields = array()) {
        if ($post_id) {
            update_post_meta($post_id, 'search_save', $search_save);
            update_post_meta($post_id, 'search_hide', $search_hide);
            update_post_meta($post_id, 'search_invert', $search_invert);

            if ($search_save == 'on') {
                foreach ($search_fields as $key => $value) {
                    update_post_meta($post_id, $key, $value);
                }
            } else {
                foreach ($search_fields as $key => $value) {
                    if ($key == 'search_category' || $key == 'search_topics') {
                        $value = '0';
                    } else {
                        $value = '';
                    }
                    update_post_meta($post_id, $key, $value);
                }
            }

            $result = true;
        } else {
            $result = false;
        }

        return $result;
    }
endif;

/**
 * Load more search petition results
 *
 * @since Campoal 1.0.0
 */
if( !function_exists('conikal_load_search_petitions') ): 
    function conikal_load_search_petitions() {
        check_ajax_referer('load_petitions_ajax_nonce', 'security');
        global $campoal_options;
        global $paged;

        $search_keyword = isset($_POST['search_keyword']) && !empty($_POST['search_keyword']) ? sanitize_text_field($_POST['search_keyword']) : '';
        $search_category = isset($_POST['search_category']) && !empty($_POST['search_category']) ? sanitize_text_field($_POST['search_category']) : false;
        $search_category = ($search_category && $search_category != ',' ? array_filter(explode(',', $search_category)) : 0);
        $search_topics = isset($_POST['search_topics']) && !empty($_POST['search_topics']) ? sanitize_text_field($_POST['search_topics']) : false;
        $search_topics = ($search_topics && $search_topics != ',' ? array_filter(explode(',', $search_topics)) : 0);
        $search_neighborhood = isset($_POST['search_neighborhood']) && !empty($_POST['search_neighborhood']) ? sanitize_text_field($_POST['search_neighborhood']) : '';
        $search_neighborhood = ($search_neighborhood ? array_filter(explode(',', $search_neighborhood)) : '');
        $search_state = isset($_POST['search_state']) && !empty($_POST['search_state']) ? sanitize_text_field($_POST['search_state']) : '';
        $search_state = ($search_state ? array_filter(explode(',', $search_state)) : '');
        $search_city = isset($_POST['search_city']) && !empty($_POST['search_city']) ? sanitize_text_field($_POST['search_city']) : '';
        $search_city = ($search_city ? array_filter(explode(',', $search_city)) : '');
        $search_country = isset($_POST['search_country']) ? sanitize_text_field($_POST['search_country']) : '';
        $search_order = isset($_POST['search_order']) && !empty($_POST['search_order']) ? sanitize_text_field($_POST['search_order']) : 'DESC';
        $search_orderby = isset($_POST['search_orderby']) && !empty($_POST['search_orderby']) ? sanitize_text_field($_POST['search_orderby']) : 'ID';
        
        $minimum_signature = isset($campoal_options['conikal_minimum_signature_field']) ? $campoal_options['conikal_minimum_signature_field'] : 0;
        
        $posts_per_page_setting = isset($campoal_options['conikal_petitions_per_page_field']) ? $campoal_options['conikal_petitions_per_page_field'] : '';
        $posts_per_page = $posts_per_page_setting != '' ? $posts_per_page_setting : 10;

        $args = array(
            'posts_per_page'    => $posts_per_page,
            'paged'             => 1,
            'post_type'         => 'petition',
            'post_status'       => array('publish'),
            's'                 => $search_keyword,
            'order'             => $search_order,
            'orderby'           => conikal_meta_key_ordering_filter($search_orderby),
        );

        if ($search_orderby == 'supporters') {
            $args['meta_key'] = 'petition_sign';
        }
        if ($search_orderby == 'views') {
            $args['meta_key'] = 'post_views_count';
        }

        if($search_category != 0 && $search_topics != 0) {
            $args['tax_query'] = array(
                'relation' => 'OR',
                array(
                    'taxonomy' => 'petition_category',
                    'field'    => 'term_id',
                    'terms'    => $search_category,
                ),
                array(
                    'taxonomy' => 'petition_topics',
                    'field'    => 'term_id',
                    'terms'    => $search_topics,
                ),
            );
        } elseif($search_category != 0) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'petition_category',
                    'field'    => 'term_id',
                    'terms'    => $search_category,
                ),
            );
        } elseif($search_topics != 0) {
            $args['tax_query'] = array(
                array(
                    'taxonomy' => 'petition_topics',
                    'field'    => 'term_id',
                    'terms'    => $search_topics,
                ),
            );
        }

        $args['meta_query'] = array('relation' => 'AND');

        if ($minimum_signature != 0) {
            array_push($args['meta_query'], array(
                'key'     => 'petition_sign',
                'value'   => $minimum_signature,
                'type'    => 'NUMERIC',
                'compare' => '>='
            ));
        }

        if($search_country != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_country',
                'value'   => $search_country,
            ));
        }

        if($search_state != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_state',
                'value'   => $search_state,
                'compare' => 'IN'
            ));
        }

        if($search_city != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_city',
                'value'   => $search_city,
                'compare' => 'IN'
            ));
        }

        if($search_neighborhood != '') {
            array_push($args['meta_query'], array(
                'key'     => 'petition_neighborhood',
                'value'   => $search_neighborhood,
                'compare' => 'IN'
            ));
        }

        $petitions = new WP_Query($args);
        
        wp_reset_query();
        wp_reset_postdata();

        // processing query and get meta post.
        $arrayPetitions = conikal_process_petition_query($petitions);

        if ($arrayPetitions) {
            echo json_encode(array('status' => true, 'found_posts' => count($arrayPetitions), 'total' => $petitions->found_posts, 'per_page' => $posts_per_page, 'petitions' => $arrayPetitions, 'message' => esc_html__('Petitions was loaded successfully.', 'campoal')));
            exit();
        } else {
            echo json_encode(array('status' => false, 'message' => esc_html__('Something went wrong. Not found petitions.', 'campoal')));
            exit();
        }

        die();
    }
endif;
add_action( 'wp_ajax_nopriv_conikal_load_search_petitions', 'conikal_load_search_petitions' );
add_action( 'wp_ajax_conikal_load_search_petitions', 'conikal_load_search_petitions' );


?>