<?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_points_recalculate_cpf
{
    /**
     * Run the task hook.
     *
     * @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() : ?array
    {
        if (!addon_installed('points')) {
            return null;
        }

        require_code('points');
        require_code('points2');

        // Re-calculate points balance for every member
        $member_id = null;
        do {
            $rows = $GLOBALS['FORUM_DRIVER']->get_next_members($member_id, 100);
            foreach ($rows as $row) {
                $member_id = $GLOBALS['FORUM_DRIVER']->mrow_member_id($row);

                if (is_guest($member_id)) {
                    continue;
                }

                // task_log($this, 'Re-calculating points_balance for member ID ' . strval($member_id), $start, null);

                // Calculate balance by combining received and sent points
                $data = points_ledger_calculate(LEDGER_TYPE_RECEIVED | LEDGER_TYPE_SENT, $member_id);
                list(, $r_points, $r_gift_points) = $data['received'];
                $points_received = ($r_points + $r_gift_points);
                list(, $points_used, ) = $data['sent'];
                $points_balance = @intval($points_received - $points_used);
                $GLOBALS['FORUM_DRIVER']->set_custom_field($member_id, 'points_balance', strval($points_balance));

                // Calculate rank points by combining received and spent points which are marked to affect rank
                $data = points_ledger_calculate(LEDGER_TYPE_RECEIVED | LEDGER_TYPE_SPENT, $member_id, null, ' AND is_ranked=1');
                list(, $r_points, $r_gift_points) = $data['received'];
                $points_received = ($r_points + $r_gift_points);
                list(, $points_spent, $gift_points_spent) = $data['spent'];
                $points_spent = ($points_spent + $gift_points_spent);
                $points_rank = @intval($points_received) - @intval($points_spent);
                $GLOBALS['FORUM_DRIVER']->set_custom_field($member_id, 'points_rank', strval($points_rank));
            }
        } while (count($rows) > 0);

        return null;
    }
}
