<?php

/**
 * @version		3.5.7
 * @package		Joomla
 * @subpackage	EShop
 * @author  	Giang Dinh Truong
 * @copyright	Copyright (C) 2012 Ossolution Team
 * @license		GNU/GPL, see LICENSE.php
 */
// no direct access
defined('_JEXEC') or die();

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

class os_userpoints extends RADPayment {

    /**
     * Process Payment
     *
     * @param   DMSTableOrder  $row
     * @param   array          $data
     */
    public function processPayment($row, $data) {
        // $subscriptionStatus = $this->params->get('subscription_status');

        if (class_exists(UserPoints::class)) {
            Factory::getLanguage()->load('com_userpoints', JPATH_SITE);
            $params = ComponentHelper::getParams('com_userpoints');
            if (!UserPoints::checkRuleEnabled('up_eventbooking_payment')) {
                $this->errorReport(Text::_('AUP_SERVICE_NOT_ACTIVATED'), $row);
            } elseif (UserPoints::canAfford('up_eventbooking_payment', '', '', $data['amount'] * $params->get('Points_per_unit', 1))) {
                UserPoints::newpoints('up_eventbooking_payment', '', '', $data['transaction_id'] . ' - ' . $data['event_title'], -$data['amount'] * $params->get('Points_per_unit', 1));
                $this->paymentMade($row);
            } else {
                $this->errorReport(Text::_('AUP_YOUDONOTHAVEENOUGHPOINTSTOPERFORMTHISOPERATION'), $row);
            }
        } else {
            $this->errorReport('UserPoints is not installed', $row);
        }
    }

    private function errorReport($message, $row) {
        $app = Factory::getApplication();
        $Itemid = $app->input->getInt('Itemid', 0);
        $app->enqueueMessage($message);
        $app->redirect($this->getPaymentFailureUrl($row, $Itemid, true));
    }

    private function paymentMade($row) {
        $app = Factory::getApplication();
        $Itemid = $app->input->getInt('Itemid', 0);
        $this->onPaymentSuccess($row, $row->transaction_id);
        $app->redirect($this->getPaymentCompleteUrl($row, $Itemid));
    }
}
