<?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_ledger
{
    /**
     * Run the task hook.
     *
     * @param  ?MEMBER $member_id Only export ledgers of the specified member (null: export the entire ledger)
     * @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 $member_id = null, ?string $file_type = null) : ?array
    {
        if (!addon_installed('points')) {
            return null;
        }

        if (!has_privilege(get_member(), 'view_points_ledger')) {
            access_denied('PRIVILEGE', 'view_points_ledger');
        }

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

        // Prepare the file
        require_code('files_spreadsheets_write');
        if ($file_type === null) {
            $file_type = spreadsheet_write_default();
        }
        $filename = 'points_ledger_' . strval(time()) . '.' . $file_type;
        $outfile_path = null;
        $sheet_writer = spreadsheet_open_write($outfile_path, $filename);

        $start = 0;
        $max = 1000;
        $rows = [];
        do {
            // Grab our transactions
            if ($member_id !== null) {
                $rows = $GLOBALS['SITE_DB']->query_select('points_ledger', ['*'], [], ' AND (receiving_member=' . strval($member_id) . ' OR sending_member=' . strval($member_id) . ') ORDER BY date_and_time DESC', $max, $start);
            } else {
                $rows = $GLOBALS['SITE_DB']->query_select('points_ledger', ['*'], [], ' ORDER BY date_and_time DESC', $max, $start);
            }

            // Write data to the file
            foreach ($rows as $row) {
                $data_point = [];
                $data_point[do_lang('IDENTIFIER')] = $row['id'];
                $data_point[do_lang('DATE')] = get_timezoned_date_time($row['date_and_time'], false);
                $data_point[do_lang('GIFT_POINTS')] = $row['amount_gift_points'];
                $data_point[do_lang('POINTS')] = $row['amount_points'];
                $data_point[do_lang('_RANK_POINTS')] = $row['is_ranked'];
                $data_point[do_lang('SENDER')] = $GLOBALS['FORUM_DRIVER']->get_username($row['sending_member'], ($member_id === null), USERNAME_DEFAULT_DELETED);
                $data_point[do_lang('RECIPIENT')] = $GLOBALS['FORUM_DRIVER']->get_username($row['receiving_member'], ($member_id === null), USERNAME_DEFAULT_DELETED);
                $data_point[do_lang('REASON')] = get_translated_text($row['reason']);

                // Anonymous transactions
                if (($member_id !== null) && ($row['anonymous'] == 1) && ($row['sending_member'] != $member_id) && (!has_privilege($member_id, 'trace_anonymous_points_transactions'))) {
                    $data_point[do_lang('SENDER')] = do_lang('ANON');
                }

                if ($row['status'] == LEDGER_STATUS_NORMAL) {
                    $data_point[do_lang('STATUS')] = do_lang('LEDGER_STATUS_0');
                } elseif (($row['linked_ledger_id'] !== null) && ($member_id === null)) { // Only show linked transaction identifiers if we are generating the full (admin) ledger
                    $data_point[do_lang('STATUS')] = do_lang('LEDGER_STATUS_SHORT_' . strval($row['status']), strval($row['linked_ledger_id']));
                } else {
                    $data_point[do_lang('STATUS')] = do_lang('LEDGER_STATUS_SHORT_B_' . strval($row['status']));
                }

                $sheet_writer->write_row($data_point);
            }

            $start += $max;
        } while (count($rows) > 0);

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