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

/**
 * Hook class.
 */
class Hook_task_export_points_overview
{
    /**
     * Run the task hook.
     *
     * @param  TIME $from Date from
     * @param  TIME $to Date to
     * @param  ?string $file_type The file type to export with (null: default)
     * @return ?array A tuple of at least 2: Return mime-type, content (either Tempcode, or a string, or a filename and file-path pair to a temporary file), map of HTTP headers if transferring immediately, map of ini_set commands if transferring immediately (null: show standard success message)
     */
    public function run(int $from, int $to, ?string $file_type = null) : ?array
    {
        if (!addon_installed('points')) {
            return null;
        }

        require_lang('points');
        require_code('points');

        $label = do_lang('POINTS_GAINED_BETWEEN', get_timezoned_date_time($from, false), get_timezoned_date_time($to, false));

        require_code('files_spreadsheets_write');
        if ($file_type === null) {
            $file_type = spreadsheet_write_default();
        }
        $filename = 'points_overview_' . date('Y-m-d', $from) . '--' . date('Y-m-d', $to) . '.' . $file_type;
        $outfile_path = null;
        $sheet_writer = spreadsheet_open_write($outfile_path, $filename);

        $quizzes = [];
        if (addon_installed('quizzes')) {
            require_lang('quiz');
            $quizzes = $GLOBALS['SITE_DB']->query_select('quizzes', ['id', 'q_name', 'q_add_date'], [], 'ORDER BY q_add_date DESC', 100);
        }

        $members = $GLOBALS['FORUM_DRIVER']->get_matching_members('', 10000/*reasonable limit -- works via returning 'most active' first*/);
        $all_usergroups = $GLOBALS['FORUM_DRIVER']->get_usergroup_list();
        foreach ($members as $i => $member) {
            task_log($this, 'Exporting points log row', $i, count($members));

            $member_id = $GLOBALS['FORUM_DRIVER']->mrow_member_id($member);
            $username = $GLOBALS['FORUM_DRIVER']->get_username($member_id, false, USERNAME_DEFAULT_NULL);
            if ($username === null) {
                $username = do_lang('UNKNOWN');
            }
            $email = $GLOBALS['FORUM_DRIVER']->get_member_email_address($member_id);

            $usergroups = '';
            $_usergroups = $GLOBALS['FORUM_DRIVER']->get_members_groups($member_id);
            foreach ($_usergroups as $_usergroup) {
                if ($usergroups != '') {
                    $usergroups .= ', ';
                }
                $usergroups .= $all_usergroups[$_usergroup];
            }

            $points_gained = points_rank($member_id, $to) - points_rank($member_id, $from);
            $points_now = points_rank($member_id);

            $data_point = [];

            $data_point[do_lang('IDENTIFIER')] = $member_id;
            $data_point[do_lang('USERNAME')] = $username;
            $data_point[$label] = $points_gained;
            $data_point[do_lang('POINTS_NOW')] = $points_now;
            $data_point[do_lang('USERGROUPS')] = $usergroups;
            $data_point[do_lang('EMAIL')] = $email;

            if (addon_installed('quizzes')) {
                foreach ($quizzes as $quiz) {
                    $entered = ($GLOBALS['SITE_DB']->query_select_value_if_there('quiz_entries', 'id', ['q_member' => $member_id, 'q_quiz_id' => $quiz['id']]) !== null);
                    $data_point[do_lang('ENTERED_THIS_QUIZ', get_translated_text($quiz['q_name']))] = do_lang($entered ? 'YES' : 'NO');
                }
            }

            $sheet_writer->write_row($data_point);
        }
        $sheet_writer->close();

        $headers = [];
        $headers['Content-Type'] = $sheet_writer->get_mime_type();
        $headers['Content-Disposition'] = 'attachment; filename="' . escape_header($filename) . '"';

        $ini_set = [];
        $ini_set['ocproducts.xss_detect'] = '0';

        return [$sheet_writer->get_mime_type(), [$filename, $outfile_path], $headers, $ini_set];
    }
}
