<?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\System;
use Admin\Form\SystemForm;
use Admin\Service\SystemManager;
use Doctrine\ORM\EntityManager;
use Laminas\Mvc\I18n\Translator;

class SystemController extends AdminActionController
{

    private $translator;
    private $entityManager;
    private $systemManager;

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

    /**
     * 系统设置
     * @return array|\Laminas\Http\Response|\Laminas\View\Model\ViewModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function indexAction()
    {
        $form = new SystemForm();

        $form->get('website_timezone|base')->setValueOptions($this->adminCommon()->timezoneArray());
        $form->get('email_service_type|email')->setValueOptions(Common::emailServiceType($this->translator));
        $form->get('smtp_check|email')->setValueOptions(Common::generalState($this->translator));
        $form->get('smtp_secure_conn|email')->setValueOptions(Common::smtpSecureConn($this->translator));
        $form->get('sms_service_provider|sms')->setValueOptions(Common::smsServiceProvider($this->translator));
        $form->get('goods_group_price_show|goods')->setValueOptions(Common::userGroupPriceType($this->translator));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if($form->isValid()) {
                $data = $form->getData();
                foreach ($data as $dataKey => $dataValue) {
                    if(in_array($dataKey, ['shop_favicon|base', 'shop_logo|base'])) {
                        $dataValue = str_replace(Config::PUBLIC_PATH, '', $dataValue['tmp_name']);
                        if(empty($dataValue)) continue;
                    }

                    $where    = explode('|', $dataKey);
                    $oneSystem= $this->entityManager->getRepository(System::class)->findOneBy(['sysName' => $where[0], 'sysType' => $where[1]]);
                    if($oneSystem) {
                        if($oneSystem->getSysBody() != $dataValue) $this->systemManager->editSystem($oneSystem, $dataValue);
                    } else {
                        $this->systemManager->addSystem(['sysName' => $where[0], 'sysBody' => $dataValue, 'sysType' => $where[1]]);
                    }
                }

                //写入配置文件
                $this->createConfig()->createSystem();

                $this->adminCommon()->addOperLog($this->translator->translate('系统设置 修改成功!'), $this->translator->translate('系统设置'));

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

        $system = $this->entityManager->getRepository(System::class)->findBaseSystem();
        $systemArray = [];
        if($system) {
            foreach ($system as $value) {
                $systemArray[$value->getSysName().'|'.$value->getSysType()] = $value->getSysBody();
            }
            $form->setData($systemArray);
        }

        return [
            'form' => $form,
            'sales_service' => $systemArray['sales_service|content'],
            'buy_service'   => $systemArray['buy_service|content']
        ];
    }

}