<?php

/**

 * @author    Martin Brampton
 * @contact   martin@remository.com
 * @copyright Copyright (C) 2025 Martin Brampton All rights reserved.
 * @license   GNU/GPL v2 http://www.gnu.org/licenses/gpl-2.0.html

 */// no direct access
defined('_JEXEC') or die;

defined ('VMCUSTOM_USERPOINTS_DEBUG') OR define ('VMCUSTOM_USERPOINTS_DEBUG', JPATH_SITE.'/up-vm.txt' );

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;

if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
    file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Loaded VmUserPoints\n", FILE_APPEND);
}

if (!class_exists('vmCustomPlugin')) {
    require(VMPATH_PLUGINS . '/vmcustomplugin.php');
}
if (!class_exists('vmCustomPlugin')) {
    Factory::getApplication()->enqueueMessage(Text::_('PLG_VM_USERPOINTS_ERROR_LOADING_CUSTOM_PLUGIN'), 'error');
}

class plgVmCustomVmuserpoints extends vmCustomPlugin {

    protected $db = null;

    public function __construct(& $subject, $config) {
        parent::__construct($subject, $config);
        $this->db = Factory::getDBo();
        if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
            file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Completed constructor\n", FILE_APPEND);
        }
    }

    public function plgVmOnUpdateOrderPayment($orders, $old_order_status) {
        if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
            file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Call to plgVmOnUpdateOrderPayment {$orders->virtuemart_user_id}, {$orders->virtuemart_order_id}\n", FILE_APPEND);
        }

        if (!class_exists(UserPoints::class)) {
            Factory::getApplication()->enqueueMessage(Text::_('PLG_VM_USERPOINTS_ERROR_LOADING_USERPOINTS'), 'error');
            return false;
        }
        if (1 == intval($this->params->get('status'))) {
            // Order Status Change to
            if ('S' == $orders->order_status) {
                $this->adjustpoints(true, $orders->virtuemart_user_id, $orders->virtuemart_order_id);
            }
        }
        //when order is cancelled or refund restore points
        $cancelled = $orders->order_status == "X";
        $refunded = $orders->order_status == "R";
        if ($cancelled || $refunded) {
            $this->adjustpoints(false, $orders->virtuemart_user_id, $orders->virtuemart_order_id);
        }
        return;
    }

    public function plgVmConfirmedOrder($cart, $order) {
        if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
            file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Call to plgVmConfirmedOrder {$order->id}\n", FILE_APPEND);
        }
        if (!class_exists(UserPoints::class)) {
            Factory::getApplication()->enqueueMessage(Text::_('PLG_VM_USERPOINTS_ERROR_LOADING_USERPOINTS'), 'error');
            return false;
        }
        $userid = (int) UserPoints::getUser()->id;
        if (intval($this->params->get('status')) == 0) {
            $this->db->setQuery("SELECT virtuemart_order_id FROM #__virtuemart_orders WHERE virtuemart_user_id=$userid AND virtuemart_order_id = (select MAX(virtuemart_order_id) from #__virtuemart_orders)");
            $this->adjustpoints(true, $userid, $this->db->loadResult());
        }
    }

    function adjustpoints(bool $addpoints, int $userid, int $orderid) {
        if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
            file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Call to adjustpoints $addpoints, $userid, $orderid\n", FILE_APPEND);
        }

        $pointsperunit = $this->params->get('pointsperunit', "1.00");
        $inctax = (1 == intval($this->params->get('shiptax'))) ? "order_total" : "order_salesPrice";
        $this->db->setQuery("SELECT `$inctax` FROM `#__virtuemart_orders` "
            . "WHERE `virtuemart_user_id` = $userid AND `virtuemart_order_id` = $orderid");
        $price = $this->db->loadResult();
        $points = (float) bcmul($price, $pointsperunit, 10);
        if (!$addpoints) {
            $points = -$points;
        }
        $keyreference = UserPoints::buildKeyreference('up_vm_order', $orderid);
        UserPoints::newpoints('up_vm_order', '', $keyreference, '', $points);
        if (defined ('VMCUSTOM_USERPOINTS_DEBUG')) {
            file_put_contents(VMCUSTOM_USERPOINTS_DEBUG, "Called UserPoints::newpoints $keyreference, $points\n", FILE_APPEND);
        }
    }
}
