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


/**
 * Get petitions of people following by user
 *
 * @since Campoal 1.0.0
 */
if( !function_exists('conikal_newsfeed_petitions') ): 
    function conikal_newsfeed_petitions($user_id, $paged = 1, $country_selected = false) {
        global $campoal_options;
        global $current_user;

        $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'] : '';
        $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';
        $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);
        }

        $posts_per_page         = $posts_per_page_setting != '' ? round($posts_per_page_setting / 2) : 5;

        $follow_user = get_user_meta($user_id, 'follow_user', true);
        $follow_topics = get_user_meta($user_id, 'follow_topics', true);

        $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;

        // query of following user's pettion
        $users_args = array(
            'post_type'         => 'petition',
            'posts_per_page'    => $posts_per_page,
            'paged'             => $paged,
            'post_status'       => array('publish'),
            'order'             => $order,
            'orderby'           => conikal_meta_key_ordering_filter($orderby),
        );

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

        // only show petition matched with country selected
        if ($country_selection_mode && $filter_by_country && $country_selected != 'WORLD') {
            array_push($users_args['meta_query'], array(
                'key'     => 'petition_country',
                'value'   => $country_selected,
                'compare' => 'IN'
            ));
        }

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

        $petition_users = new WP_Query($users_args);

        wp_reset_query();
        wp_reset_postdata();

        // query of topic's petition
        $topics_args = array(
            'post_type' => 'petition',
            'posts_per_page' => $posts_per_page,
            'paged' => $paged,
            'post_status' => array('publish'),
        );

        if ($follow_topics != '') {
            $topics_args['tax_query'] = array(
                array(
                    'taxonomy' => 'petition_topics',
                    'field'    => 'term_id',
                    'terms'    => $follow_topics,
                ),
            );
        }
        
        $topics_args['meta_query'] = array('relation' => 'AND');
        
        if ($minimum_signature != 0) {

            array_push($topics_args['meta_query'], array(
                'key'     => 'petition_sign',
                'value'   => $minimum_signature,
                'type'    => 'NUMERIC',
                'compare' => '>='
            ));
        }

        // only show petition matched with country selected
        if ($country_selection_mode && $filter_by_country && $country_selected != 'WORLD') {
            array_push($topics_args['meta_query'], array(
                'key'     => 'petition_country',
                'value'   => $country_selected,
                'compare' => 'IN'
            ));
        }

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

        $petition_topics = new WP_Query($topics_args);
        
        wp_reset_query();
        wp_reset_postdata();

        // marge array pettion user and topic petition following
        if ($petition_users->have_posts() && $petition_topics->have_posts()) {
            //create new empty query and populate it with the other two
            $query = new WP_Query();
            $query->posts = array_merge($petition_users->posts, $petition_topics->posts);
            $query->posts = array_unique($query->posts, SORT_REGULAR);
            
            //populate post_count count for the loop to work correctly
            $query->post_count = count($query->posts);
            wp_reset_query();
            wp_reset_postdata();
        } elseif ($petition_topics->have_posts()) {
            $query = $petition_topics;
        } else {
            $query = $petition_users;
        }
        
        return $query;
    }
endif;

/**
 * Load more newsfeed petitions
 *
 * @since Campoal 1.0.0
 */
if( !function_exists('conikal_load_newsfeed_petitions') ): 
    function conikal_load_newsfeed_petitions() {
        check_ajax_referer('load_petitions_ajax_nonce', 'security');
        global $campoal_options;
        
        $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 != '' ? round($posts_per_page_setting / 2) : 5;

        $user_id = isset($_POST['user_id']) ? sanitize_text_field($_POST['user_id']) : '';
        $paged = isset($_POST['paged']) ? sanitize_text_field($_POST['paged']) : 2;
        $country = isset($_POST['country']) ? sanitize_text_field($_POST['country']) : 'WORLD';

        // get newsfeed petitions data
        $petitions = conikal_newsfeed_petitions($user_id, $paged, $country);

        // 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->post_count, '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_newsfeed_petitions', 'conikal_load_newsfeed_petitions' );
add_action( 'wp_ajax_conikal_load_newsfeed_petitions', 'conikal_load_newsfeed_petitions' );

?>