<?php
/**
 * 2007-2021 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <contact@prestashop.com>
 * @copyright 2007-2021 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License
 *            (AFL 3.0) International Registered Trademark & Property of
 *            PrestaShop SA
 */

// @codingStandardsIgnoreStart
/* @noinspection AutoloadingIssuesInspection */
/* @noinspection PhpMultipleClassDeclarationsInspection */
/* @noinspection PhpIllegalPsrClassPathInspection */
/* @noinspection PhpDeprecationInspection */
/* @noinspection ReturnTypeCanBeDeclaredInspection */
// @codingStandardsIgnoreEnd

/**
 * BO controller for transactions.
 */
class AdminAddonpaymentsTransactionsController extends ModuleAdminController
{
    public function __construct()
    {
        $this->bootstrap = true;
        $this->table = 'addonpayments_transactions';
        $this->className = 'Transactions';
        $this->lang = false;
        $this->actions = [];
        $this->explicitSelect = true;
        $this->allow_export = true;

        parent::__construct();
        $dbPrefix = _DB_PREFIX_;

        $this->identifier = "id_transaction";
        $this->_select .= " a.`payFrexTransactionId`, `o`.`reference`, `a`.`currency`, `a`.`operationType`, UPPER(`a`.`paymentSolution`) AS `paymentSolution`, `a`.`status`, (SELECT COUNT(1) FROM `{$dbPrefix}addonpayments_transactions` b WHERE b.`payFrexTransactionId` = a.`payFrexTransactionId`) AS `numberOfOperations` ";
        $this->_join .= " LEFT JOIN `{$dbPrefix}orders` o ON `a`.`id_order` = `o`.`id_order` ";
        $this->_where .= " AND a.`lastOp` = 1 ";
        $this->_defaultOrderBy = "a.payFrexTransactionId";
        $this->_defaultOrderWay = "DESC";
        $this->fields_list = [
            'payFrexTransactionId' => [
                'title' => $this->l('Transaction'),
                'callback' => 'setOperationCount',
            ],
            'reference' => [
                'title' => $this->l('Order'),
                'orderby' => false,
            ],
            'amount' => ['title' => $this->l('Amount')],
            'currency' => [
                'title' => $this->l('Currency'),
                'type' => 'select',
                'list' => $this->getCurrencies(),
                'filter_type' => 'string',
                'filter_key' => 'a!currency',
                'orderby' => false,
            ],
            'operationType' => [
                'title' => $this->l('Operation type'),
                'type' => 'select',
                'list' => $this->getOperationTypes(),
                'filter_type' => 'string',
                'filter_key' => 'a!operationType',
                'orderby' => false,
            ],
            'paymentSolution' => [
                'title' => $this->l('Payment solution'),
                'type' => 'select',
                'list' => $this->getPaymentSolutions(),
                'filter_type' => 'string',
                'filter_key' => 'a!paymentSolution',
                'orderby' => false,
            ],
            'status' => [
                'title' => $this->l('Status'),
                'type' => 'select',
                'list' => $this->getStatuses(),
                'filter_type' => 'string',
                'filter_key' => 'a!status',
                'orderby' => false,
            ],
            'createdAt' => ['title' => $this->l('Created')],
            'updatedAt' => ['title' => $this->l('Last update')],
        ];
        $this->actions_available = [];
        $this->_use_found_rows = false;
    }

    public function initToolbar()
    {
        parent::initToolbar();
        unset($this->toolbar_btn['new']);
    }

    public function getList(
        $id_lang,
        $order_by = null,
        $order_way = null,
        $start = 0,
        $limit = null,
        $id_lang_shop = false
    ) {
        parent::getList(
            $id_lang,
            $order_by,
            $order_way,
            $start,
            $limit,
            $id_lang_shop
        );
        $this->_listTotal = count($this->_list);
    }

    /**
     * Get currency filter values.
     */
    private function getCurrencies(): array
    {
        $currencies = array_column(Currency::getCurrencies(), 'name', 'iso_code');

        return array_map(static function ($item) {
            return strtoupper($item);
        }, $currencies);
    }

    /**
     * Get operation type filter values.
     */
    private function getOperationTypes(): array
    {
        $operations = Transactions::getOperationTypes();

        if (!empty($operations)) {
            $copy = [];
            foreach ($operations as $operation) {
                $copy[$operation['operationType']] = $this->l($operation['operationType']);
            }
            $operations = $copy;
        }

        return $operations;
    }

    /**
     * Get payment solution filter values.
     */
    private function getPaymentSolutions(): array
    {
        $operations = Transactions::getPaymentSolutions();

        if (!empty($operations)) {
            $copy = [];
            foreach ($operations as $operation) {
                $copy[$operation['paymentSolution']] = strtoupper($operation['paymentSolution']);
            }
            $operations = $copy;
        }

        return $operations;
    }

    /**
     * Get status filter values.
     */
    private function getStatuses(): array
    {
        $operations = Transactions::getStatuses();

        if (!empty($operations)) {
            $copy = [];
            foreach ($operations as $operation) {
                $copy[$operation['status']] = $operation['status'];
            }
            $operations = $copy;
        }

        return $operations;
    }

    /**
     * Show operation count badge next to transaction ID.
     */
    public static function setOperationCount($echo, $tr): string
    {
        $count = $tr['numberOfOperations'] ?? 1;

        return sprintf(
            '<span class="badge"
                              title="%s">%d</span>&nbsp;&nbsp;%s',
            Translate::getAdminTranslation('Number of operations involved in this transaction', __CLASS__),
            $count,
            $echo
        );
    }
}
