<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Controller;

use Admin\Data\Common;
use Admin\Data\Config;
use Admin\Entity\Currency;
use Admin\Form\CurrencyForm;
use Admin\Service\CurrencyManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;

class CurrencyController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $currencyManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        CurrencyManager $currencyManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->currencyManager  = $currencyManager;
    }

    /**
     * 货币列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $currencyList = $this->entityManager->getRepository(Currency::class)->findBy([], ['currencyId' => 'ASC']);

        return ['currencyList' => $currencyList];
    }

    /**
     * 添加货币
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $form = new CurrencyForm();
        $form->get('currencyCode')->setValueOptions($this->adminCommon()->currencyArray());
        $form->get('currencyState')->setValueOptions(Common::state($this->translator));

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();

                $numberFormatter = new \NumberFormatter(Config::SHOP_CURRENCY_LOCALE . '@currency=' . $data['currencyCode'], \NumberFormatter::CURRENCY);
                $data['currencySymbol'] = $numberFormatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);

                $this->currencyManager->addCurrency($data);
                $this->createConfig()->createCurrency();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('货币 %s 添加成功!'), $data['currencyName']), $this->translator->translate('货币设置'));

                return $this->redirect()->toRoute('currency');
            }
        }

        return ['form' => $form];
    }

    /**
     * 编辑货币
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $currencyId = (int) $this->params()->fromRoute('id', -1);

        $currencyInfo = $this->entityManager->getRepository(Currency::class)->findOneByCurrencyId($currencyId);
        if($currencyInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该货币信息不存在!'));
            return $this->redirect()->toRoute('currency');
        }

        $form = new CurrencyForm();
        $form->get('currencyCode')->setValueOptions($this->adminCommon()->currencyArray());
        $form->get('currencyState')->setValueOptions(Common::state($this->translator));

        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $numberFormatter = new \NumberFormatter(Config::SHOP_CURRENCY_LOCALE . '@currency=' . $data['currencyCode'], \NumberFormatter::CURRENCY);
                $data['currencySymbol'] = $numberFormatter->getSymbol(\NumberFormatter::CURRENCY_SYMBOL);

                $this->currencyManager->editCurrency($data, $currencyInfo);
                $this->createConfig()->createCurrency();

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('货币 %s 编辑成功!'), $data['currencyName']), $this->translator->translate('货币设置'));

                return $this->redirect()->toRoute('currency');
            }
        } else $form->setData($currencyInfo->valuesArray());

        return ['form' => $form, 'currency' => $currencyInfo];
    }

    /**
     * 删除货币
     * @return \Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->redirect()->toRoute('currency');

        $currencyId = (int) $this->params()->fromRoute('id', -1);
        if($currencyId <= 1) {
            $this->flashMessenger()->addErrorMessage($this->translator->translate('不能删除基础货币!'));
            return $this->redirect()->toRoute('currency');
        }

        $currencyInfo = $this->entityManager->getRepository(Currency::class)->findOneByCurrencyId($currencyId);
        if($currencyInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该货币信息不存在!'));
            return $this->redirect()->toRoute('currency');
        }

        $this->currencyManager->deleteCurrency($currencyInfo);
        $this->createConfig()->createCurrency();

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('货币 %s 删除成功!'), $currencyInfo->getCurrencyName()), $this->translator->translate('货币设置'));

        return $this->adminCommon()->toReferer();
    }
}