<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  Christopher Graham
 * @package    stats
 */

/**
 * Hook class.
 */
class Hook_admin_stats_ratings extends CMSStatsProvider
{
    /**
     * Find metadata about stats graphs that are provided by this stats hook.
     *
     * @param  boolean $for_kpi Whether this is for setting up a KPI
     * @return ?array Map of metadata (null: hook is disabled)
     */
    public function info(bool $for_kpi = false) : ?array
    {
        if (get_option('is_on_rating') == '0') {
            return null;
        }

        return [
            'ratings' => [
                'label' => do_lang_tempcode('RATINGS'),
                'category' => 'feedback_and_engagement',
                'filters' => [
                    'ratings__month_range' => new CMSStatsDateMonthRangeFilter('ratings__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'ratings__rating_for_type' => new CMSStatsListFilter('ratings__rating_for_type', do_lang_tempcode('CONTENT_TYPE'), $this->find_all_feedback_type_codes()),
                ],
                'pivot' => null,
            ],
            'average_rating' => [
                'label' => do_lang_tempcode('AVERAGE_RATING'),
                'category' => 'feedback_and_engagement',
                'filters' => [
                    'average_rating__month_range' => new CMSStatsDateMonthRangeFilter('average_rating__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'average_rating__rating_for_type' => new CMSStatsListFilter('average_rating__rating_for_type', do_lang_tempcode('CONTENT_TYPE'), $this->find_all_feedback_type_codes()),
                ],
                'pivot' => new CMSStatsDatePivot('average_rating__pivot', $this->get_date_pivots(!$for_kpi)),
                'support_kpis' => self::KPI_HIGH_IS_GOOD,
            ],
        ];
    }

    /**
     * Preprocess raw data in the database into something we can efficiently draw graphs/conclusions from.
     *
     * @param  TIME $start_time Start timestamp
     * @param  TIME $end_time End timestamp
     * @param  array $data_buckets Map of data buckets; a map of bucket name to nested maps with the following maps in sequence: 'month', 'pivot', 'value' (then further map data) ; extended and returned by reference
     */
    public function preprocess_raw_data(int $start_time, int $end_time, array &$data_buckets)
    {
        require_code('temporal');

        $server_timezone = get_server_timezone();

        $date_pivots = $this->get_date_pivots();

        $max = 1000;
        $start = 0;

        $query = 'SELECT * FROM ' . get_table_prefix() . 'rating WHERE ';
        $query .= 'rating_time>=' . strval($start_time) . ' AND ';
        $query .= 'rating_time<=' . strval($end_time);
        $query .= ' ORDER BY rating_time';
        do {
            $rows = $GLOBALS['SITE_DB']->query($query, $max, $start);
            foreach ($rows as $row) {
                $timestamp = $row['rating_time'];
                $timestamp = tz_time($timestamp, $server_timezone);

                $month = to_epoch_interval_index($timestamp, 'months');

                $rating_for_type = $row['rating_for_type'];
                $rating = $row['rating'];

                if (!isset($data_buckets['ratings'][$month][''][$rating_for_type][$rating])) {
                    $data_buckets['ratings'][$month][''][$rating_for_type][$rating] = 0;
                }
                $data_buckets['ratings'][$month][''][$rating_for_type][$rating]++;

                foreach (array_keys($date_pivots) as $pivot) {
                    $pivot_value = $this->calculate_date_pivot_value($pivot, $timestamp);

                    if (!isset($data_buckets['average_rating'][$month][$pivot][$pivot_value][$rating_for_type])) {
                        $data_buckets['average_rating'][$month][$pivot][$pivot_value][$rating_for_type] = [0, 0];
                    }
                    $data_buckets['average_rating'][$month][$pivot][$pivot_value][$rating_for_type][0] += $rating;
                    $data_buckets['average_rating'][$month][$pivot][$pivot_value][$rating_for_type][1]++;
                }
            }

            $start += $max;
        } while (!empty($rows));
    }

    /**
     * Generate final data from preprocessed data.
     *
     * @param  string $bucket Data bucket we want data for
     * @param  string $pivot Pivot value
     * @param  array $filters Map of filters (including pivot if applicable)
     * @return ?array Final data in standardised map format (null: could not generate)
     */
    public function generate_final_data(string $bucket, string $pivot, array $filters) : ?array
    {
        switch ($bucket) {
            case 'ratings':
                $range = $this->convert_month_range_filter_to_pair($filters[$bucket . '__month_range']);

                $data = [
                    1 => 0,
                    2 => 0,
                    3 => 0,
                    4 => 0,
                    5 => 0,
                ];

                $where = [
                    'p_bucket' => $bucket,
                    'p_pivot' => $pivot,
                ];
                $extra = '';
                $extra .= ' AND p_month>=' . strval($range[0]);
                $extra .= ' AND p_month<=' . strval($range[1]);
                $data_rows = $GLOBALS['SITE_DB']->query_select('stats_preprocessed', ['p_data'], $where, $extra);
                foreach ($data_rows as $data_row) {
                    $_data = @unserialize($data_row['p_data']);
                    foreach ($_data as $rating_for_type => $_) {
                        if ((!empty($filters[$bucket . '__rating_for_type'])) && ($filters[$bucket . '__rating_for_type'] != $rating_for_type)) {
                            continue;
                        }

                        foreach ($_ as $rating => $num_ratings) {
                            $_rating = intval(round((floatval($rating) / 2.0)));
                            $data[$_rating] += $num_ratings;
                        }
                    }
                }

                return [
                    'type' => self::GRAPH_BAR_CHART,
                    'data' => $data,
                    'x_axis_label' => do_lang_tempcode('RATING'),
                    'y_axis_label' => do_lang_tempcode('COUNT_NEW'),
                ];

            case 'average_rating':
                $range = $this->convert_month_range_filter_to_pair($filters[$bucket . '__month_range']);

                $data = $this->fill_data_by_date_pivots($pivot, $range[0], $range[1]);

                $where = [
                    'p_bucket' => $bucket,
                    'p_pivot' => $pivot,
                ];
                $extra = '';
                $extra .= ' AND p_month>=' . strval($range[0]);
                $extra .= ' AND p_month<=' . strval($range[1]);
                $data_rows = $GLOBALS['SITE_DB']->query_select('stats_preprocessed', ['p_data'], $where, $extra);
                foreach ($data_rows as $data_row) {
                    $_data = @unserialize($data_row['p_data']);
                    foreach ($_data as $pivot_value => $__) {
                        $pivot_value = $this->make_date_pivot_value_nice($pivot, $pivot_value);

                        $aggregate_rating = 0;
                        $total_ratings = 0;

                        foreach ($__ as $rating_for_type => $_) {
                            if ((!empty($filters[$bucket . '__rating_for_type'])) && ($filters[$bucket . '__rating_for_type'] != $rating_for_type)) {
                                continue;
                            }

                            $aggregate_rating += $_[0];
                            $total_ratings += $_[1];
                        }

                        $data[$pivot_value] = (floatval($aggregate_rating) / 2.0) / floatval($total_ratings);
                    }
                }

                if (array_sum($data) == 0) {
                    $data = [];
                }

                return [
                    'type' => null,
                    'data' => $data,
                    'x_axis_label' => do_lang_tempcode('TIME_IN_TIMEZONE', escape_html(make_nice_timezone_name(get_site_timezone()))),
                    'y_axis_label' => do_lang_tempcode('AVERAGE_RATING'),
                ];
        }

        fatal_exit(do_lang_tempcode('INTERNAL_ERROR', escape_html('8b7bdc2cdb7f5b55accedb56961aae08')));
    }
}
