<?php
/*

Copyright 2014 Dario Curvino (email : d.curvino@tiscali.it)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>
*/

if (!defined('ABSPATH')) {
    exit('You\'re not allowed to see this page');
} // Exit if accessed directly

/**
 * Class YasrRankings
 */
class YasrRankings extends YasrShortcode {

    protected $query_highest_rated_overall;
    protected $query_result_most_rated_visitor;
    protected $query_result_highest_rated_visitor;

    /**
     * Returns the shortcode for yasr_ov_ranking
     *
     * @param $atts
     *
     * @return string
     */
    public function returnHighestRatedOverall ($atts) {
        $this->shortcode_html = '<!-- Yasr Highest Rated Shortcode-->';

        //hook in this filter to get cleaned_atts to use in yasr_ov_ranking
        //false is the default value to assign to cleaned_atts
        $cleaned_atts = apply_filters('yasr_ov_rankings_atts', false, $atts);
        $this->query_highest_rated_overall = YasrRankingData::rankingOverallGetResults($cleaned_atts);

        //hook in this filter to making $cleaned_atts ready to be printed in shortcode
        $cleaned_params = apply_filters('yasr_ov_rankings_cleaned_atts', $cleaned_atts);

        $this->returnTableOverall($cleaned_params);
        $this->shortcode_html .= '<!--End Yasr Top 10 highest Rated Shortcode-->';

        return $this->shortcode_html;
    }

    /**
     * Returns only initial and ending table tag
     * Table content is build with REACT
     *
     * @author Dario Curvino <@dudo>
     * @since 2.5.7
     *
     * @param $sql_params array|string - params that can be used in REST API
     *
     */
    protected function returnTableOverall($sql_params=false) {
        if ($this->query_highest_rated_overall) {

            $table_id = 'yasr_overall_ranking_'.str_shuffle(uniqid());
            $array_with_title['data_overall'] = self::rankingData($this->query_highest_rated_overall);

            $table_attributes = json_encode($sql_params);

            $this->shortcode_html .= "<table 
                                          class='yasr-rankings yasr-stars-rankings'
                                          id=$table_id
                                          data-ranking-data='".json_encode($array_with_title)."'
                                          data-ranking-source='overall_rating'
                                          data-ranking-params='$table_attributes'
                                          data-ranking-size='".$this->starSize()."'
                                          >";

            $this->shortcode_html .= "</table>";
        }
        else {
            $this->shortcode_html .= __("No data found", 'yet-another-stars-rating');
        }

    }

    /**
     * Returns the shortcode for yasr_most_or_highest_rated_posts
     *
     * @param $atts
     *
     * @return string
     */
    public function vvReturnMostHighestRated ($atts) {
        $this->shortcode_html = '<!-- Yasr Most Or Highest Rated Shortcode -->';

        //hook in this filter to get sql_atts to use in yasr_ov_ranking
        //false is the default value to assign to sql_atts
        $sql_atts = apply_filters('yasr_vv_rankings_atts', false, $atts);

        if($sql_atts !== false) {
            $required_votes_most    = $sql_atts['required_votes']['most'];
            $required_votes_highest = $sql_atts['required_votes']['highest'];
        } else {
            $required_votes_most    = 1;
            $required_votes_highest = 1;
        }

        $this->query_result_most_rated_visitor    = YasrRankingData::rankingVVGetResults($sql_atts, 'most', $required_votes_most);
        $this->query_result_highest_rated_visitor = YasrRankingData::rankingVVGetResults($sql_atts, 'highest', $required_votes_highest);

        //hook in this filter to making $sql_atts ready for wp_localize_script
        $cleaned_params = apply_filters('yasr_vv_rankings_cleaned_atts', $sql_atts);

        $this->returnTableVV($cleaned_params);
        $this->shortcode_html .= '<!--End Yasr TMost Or Highest Rated Shortcode -->';

        return $this->shortcode_html;
    }

    /**
     * Create the queries for the rankings
     * Return the full html for the shortcode
     *
     * @param $sql_params array|string - params that can be used in REST API
     */
    public function returnTableVV($sql_params=null) {
        if($this->query_result_most_rated_visitor && $this->query_result_highest_rated_visitor) {

            $table_attributes = json_encode($sql_params);

            $array_with_title['most']    = self::rankingData($this->query_result_most_rated_visitor);
            $array_with_title['highest'] = self::rankingData($this->query_result_highest_rated_visitor);

            $table_id = 'yasr_vv_ranking_' . str_shuffle(uniqid());

            $this->shortcode_html .= "<table 
                                          class='yasr-rankings yasr-stars-rankings'
                                          id=$table_id
                                          data-ranking-data='".json_encode($array_with_title)."'
                                          data-ranking-source='visitor_votes'
                                          data-ranking-params='$table_attributes'
                                          data-ranking-size='".$this->starSize()."'
                                          >";
            $this->shortcode_html .= '</table>';

        } else {
            $this->shortcode_html .= __("No data found", 'yet-another-stars-rating');
        }

    }

    /**
     * Returns an array with post titles and links
     *
     * @author Dario Curvino <@dudo>
     * @since 2.5.2
     *
     * @param $query_result array to loop; MUST have:
     * post_id
     * rating
     * (optional) number_of_votes
     *
     * @return array
     */
    public static function rankingData($query_result) {
        $data_array = array();

        $i=0;
        foreach ($query_result as $result) {
            $data_array[$i]['post_id']        = (int)$result->post_id;
            $data_array[$i]['rating']         = round($result->rating,1);
            if(isset($result->number_of_votes)) {
                $data_array[$i]['number_of_votes'] = (int)$result->number_of_votes;
            }
            $data_array[$i]['title']          = wp_strip_all_tags(get_the_title($result->post_id));
            $data_array[$i]['link']           = get_permalink($result->post_id); //Get permalink from post id
            $i++;
        } //End foreach

        return $data_array;
    }

}