<?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    cns_warnings
 */

/**
 * Hook class.
 */
class Hook_admin_stats_warnings extends CMSStatsProvider
{
    /**
     * Find metadata about stats categories that are defined by this stats hook.
     *
     * @return ?array Map of metadata (null: hook is disabled)
     */
    public function category_info() : ?array
    {
        if (!addon_installed('cns_warnings')) {
            return null;
        }

        require_lang('cns_warnings');

        return [
            'moderation' => [
                'label_lang_string' => 'PUNITIVE_ACTIONS',
                'icon' => 'menu/social/warnings',
            ],
        ];
    }

    /**
     * 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 (!addon_installed('cns_warnings')) {
            return null;
        }

        require_lang('cns');
        require_lang('cns_warnings');
        require_code('locations');

        $ret = [
            'recorded_punishments' => [
                'label' => do_lang_tempcode('WARNINGS'),
                'category' => 'moderation',
                'filters' => [
                    'recorded_punishments__month_range' => new CMSStatsDateMonthRangeFilter('recorded_punishments__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'recorded_punishments__country' => new CMSStatsListFilter('recorded_punishments__country', do_lang_tempcode('VISITOR_COUNTRY'), find_countries()),
                    'recorded_punishments__reason' => new CMSStatsTextFilter('recorded_punishments__reason', do_lang_tempcode('REASON'), ''),
                ],
                'pivot' => new CMSStatsDatePivot('recorded_punishments__pivot', $this->get_date_pivots(!$for_kpi)),
            ],
            'recorded_punishment_reasons' => [
                'label' => do_lang_tempcode('WARNINGS_BY_REASON'),
                'category' => 'moderation',
                'filters' => [
                    'recorded_punishment_reasons__month_range' => new CMSStatsDateMonthRangeFilter('recorded_punishment_reasons__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'recorded_punishment_reasons__country' => new CMSStatsListFilter('recorded_punishment_reasons__country', do_lang_tempcode('VISITOR_COUNTRY'), find_countries()),
                ],
                'pivot' => null,
            ],
        ];
        if (has_geolocation_data()) {
            $ret['recorded_punishment_countries'] = [
                'label' => do_lang_tempcode('_COUNTRIES', do_lang_tempcode('WARNINGS')),
                'category' => 'moderation',
                'filters' => [
                    'recorded_punishment_countries__month_range' => new CMSStatsDateMonthRangeFilter('recorded_punishment_countries__month_range', do_lang_tempcode('DATE_RANGE'), null, $for_kpi),
                    'recorded_punishment_countries__reason' => new CMSStatsTextFilter('recorded_punishment_countries__reason', do_lang_tempcode('REASON'), ''),
                ],
                'pivot' => null,
            ];
        }

        return $ret;
    }

    /**
     * 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();

        $max = 1000;
        $start = 0;

        $date_pivots = $this->get_date_pivots();

        $query = 'SELECT w_time,w_explanation,m_ip_address FROM ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_warnings w JOIN ' . $GLOBALS['FORUM_DB']->get_table_prefix() . 'f_members m ON m.id=w.w_member_id  WHERE ';
        $query .= 'w_time>=' . strval($start_time) . ' AND ';
        $query .= 'w_time<=' . strval($end_time);
        $query .= ' ORDER BY w_time';
        do {
            $rows = $GLOBALS['FORUM_DB']->query($query, $max, $start);
            foreach ($rows as $row) {
                $timestamp = $row['w_time'];
                $timestamp = tz_time($timestamp, $server_timezone);

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

                $country = geolocate_ip($row['m_ip_address']);
                if ($country === null) {
                    $country = '';
                }

                $explanation = $row['w_explanation'];

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

                    if (!isset($data_buckets['recorded_punishments'][$month][$pivot][$pivot_value][$country][$explanation])) {
                        $data_buckets['recorded_punishments'][$month][$pivot][$pivot_value][$country][$explanation] = 0;
                    }
                    $data_buckets['recorded_punishments'][$month][$pivot][$pivot_value][$country][$explanation]++;
                }

                if (!isset($data_buckets['recorded_punishment_reasons'][$month][''][$country][$explanation])) {
                    $data_buckets['recorded_punishment_reasons'][$month][''][$country][$explanation] = 0;
                }
                $data_buckets['recorded_punishment_reasons'][$month][''][$country][$explanation]++;

                if (has_geolocation_data()) {
                    if (!isset($data_buckets['recorded_punishment_countries'][$month][''][$country][$explanation])) {
                        $data_buckets['recorded_punishment_countries'][$month][''][$country][$explanation] = 0;
                    }
                    $data_buckets['recorded_punishment_countries'][$month][''][$country][$explanation]++;
                }
            }

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

                        foreach ($__ as $country => $___) {
                            if ((!empty($filters[$bucket . '__country'])) && ($filters[$bucket . '__country'] != $country)) {
                                continue;
                            }

                            foreach ($___ as $explanation => $total_punishments) {
                                if ((!empty($filters[$bucket . '__reason'])) && ($filters[$bucket . '__reason'] != $explanation)) {
                                    continue;
                                }

                                if (!isset($data[$pivot_value])) {
                                    $data[$pivot_value] = 0;
                                }

                                $data[$pivot_value] += $total_punishments;
                            }
                        }
                    }
                }

                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('COUNT_NEW'),
                ];

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

                $data = [];

                $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 $country => $___) {
                        if ((!empty($filters[$bucket . '__country'])) && ($filters[$bucket . '__country'] != $country)) {
                            continue;
                        }

                        foreach ($___ as $explanation => $total_punishments) {
                            if (!isset($data[$explanation])) {
                                $data[$explanation] = 0;
                            }

                            $data[$explanation] += $total_punishments;
                        }
                    }
                }

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

            case 'recorded_punishment_countries':
                require_code('locations');

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

                $data = [];

                $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 $country => $total_punishments) {
                        $_country = find_country_name_from_iso($country);
                        if ($_country === null) {
                            $_country = do_lang('OTHER');
                        }

                        if (!isset($data[$_country])) {
                            $data[$_country] = 0;
                        }
                        $data[$_country] += $total_punishments;
                    }
                }

                return [
                    'type' => self::GRAPH_BAR_CHART,
                    'data' => $data,
                    'x_axis_label' => do_lang_tempcode('COUNTRY'),
                    'y_axis_label' => do_lang_tempcode('COUNT_TOTAL'),
                    'limit_bars' => true,
                ];
        }

        fatal_exit(do_lang_tempcode('INTERNAL_ERROR', escape_html('73576d1294dd5e51bbdc119f44fa72fa')));
    }
}
