<?php

/**
 * @package JoomShopping for Joomla!
 * @subpackage payment
 * @author YooMoney
 * @copyright Copyright (C) 2025 YooMoney. All rights reserved.
 */

namespace YooMoney\Helpers;

use JDatabaseDriver;
use parseString;
use YooKassa\Model\Payment\PaymentInterface;
use YooKassa\Model\Refund\RefundInterface;

/**
 * Класс методов для запросов в БД
 */
class DatabaseHelper
{
    /** @var JDatabaseDriver Драйвер для работы с БД */
    private $_db;

    /**
     * DatabaseHelper конструктор.
     */
    public function __construct()
    {
        $this->_db = \JFactory::getDbo();
    }

    public function getPmConfig($paymentMethod = 'pm_yoomoney')
    {
        $query = $this->_db->getQuery(true);
        $query->select('payment_params')
            ->from('#__jshopping_payment_method')
            ->where(
                $this->_db->quoteName('payment_class') . ' = \'' . $paymentMethod . '\''
            );
        $this->_db->setQuery($query);
        $params = $this->_db->loadResult();

        return $this->parsePaymentParams($params);
    }

    private function parsePaymentParams($params)
    {
        if ($this->getJoomlaVersion() === 4) {
            return (array)json_decode($params, true);
        }

        return (new parseString($params))->parseStringToParams();
    }

    /**
     * @return int
     */
    private function getJoomlaVersion()
    {
        $version = (version_compare(JVERSION, '3.0', '<') == 1) ? 2 : 3;
        return (version_compare(JVERSION, '4.0', '<') == 1) ? $version : 4;
    }

    /**
     * @param string|null $status
     * @param string|null $isPaid
     * @param string|null $currency
     * @return mixed [total, count]
     */
    public function getSuccessPaymentStat($status = 'succeeded', $isPaid = 'Y', $currency = 'RUB')
    {
        $query = $this->_db->getQuery(true);

        $query->select('COUNT(`payment_id`) AS count, SUM(`amount`) as total')
            ->from('#__yoomoney_payments')
            ->where([
                $this->_db->quoteName('status') . " = '$status'",
                $this->_db->quoteName('paid') . " = '$isPaid'",
                $this->_db->quoteName('currency') . " = '$currency'",
            ]);
        $this->_db->setQuery($query);
        return $this->_db->loadAssoc();
    }
}
