<?php

namespace Plugin\SendAllMails4\Controller\Admin;

use Eccube\Controller\AbstractController;
use Plugin\SendAllMails4\Form\Type\Admin\ConfigType;
use Plugin\SendAllMails4\Repository\ConfigRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

use Eccube\Entity\MailHistory;
use Eccube\Entity\MailTemplate;
use Eccube\Form\Type\Admin\OrderMailType;
use Eccube\Repository\MailHistoryRepository;
use Eccube\Repository\OrderRepository;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Service\MailService;
use Eccube\Repository\ShippingRepository;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ConfigController extends AbstractController
{
    /**
     * @var ConfigRepository
     */
    protected $configRepository;

    /**
     * ConfigController constructor.
     *
     * @param ConfigRepository $configRepository
     */
    public function __construct(
        ConfigRepository $configRepository,
        BaseInfoRepository $baseInfoRepository,
        \Swift_Mailer $mailer,
        MailService $mailService,
        MailHistoryRepository $mailHistoryRepository,
        ShippingRepository $shippingRepository,
        OrderRepository $orderRepository
    )
    {
        $this->configRepository = $configRepository;
        $this->BaseInfo = $baseInfoRepository->get();
        $this->mailer = $mailer;
        $this->mailService = $mailService;
        $this->mailHistoryRepository = $mailHistoryRepository;
        $this->shippingRepository = $shippingRepository;
        $this->orderRepository = $orderRepository;
    }

    /**
     * @Route("/%eccube_admin_route%/send_all_mails4/config", name="send_all_mails4_admin_config")
     * @Template("@SendAllMails4/admin/config.twig")
     */
    public function index(Request $request)
    {
        $Config = $this->configRepository->get();
        $form = $this->createForm(ConfigType::class, $Config);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $Config = $form->getData();
            $this->entityManager->persist($Config);
            $this->entityManager->flush($Config);
            $this->addSuccess('登録しました。', 'admin');

            return $this->redirectToRoute('send_all_mails4_admin_config');
        }

        return [
            'form' => $form->createView(),
        ];
    }



    /**
     * @Route("/%eccube_admin_route%/send_all_mails4/mail/{ids}", name="send_all_mails4_admin_mail")
     * @Template("@SendAllMails4/admin/mail.twig")
     */
    public function mail(Request $request, $ids)
    {
        // たぶん正しくはない
        $Orders = [];
        foreach(explode(',', $ids) as $id) {
            $Shipping = $this->shippingRepository->find($id);
            if (null === $Shipping) {
                throw new NotFoundHttpException();
            }
            $Orders[] = $Shipping->getOrder();
        }
        $Order = $Orders[0];

        $builder = $this->formFactory->createBuilder(OrderMailType::class, [], ['add_form' => true]);

        $form = $builder->getForm();
        
        $complete_flg = false; // 完了時判定用

        if ('POST' === $request->getMethod()) {
            $form->handleRequest($request);

            $mode = $request->get('mode');


            $body = null;
            // テンプレート変更の場合は. バリデーション前に内容差し替え.
            switch ($mode) {
                case 'change':
                    if ($form->get('template')->isValid()) {
                        /** @var $data \Eccube\Entity\MailTemplate */
                        $MailTemplate = $form->get('template')->getData();
                        $data = $form->getData();

                        if ($MailTemplate) {
                            $twig = $MailTemplate->getFileName();
                            if (!$twig) {
                                $twig = 'Mail/order.twig';
                            }

                            // 本文確認用
                            $body = $this->createBody($Order, $twig);
                        }

                        $form = $builder->getForm();
                        $form->get('template')->setData($MailTemplate);
                        if ($MailTemplate) {
                            $form->get('mail_subject')->setData($MailTemplate->getMailSubject());
                        }
                        $form->get('tpl_data')->setData($body);
                    }
                    break;
                case 'confirm':
                    if ($form->isValid()) {
                        $builder->setAttribute('freeze', true);
                        $builder->setAttribute('freeze_display_text', false);
                        $form = $builder->getForm();
                        $form->handleRequest($request);

                        return $this->render('@SendAllMails4/admin/mail_confirm.twig', [
                            'form' => $form->createView(),
                            //'Order' => $Order,
                            'Orders' => $Orders,
                            'ids' => $ids,
                        ]);
                    }
                    break;
                case 'complete':
                    if ($form->isValid()) {
                      
                        // 編集した部分を切り出す　2020.12
                        // 「-*-*-*-*-*-*-*-*-*-*-」で挟まれた部分のみ編集可能とする
                        $MailTpl_data = $form->get('tpl_data')->getData();
                        $changed_tpl_data = explode("-*-*-*-*-*-*-*-*-*-*-", $MailTpl_data);
                      
                        $data = $form->getData();
                        $MailTemplate = $form->get('template')->getData();
                        $twig = '';
                        if ($MailTemplate) {
                            $twig = $MailTemplate->getFileName();
                        }
                        if (!$twig) {
                            $twig = 'Mail/order.twig';
                        }

                        $success = 0;
                        $failedMail = [];
                        foreach($Orders as $Order) {
                            if ($form->get('message')->getData()) {
                                $Order->setCompleteMailMessage($form->get('message')->getData());
                            }

                            $body = $this->createBody($Order, $twig);

                            // 編集した部分を入れ替える　2020.12
                            if (count($changed_tpl_data)> 1) {
                                $body = $this->changeBody($changed_tpl_data[1], $body);
                            }

                            $message = (new \Swift_Message())
                                ->setSubject('['.$this->BaseInfo->getShopName().'] '.$data['mail_subject'])
                                ->setFrom([$this->BaseInfo->getEmail01() => $this->BaseInfo->getShopName()])
                                ->setTo([$Order->getEmail()])
                                ->setBcc($this->BaseInfo->getEmail01())
                                ->setReplyTo($this->BaseInfo->getEmail03())
                                ->setReturnPath($this->BaseInfo->getEmail04())
                                ->setBody($body);

                        
                            if ($this->mailer->send($message)) {
                                // 送信履歴を保存.
                                $MailHistory = new MailHistory();
                                $MailHistory
                                    ->setMailSubject($message->getSubject())
                                    ->setMailBody($message->getBody())
                                    ->setSendDate(new \DateTime())
                                    ->setOrder($Order);

                                $this->entityManager->persist($MailHistory);
                                $this->entityManager->flush($MailHistory);
                                $success++;
                            } else {
                                $failedMail[] = $Order->getEmail();
                            }
                            
                        }

                        $this->addSuccess('メールを送信しました。' . $success . '/' . count($Orders) . "件", 'admin');

                        if (count($failedMail) > 0) {
                            $this->addError('[送信失敗アドレス]'.implode(',', $failedMail), 'admin');
                        }

                        //return $this->redirectToRoute('admin_order');
                        $complete_flg = true;
                        
                    }
                    break;
                default:
                    break;
            }
        }

        return [
            'form' => $form->createView(),
            'Orders' => $Orders,
            'ids' => $ids,
            //'MailHistories' => $MailHistories,
            'complete_flg' => $complete_flg, // 完了時判定用 2020.12
        ];
    }


    protected function createBody($Order, $twig = 'Mail/order.twig')
    {
        return $this->renderView($twig, [
            'Order' => $Order,
        ]);
    }
  
    protected function changeBody($changed_str, $template_body)
    {
        $changed_tpl_data = explode("-*-*-*-*-*-*-*-*-*-*-", $template_body);
        
        if (count($changed_tpl_data)> 1) {        
            $body = $changed_tpl_data[0].$changed_str.$changed_tpl_data[2];
        } else {
            // twig に「-*-*-*-*-*-*-*-*-*-*-」がない場合は変更しない
            $body = $template_body;
        }
       
        return $body;
    }
}
