<?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('Direct Access to ' . basename(__FILE__) . ' is not allowed.');

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

if (!class_exists('vmPSPlugin')) {
    require(VMPATH_PLUGINLIBS . '/vmpsplugin.php');
}

class plgVmPaymentUserpoints extends vmPSPlugin {

    public static $_this = false;

    function __construct(& $subject, $config) {
        parent::__construct($subject, $config);
        $this->_loggable = true;
        $this->tableFields = array_keys($this->getTableSQLFields());
        $this->_tablepkey = 'id';
        $this->_tableId = 'id';

        $varsToPush = array(
            'status_pending' => array('P', 'char'),
            'status_success' => array('C', 'char'),
            'status_canceled' => array('X', 'char'),
            'min_amount' => array(0, 'int'),
            'max_amount' => array(0, 'int'),
            'countries' => array(0, 'char'),
            'points_rate' => array(1, 'int'), // How many points = 1 currency unit
        );

        $this->addVarsToPushCore($varsToPush, 1);
        $this->setConfigParameterable($this->_configTableFieldName, $varsToPush);
    }

    public function getVmPluginCreateTableSQL() {
        return $this->createTableSQL('Payment UserPoints Table');
    }

    function getTableSQLFields() {
        $SQLfields = array(
            'id' => 'int(11) unsigned NOT NULL AUTO_INCREMENT ',
            'virtuemart_order_id' => 'int(11) UNSIGNED',
            'order_number' => 'char(32)',
            'virtuemart_paymentmethod_id' => 'mediumint(1) UNSIGNED',
            'payment_name' => 'char(255) NOT NULL DEFAULT \'\' ',
            'payment_order_total' => 'decimal(15,5) NOT NULL DEFAULT \'0.00000\' ',
            'points_used' => 'int(11) NOT NULL DEFAULT 0',
            'user_id' => 'int(11) UNSIGNED'
        );
        return $SQLfields;
    }

    function plgVmConfirmedOrder($cart, $order) {
        if (!($method = $this->getVmPluginMethod($order['details']['BT']->virtuemart_paymentmethod_id))) {
            return null;
        }
        if (!$this->selectedThisElement($method->payment_element)) {
            return false;
        }

        $user = UserPoints::getUser();
        $userId = $user->id;

        if (!$userId) {
            vmError('User must be logged in to pay with points');
            return false;
        }

        // Calculate points needed
        $orderTotal = $order['details']['BT']->order_total;
        $pointsNeeded = ceil($orderTotal * $method->points_rate);

        // Check if user has enough points
        if (!UserPoints::canAfford('up_vm_payment', '', 0, $pointsNeeded)) {
            vmError('Insufficient points. You need ' . $pointsNeeded . ' points for this order.');
            return false;
        }

        // Deduct points
        $pointsResult = UserPoints::newpoints('up_vm_payment', '', '', 'VirtueMart Order #' . $order['details']['BT']->order_number, -$pointsNeeded);

        if (!$pointsResult) {
            vmError('Failed to deduct points');
            return false;
        }

        // Store transaction data
        $dbValues = array(
            'order_number' => $order['details']['BT']->order_number,
            'payment_name' => $this->renderPluginName($method, $order),
            'virtuemart_paymentmethod_id' => $cart->virtuemart_paymentmethod_id,
            'payment_order_total' => $orderTotal,
            'points_used' => $pointsNeeded,
            'user_id' => $userId
        );

        $this->storePSPluginInternalData($dbValues);

        // Set order status to success
        $new_status = $method->status_success;

        // Simple success message
        $html = '<div class="payment-success">';
        $html .= '<h3>Payment Successful!</h3>';
        $html .= '<p>' . $pointsNeeded . ' points have been deducted from your account.</p>';
        $html .= '</div>';

        return $this->processConfirmedOrderPaymentResponse(1, $cart, $order, $html, $dbValues['payment_name'], $new_status);
    }

    protected function checkConditions($cart, $method, $cart_prices) {
        $user = UserPoints::getUser();
        if (!$user->id) {
            return false; // User must be logged in
        }

        // Check if user has enough points
        $pointsNeeded = ceil($cart_prices['salesPrice'] * $method->points_rate);
        if (!UserPoints::canAfford('up_vm_payment', '', 0, $pointsNeeded)) {
            return false;
        }

        return parent::checkConditions($cart, $method, $cart_prices);
    }

    public function plgVmDisplayListFEPayment(VirtueMartCart $cart, $selected, &$htmlIn) {
        $user = UserPoints::getUser();
        if (!$user->id) {
            return false;
        }

        return $this->displayListFE($cart, $selected, $htmlIn);
    }

    function plgVmOnShowOrderBEPayment($virtuemart_order_id, $payment_method_id) {
        if (!$this->selectedThisByMethodId($payment_method_id)) {
            return null;
        }

        if (!($paymentTable = $this->getDataByOrderId($virtuemart_order_id))) {
            return NULL;
        }

        $html = '<table class="adminlist table">' . "\n";
        $html .= $this->getHtmlHeaderBE();
        $html .= $this->getHtmlRowBE('Payment Name', $paymentTable->payment_name);
        $html .= $this->getHtmlRowBE('Points Used', $paymentTable->points_used);
        $html .= $this->getHtmlRowBE('Order Total', $paymentTable->payment_order_total);
        $html .= '</table>' . "\n";

        return $html;
    }

    // Required plugin methods
    function plgVmOnStoreInstallPaymentPluginTable($jplugin_id) {
        return $this->onStoreInstallPluginTable($jplugin_id);
    }

    public function plgVmOnSelectCheckPayment(VirtueMartCart $cart) {
        return $this->OnSelectCheck($cart);
    }

    public function plgVmOnSelectedCalculatePricePayment(VirtueMartCart $cart, array &$cart_prices, &$cart_prices_name) {
        return $this->onSelectedCalculatePrice($cart, $cart_prices, $cart_prices_name);
    }

    function plgVmOnCheckAutomaticSelectedPayment(VirtueMartCart $cart, array $cart_prices = array()) {
        return $this->onCheckAutomaticSelected($cart, $cart_prices);
    }

    public function plgVmOnShowOrderFEPayment($virtuemart_order_id, $virtuemart_paymentmethod_id, &$payment_name) {
        $this->onShowOrderFE($virtuemart_order_id, $virtuemart_paymentmethod_id, $payment_name);
    }

    function plgVmDeclarePluginParamsPayment($name, $id, &$data) {
        return $this->declarePluginParams('payment', $name, $id, $data);
    }

    function plgVmSetOnTablePluginParamsPayment($name, $id, &$table) {
        return $this->setOnTablePluginParams($name, $id, $table);
    }
}