<?php

/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
 *
 * http://www.ec-cube.co.jp/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Customize\Controller;

use Eccube\Controller\AbstractController;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Eccube\Form\Type\Front\EntryType;
use Eccube\Repository\CustomerRepository;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;

use Eccube\Common\EccubeConfig;
use Eccube\Entity\BaseInfo;
use Eccube\Entity\Customer;
use Eccube\Entity\MailHistory;
use Eccube\Repository\BaseInfoRepository;
use Eccube\Repository\MailHistoryRepository;


class CustomizeMypageChangeController extends AbstractController
{
    /**
     * @var TokenStorage
     */
    protected $tokenStorage;

    /**
     * @var CustomerRepository
     */
    protected $customerRepository;

    /**
     * @var EncoderFactoryInterface
     */
    protected $encoderFactory;
    
    /**
     * @var BaseInfoRepository
     * 2020.11 追加
     */
    protected $baseInfoRepository;
    
    /**
     * @var \Swift_Mailer
     * 2020.11 追加
     */
    protected $mailer;

    public function __construct(
        CustomerRepository $customerRepository,
        EncoderFactoryInterface $encoderFactory,
        TokenStorageInterface $tokenStorage,
        BaseInfoRepository $baseInfoRepository, // 2020.11
        \Swift_Mailer $mailer //2020.11
    ) {
        $this->customerRepository = $customerRepository;
        $this->encoderFactory = $encoderFactory;
        $this->tokenStorage = $tokenStorage;
        $this->baseInfoRepository = $baseInfoRepository;
        $this->mailer = $mailer;
    }

    /**
     * 会員情報編集画面.
     *
     * @Route("/mypage/change", name="mypage_change")
     * @Template("Mypage/change.twig")
     */
    public function index(Request $request)
    {
        $Customer = $this->getUser();
        $LoginCustomer = clone $Customer;
        $this->entityManager->detach($LoginCustomer);

        $previous_password = $Customer->getPassword();
        $Customer->setPassword($this->eccubeConfig['eccube_default_password']);

        /* @var $builder \Symfony\Component\Form\FormBuilderInterface */
        $builder = $this->formFactory->createBuilder(EntryType::class, $Customer);

        $event = new EventArgs(
            [
                'builder' => $builder,
                'Customer' => $Customer,
            ],
            $request
        );

        $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_CHANGE_INDEX_INITIALIZE, $event);
        
        // 変更前の会員情報を退避　2020.11
        $OriginalCustomer = clone $Customer;    

        /* @var $form \Symfony\Component\Form\FormInterface */
        $form = $builder->getForm();
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            log_info('会員編集開始');

            if ($Customer->getPassword() === $this->eccubeConfig['eccube_default_password']) {
                $Customer->setPassword($previous_password);
            } else {
                $encoder = $this->encoderFactory->getEncoder($Customer);
                if ($Customer->getSalt() === null) {
                    $Customer->setSalt($encoder->createSalt());
                }
                $Customer->setPassword(
                    $encoder->encodePassword($Customer->getPassword(), $Customer->getSalt())
                );
            }
            $this->entityManager->flush();

            log_info('会員編集完了');

            // 会員情報変更時メール送信 2020.11 追加
            $this->sendChangeMypageMail($LoginCustomer, $Customer);
            
            $event = new EventArgs(
                [
                    'form' => $form,
                    'Customer' => $Customer,
                ],
                $request
            );
            $this->eventDispatcher->dispatch(EccubeEvents::FRONT_MYPAGE_CHANGE_INDEX_COMPLETE, $event);

            return $this->redirect($this->generateUrl('mypage_change_complete'));
        }

        $this->tokenStorage->getToken()->setUser($LoginCustomer);

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

    /**
     * 会員情報編集完了画面.
     *
     * @Route("/mypage/change_complete", name="mypage_change_complete")
     * @Template("Mypage/change_complete.twig")
     */
    public function complete(Request $request)
    {
        return [];
    }
    
    /**
     * 「お名前」「お名前（フリガナ）」「郵便番号」「住所」「メールアドレス」「携帯メールアドレス」「電話番号」「FAX」が変更されたら
     *  管理者にメールを送る  2020.11
     *
     */
    public function sendChangeMypageMail(\Eccube\Entity\Customer $OriginCustomer, \Eccube\Entity\Customer $Customer)
    {
        $mailfg = false;
        
        if (($OriginCustomer->getName01() != $Customer->getName01()) 
						|| ($OriginCustomer->getName02() != $Customer->getName02())
						|| ($OriginCustomer->getKana01() != $Customer->getKana01())
						|| ($OriginCustomer->getKana02() != $Customer->getKana02())
						|| ($OriginCustomer->getPostalCode() != $Customer->getPostalCode())
						|| ($OriginCustomer->getPref() != $Customer->getPref())
						|| ($OriginCustomer->getAddr01() != $Customer->getAddr01())
						|| ($OriginCustomer->getAddr02() != $Customer->getAddr02())
						|| ($OriginCustomer->getEmail() != $Customer->getEmail())
						|| ($OriginCustomer->getPhoneNumber() != $Customer->getPhoneNumber())
						) {						
							$mailfg = true;
        }        
        
        if ($mailfg) {
            $BaseInfo = $this->baseInfoRepository->get();

            // 以下メール本文 「\n」は改行文字  
            $body = date('Y年m月d日H時i分').'  会員登録情報が変更されました。'."\n"."\n";
            $body .= '【会員ＩＤ】 '. $Customer->getId()."\n";
            $body .= '【お名前】 '. $Customer->getName01()." ".$Customer->getName02()."\n";
            $body .= '【お名前(フリガナ)】 '.$Customer->getKana01()." ".$Customer->getKana02()."\n";
            $body .= '【郵便番号】 '.$Customer->getPostalCode()."\n";
            $body .= '【住所】 '.$Customer->getPref()->getName().$Customer->getAddr01().$Customer->getAddr02()."\n";
            $body .= '【メールアドレス】 '.$Customer->getEmail()."\n";
            $body .= '【電話番号】 '.$Customer->getPhoneNumber()."\n";
            
            //dump($body);exit;

            $message = (new \Swift_Message())
                ->setSubject('['.$BaseInfo->getShopName().'] '.'会員登録情報が変更されました')
                ->setFrom([$BaseInfo->getEmail01() => $BaseInfo->getShopName()])
                ->setTo($BaseInfo->getEmail01())
                ->setReplyTo($BaseInfo->getEmail03())
                ->setReturnPath($BaseInfo->getEmail04())
                ->setBody($body);

            $event = new EventArgs(
                [
                    'message' => $message,
                    'Customer' => $Customer,
                    'BaseInfo' => $BaseInfo,
                    'email' => $BaseInfo->getEmail01(),
                ],
                null
            );
            $count = $this->mailer->send($message);

            log_info('管理者宛会員情報変更メール送信完了', ['customer_id' => $Customer->getId()]);
        
        }
        
        return [];
    }
}
