<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2016 - Bernard Gilly - Adrien Roussel
 * @license : GNU/GPL
 * @Website : https://remository.com
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

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

function payment_update($tid) {
    if (!file_exists(JPATH_ADMINISTRATOR . '/components/com_payage/api.php')) {
        Factory::getApplication()->enqueueMessage(Text::_('COM_PAYAGE_TEST_NOT_INSTALLED'));
        return;
    }
    require_once JPATH_ADMINISTRATOR . '/components/com_payage/api.php';
    $result = \PayageApi::get_payment_data($tid);
    if (isset($result->app_transaction_details[1])) {
        $detail = new PointsDetails((int) $result->app_transaction_details[1]);
    }
    if (!isset($detail) OR !$detail->id OR 'sysplgup_buypoints' != $detail->rule_id OR $tid != $detail->keyreference) {
        Factory::getApplication()->enqueueMessage(Text::_('COM_PAYAGE_INTERNAL_ERROR'));
        return;
    }
    Factory::getLanguage()->load( 'com_userpoints', JPATH_SITE);
    if (LAPG_STATUS_SUCCESS == $result->pg_status_code) {
        $params = ComponentHelper::getParams('com_userpoints');
        $detail->points = $result->gross_amount * (float) $params->get('Points_per_unit',1.0);
        $detail->insert_date = SQL::datetimeSQL();
        $detail->datareference = Text::_('AUP_LAPG_STATUS_SUCCESS');
        $detail->enabled = 1;
        $detail->approved = 1;
        $detail->save();
    }
    elseif (LAPG_STATUS_REFUNDED == $result->pg_status_code) {
        $detail->id = 0;
        $detail->points = -$detail->points;
        $detail->insert_date = SQL::datetimeSQL();
        $detail->datareference = Text::_('AUP_LAPG_STATUS_REFUNDED');
        $detail->save();
    }
    elseif (LAPG_STATUS_FAILED == $result->pg_status_code) {
        $detail->points = 0.0;
        $detail->insert_date = SQL::datetimeSQL();
        $detail->datareference = Text::_('AUP_LAPG_STATUS_FAILED');
        $detail->enabled = 1;
        $detail->save();
    }
}
