<?php
 
/*
 
* Plugin Name : CustomerPlus4
 
*
 
* Copyright (C) BraTech Co., Ltd. All Rights Reserved.
 
* http://www.bratech.co.jp/
 
*
 
* For the full copyright and license information, please view the LICENSE
 
* file that was distributed with this source code.
 
*/
 
 
namespace Plugin\CustomerPlus4;
 
 
use Eccube\Event\EccubeEvents;
 
use Eccube\Event\RenderEvent;
 
use Eccube\Event\TemplateEvent;
 
use Eccube\Event\EventArgs;
 
use Eccube\Form\Type\Shopping\CustomerAddressType;
 
use Eccube\Service\OrderHelper;
 
use Plugin\CustomerPlus4\Entity\CustomerItem;
 
use Plugin\CustomerPlus4\Entity\CustomerData;
 
use Plugin\CustomerPlus4\Entity\CustomerDataDetail;
 
use Plugin\CustomerPlus4\Entity\CustomerCustom;
 
use Plugin\CustomerPlus4\Entity\CustomerAddressCustom;
 
use Plugin\CustomerPlus4\Entity\ShippingCustom;
 
use Plugin\CustomerPlus4\Service\CustomerPlusService;
 
use Symfony\Component\DependencyInjection\ContainerInterface;
 
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
 
use Symfony\Component\Form\FormFactoryInterface;
 
use Symfony\Component\HttpFoundation\Session\SessionInterface;
 
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
 
 
class CustomerPlusEvent implements EventSubscriberInterface
 
{
 
    private $container;
 
    private $formFactory;
 
    private $customerPlusService;
 
    private $authorizationChecker;
 
    private $session;
 
    private $orderHelper;
 
 
    public function __construct(
 
            ContainerInterface $container,
 
            FormFactoryInterface $formFactory,
 
            OrderHelper $orderHelper,
 
            SessionInterface $session,
 
            AuthorizationCheckerInterface $authorizationChecker,
 
            CustomerPlusService $customerPlusService
 
            )
 
    {
 
        $this->container = $container;
 
        $this->formFactory = $formFactory;
 
        $this->orderHelper = $orderHelper;
 
        $this->session = $session;
 
        $this->authorizationChecker = $authorizationChecker;
 
        $this->customerPlusService = $customerPlusService;
 
    }
 
 
    /**
 
     * @return array
 
     */
 
    public static function getSubscribedEvents()
 
    {
 
        return [
 
            '@admin/Customer/edit.twig' => 'onTemplateAdminCustomerEdit',
 
            '@admin/Customer/delivery_edit.twig' => 'onTemplateAdminCustomerDeliveryEdit',
 
            '@admin/Order/edit.twig' => 'onTemplateAdminOrderEdit',
 
            '@admin/Order/search_customer.twig' => 'onTemplateAdminOrderSearchCustomer',
 
            '@admin/Order/shipping.twig' => 'onTemplateAdminOrderShipping',
 
            EccubeEvents::ADMIN_ORDER_EDIT_SEARCH_CUSTOMER_BY_ID_COMPLETE => 'hookAdminOrderEditSearchCustomerByIdComplete',
 
            'Shopping/index.twig' => 'onTemplateShoppingIndex',
 
            'Shopping/nonmember.twig' => 'onTemplateShoppingNonmember',
 
            EccubeEvents::FRONT_SHOPPING_NONMEMBER_COMPLETE => 'hookFrontShoppingNonmemberComplete',
 
            EccubeEvents::FRONT_SHOPPING_SHIPPING_COMPLETE => 'hookFrontShoppingShippingComplete',
 
            EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_INITIALIZE => 'hookFrontShoppingShippingEditInitialize',
 
            EccubeEvents::FRONT_SHOPPING_SHIPPING_EDIT_COMPLETE => 'hookFrontShoppingShippingEditComplete',
 
            EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_INITIALIZE => 'hookFrontShoppingShippingMultipleInitialize',
 
            EccubeEvents::FRONT_SHOPPING_SHIPPING_MULTIPLE_COMPLETE => ['hookFrontShoppingShippingMultipleComplete',-10],
 
            EccubeEvents::FRONT_CONTACT_INDEX_COMPLETE => 'hookFrontContactIndexComplete',
 
            EccubeEvents::ADMIN_CUSTOMER_CSV_EXPORT => 'hookAdminCustomerCsvExport',
 
            EccubeEvents::ADMIN_ORDER_CSV_EXPORT_ORDER => 'hookAdminOrderCsvExport',
 
            'Entry/index.twig' => 'insertDatePickerJS',
 
            'Mypage/change.twig' => 'insertDatePickerJS',
 
            'Mypage/delivery_edit.twig' => 'insertDatePickerJS',
 
            'Shopping/shipping_edit.twig' => 'insertDatePickerJS',
 
            'Shopping/shipping_multiple_edit.twig' => 'insertDatePickerJS',
 
            'Contact/index.twig' => 'insertDatePickerJS',
 
        ];
 
    }
 
 
    public function onTemplateAdminCustomerEdit(TemplateEvent $event)
 
    {
 
        $parameters = $event->getParameters();
 
        $source = $event->getSource();
 
 
        $CustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('customer');
 
        $AdminCustomerItems = $this->customerPlusService->getCustomerPlusForm('admin_customer');
 
        foreach($CustomerItems as $key => $CustomerItem){
 
            foreach($AdminCustomerItems as $AdminCustomerItem){
 
                if($CustomerItem->getId() == $AdminCustomerItem->getId())unset($CustomerItems[$key]);
 
            }
 
        }
 
 
        if(preg_match('/\{\%\sfor\sf\sin\sform(\sif|\|filter\(f\s\=\>)\sf\.vars\.eccube\_form\_options\.auto\_render/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Customer/ext_edit.twig');
 
            $replace = $snippet . $search;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
        $parameters['CustomerItems'] = $CustomerItems;
 
        $event->setParameters($parameters);
 
 
        $this->insertDatePickerJSAdmin($event);
 
    }
 
 
    public function onTemplateAdminCustomerDeliveryEdit(TemplateEvent $event)
 
    {
 
        $parameters = $event->getParameters();
 
        $source = $event->getSource();
 
 
        $CustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('shipping');
 
        $AdminCustomerItems = $this->customerPlusService->getCustomerPlusForm('admin_delivery');
 
        foreach($CustomerItems as $key => $CustomerItem){
 
            foreach($AdminCustomerItems as $AdminCustomerItem){
 
                if($CustomerItem->getId() == $AdminCustomerItem->getId())unset($CustomerItems[$key]);
 
            }
 
        }
 
 
        if(preg_match('/\{\%\sfor\sf\sin\sform(\sif|\|filter\(f\s\=\>)\sf\.vars\.eccube\_form\_options\.auto\_render/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Customer/ext_edit.twig');
 
            $replace = $snippet . $search;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
        $parameters['CustomerItems'] = $CustomerItems;
 
        $event->setParameters($parameters);
 
 
        $this->insertDatePickerJSAdmin($event);
 
    }
 
 
    public function onTemplateAdminOrderEdit(TemplateEvent $event)
 
    {
 
        $parameters = $event->getParameters();
 
        $source = $event->getSource();
 
 
        $OrderCustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('order');
 
        $AdminCustomerItems = $this->customerPlusService->getCustomerPlusForm('admin_order');
 
        foreach($OrderCustomerItems as $key => $CustomerItem){
 
            foreach($AdminCustomerItems as $AdminCustomerItem){
 
                if($CustomerItem->getId() == $AdminCustomerItem->getId())unset($OrderCustomerItems[$key]);
 
            }
 
        }
 
 
        $ShippingCustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('admin_delivery');
 
 
        if(preg_match('/\{\{\sform\_errors\(form\.message\)\s\}\}[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Order/ext_order_edit.twig');
 
            $replace = $search . $snippet;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        if(preg_match('/\{\{\sform\_errors\(form\.Shipping\.company_name\)\s\}\}[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Order/ext_shipping_edit.twig');
 
            $replace = $search . $snippet;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
        $parameters['OrderCustomerItems'] = $OrderCustomerItems;
 
        $parameters['ShippingCustomerItems'] = $ShippingCustomerItems;
 
        $event->setParameters($parameters);
 
 
        $twig = '@CustomerPlus4/admin/Order/copy_customer_js.twig';
 
        $event->addSnippet($twig);
 
 
        $this->insertDatePickerJSAdmin($event);
 
    }
 
 
    public function onTemplateAdminOrderSearchCustomer(TemplateEvent $event)
 
    {
 
        $parameters = $event->getParameters();
 
 
        $CustomerCustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('admin_customer');
 
 
        $source = $event->getSource();
 
        if(preg_match('/val\(data\[\'company_name\'\]\)\;/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Order/insert_customer_js.twig');
 
 
            $replace = $search . $snippet;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
        $parameters['CustomerCustomerItems'] = $CustomerCustomerItems;
 
        $event->setParameters($parameters);
 
    }
 
 
    public function hookAdminOrderEditSearchCustomerByIdComplete(EventArgs $event)
 
    {
 
        $data = $event->getArgument('data');
 
        $Customer = $event->getArgument('Customer');
 
 
        $CustomerCustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('admin_customer');
 
 
        foreach($CustomerCustomerItems as $CustomerItem){
 
            $data['customerplus_'.$CustomerItem->getId()] = '';
 
            $value = $Customer->getCustomData($CustomerItem->getId());
 
            $data['customerplus_'.$CustomerItem->getId()] = $value;
 
        }
 
 
        $event->setArgument('data',$data);
 
    }
 
 
    public function onTemplateAdminOrderShipping(TemplateEvent $event)
 
    {
 
        $parameters = $event->getParameters();
 
        $source = $event->getSource();
 
 
        $ShippingCustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('admin_delivery');
 
 
        if(preg_match('/\{\{\sform\_errors\(shippingForm\.company\_name\)\s\}\}[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>[\n|\r\n|\r]\s*\<\/div\>/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/admin/Order/ext_shipping.twig');
 
            $replace = $search . $snippet;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
        $parameters['ShippingCustomerItems'] = $ShippingCustomerItems;
 
        $event->setParameters($parameters);
 
 
        $this->insertDatePickerJSAdmin($event);
 
    }
 
 
    public function onTemplateShoppingIndex(TemplateEvent $event)
 
    {
 
        $source = $event->getSource();
 
 
        if(preg_match('/\$\(\'#customer\'\)\.click\(function\(\)\s\{/',$source, $result)){
 
            $search = $result[0];
 
            $snippet = file_get_contents($this->container->getParameter('plugin_realdir'). '/CustomerPlus4/Resource/template/default/Shopping/insert_js.twig');
 
            $replace = $search . $snippet;
 
            $source = str_replace($search, $replace, $source);
 
        }
 
 
        $event->setSource($source);
 
    }
 
 
    public function onTemplateShoppingNonmember(TemplateEvent $event)
 
    {
 
        $source = $event->getSource();
 
 
        $request = $this->container->get('request_stack')->getCurrentRequest();
 
        $session = $request->getSession();
 
        if($session->has(OrderHelper::SESSION_NON_MEMBER)){
 
            if($session->get(OrderHelper::SESSION_NON_MEMBER)){
 
                if(preg_match('/url\(\'shopping_nonmember\'\)/',$source, $result)){
 
                    $search = $result[0];
 
                    $replace = "url('shopping_customer_edit')";
 
                    $source = str_replace($search, $replace, $source);
 
                }
 
 
                if(preg_match('/url\(\'cart\'\)/',$source, $result)){
 
                    $search = $result[0];
 
                    $replace = "url('shopping')";
 
                    $source = str_replace($search, $replace, $source);
 
                }
 
 
                if(preg_match('/\{\{\s\''.trans('common.next').'\'\|trans\s\}\}\<\/button\>/',$source, $result)){
 
                    $search = $result[0];
 
                    $replace = "{{ '".trans('customerplus.common.edit')."'|trans }}</button>";
 
                    $source = str_replace($search, $replace, $source);
 
                }
 
            }
 
        }
 
 
        $event->setSource($source);
 
        $this->insertDatePickerJS($event);
 
    }
 
 
    public function hookFrontShoppingNonmemberComplete(EventArgs $event)
 
    {
 
        $form = $event->getArgument('form');
 
        $request = $this->container->get('request_stack')->getCurrentRequest();
 
        $session = $request->getSession();
 
        $Customer = $session->get(OrderHelper::SESSION_NON_MEMBER);
 
 
        $CustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('customer');
 
        if($Customer instanceof \Eccube\Entity\Customer){
 
            foreach($CustomerItems as $CustomerItem){
 
                if($form->has('customerplus_'.$CustomerItem->getId())){
 
                    $plgCustomer = new CustomerCustom();
 
                    $plgCustomer->setCustomerItemId($CustomerItem->getId());
 
                    $plgCustomer->setCustomer($Customer);
 
                    $value = $form->get('customerplus_'.$CustomerItem->getId())->getData();
 
                    $value = $this->customerPlusService->convRegistData($value, $CustomerItem);
 
 
                    $CustomerData = new CustomerData();
 
                    if($CustomerItem->getInputType() == CustomerItem::CHECKBOX_TYPE){
 
                        $arrValue = explode(',', $value);
 
                    }else{
 
                        $arrValue = [$value];
 
                    }
 
                    foreach($arrValue as $value){
 
                        $detail = new CustomerDataDetail();
 
                        $detail->setCustomerData($CustomerData);
 
                        $disp_value = $value;
 
                        if($CustomerItem->getInputType() == CustomerItem::DATE_TYPE){
 
                            if(!is_null($value)){
 
                                $value = new \DateTime($value);
 
                            }
 
                            $detail->setDateValue($value);
 
                        }
 
                        if($CustomerItem->getInputType() >= CustomerItem::SELECT_TYPE){
 
                            $detail->setNumValue(intval($value));
 
                            foreach($CustomerItem->getOptions() as $Option){
 
                                if($value == $Option->getId())$disp_value = $Option->getText();
 
                            }
 
                        }
 
                        $detail->setValue($disp_value);
 
                        $CustomerData->setCustomerItem($CustomerItem);
 
                        $CustomerData->addDetail($detail);
 
                    }
 
                    $plgCustomer->setCustomerData($CustomerData);
 
                    $Customer->addCustomerCustom($plgCustomer);
 
                }
 
            }
 
            $session->set(OrderHelper::SESSION_NON_MEMBER, $Customer);
 
        }else{
 
            $data = $session->get(OrderHelper::SESSION_NON_MEMBER);
 
            foreach($CustomerItems as $CustomerItem){
 
                if($form->has('customerplus_'.$CustomerItem->getId())){
 
                    $value = $form->get('customerplus_'.$CustomerItem->getId())->getData();
 
                    $data['customerplus_'.$CustomerItem->getId()] = $this->customerPlusService->convRegistData($value, $CustomerItem);
 
                }
 
            }
 
            $session->set(OrderHelper::SESSION_NON_MEMBER, $data);
 
        }
 
    }
 
 
    public function hookFrontShoppingShippingComplete(EventArgs $event)
 
    {
 
        $Shipping = $event->getArgument('Shipping');
 
        $Order = $event->getArgument('Order');
 
        $request = $this->container->get('request_stack')->getCurrentRequest();
 
 
        $builder = $this->formFactory->createBuilder(CustomerAddressType::class, null, [
 
            'customer' => $Order->getCustomer(),
 
            'shipping' => $Shipping,
 
        ]);
 
 
        $form = $builder->getForm();
 
        $form->handleRequest($request);
 
 
        if ($form->isSubmitted() && $form->isValid()) {
 
            $CustomerAddress = $form['addresses']->getData();
 
            $this->setShippingFromCustomerAddress($Shipping,$CustomerAddress);
 
        }
 
    }
 
 
    public function hookFrontShoppingShippingEditInitialize(EventArgs $event)
 
    {
 
        if(!$this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
 
            $builder = $event->getArgument('builder');
 
            $Shipping = $event->getArgument('Shipping');
 
            $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
            $CustomerItems = $this->customerPlusService->getCustomerPlusForm('shipping_multiple_edit');
 
            $plgShippings = $Shipping->getShippingCustoms();
 
            if(!is_null($plgShippings) && count($plgShippings) > 0){
 
                foreach($plgShippings as $plgShipping){
 
                    $CustomerItem = $plgShipping->getCustomerData()->getCustomerItem();
 
                    if(in_array($CustomerItem,$CustomerItems)){
 
                        $customer_item_id = $CustomerItem->getId();
 
                        $value = $plgShipping->getValue();
 
                        if($value){
 
                            $value = $this->customerPlusService->convSetData($value, $customer_item_id, 'customerplus_Shipping_customerplus_');
 
                            $builder->get('customerplus_'.$customer_item_id)->setData($value);
 
                        }
 
                    }
 
                }
 
            }
 
        }
 
    }
 
 
    public function hookFrontShoppingShippingEditComplete(EventArgs $event)
 
    {
 
        $form = $event->getArgument('form');
 
        $Shipping = $event->getArgument('Shipping');
 
        $CustomerAddress = $event->getArgument('CustomerAddress');
 
        if($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')){
 
            $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
            $customerDataRepository = $entityManager->getRepository(CustomerData::class);
 
            $CustomerItems = $this->customerPlusService->getCustomerPlusForm('shipping_edit');
 
            foreach($CustomerItems as $CustomerItem){
 
                if($form->has('customerplus_'.$CustomerItem->getId())){
 
                    $plgCustomerAddress = new CustomerAddressCustom();
 
                    $plgCustomerAddress->setCustomerItemId($CustomerItem->getId());
 
                    $plgCustomerAddress->setCustomerAddress($CustomerAddress);
 
 
                    $value = $form->get('customerplus_'.$CustomerItem->getId())->getData();
 
                    $value = $this->customerPlusService->convRegistData($value, $CustomerItem);
 
                    $CustomerData = new CustomerData();
 
                    $CustomerData = $customerDataRepository->regist($CustomerData, $CustomerItem, $value);
 
                    $plgCustomerAddress->setCustomerData($CustomerData);
 
                    $CustomerAddress->addCustomerAddressCustom($plgCustomerAddress);
 
                }
 
            }
 
        }
 
        $this->setShippingFromCustomerAddress($Shipping,$CustomerAddress);
 
    }
 
 
    public function hookFrontContactIndexComplete(EventArgs $event)
 
    {
 
        $form = $event->getArgument('form');
 
        $data = $event->getArgument('data');
 
 
        $CustomerItems = $this->customerPlusService->getEnabledCustomerPlusForm('contact');
 
        foreach($CustomerItems as $CustomerItem){
 
            if($form->has('customerplus_'.$CustomerItem->getId())){
 
                $value = $form->get('customerplus_'.$CustomerItem->getId())->getData();
 
                $input_type = $CustomerItem->getInputType();
 
                if ($input_type == CustomerItem::DATE_TYPE) {
 
                    if($value instanceof \DateTime){
 
                        $value = $value->format('Y-m-d');
 
                    }
 
                } elseif($input_type >= CustomerItem::SELECT_TYPE) {
 
                    $Options = $CustomerItem->getOptions();
 
                    if(!is_array($value))$value = [$value];
 
                    $ret = [];
 
                    foreach($value as $val){
 
                        foreach($Options as $Option){
 
                            if($Option->getId() == $val){
 
                                $ret[] = $Option->getText();
 
                                continue;
 
                            }
 
                        }
 
                    }
 
                    $value = implode(',', $ret);
 
                }
 
                $data['customerplus_'.$CustomerItem->getId()] = $value;
 
            }
 
        }
 
        $event->setArgument('data',$data);
 
    }
 
 
    public function hookFrontShoppingShippingMultipleInitialize(EventArgs $event)
 
    {
 
        //ゲスト購入時の場合は削除前のShipping情報のカスタム要素を保持
 
        $Order = $event->getArgument('Order');
 
        $Shippings = $Order->getShippings();
 
        $ShippingCustoms = [];
 
        $ShippingNames = [];
 
        $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
        $customerItemRepository = $entityManager->getRepository('Plugin\CustomerPlus4\Entity\CustomerItem');
 
        foreach($Shippings as $Shipping){
 
            foreach($Shipping->getShippingCustoms() as $ShippingCustom){
 
                $CustomerItem = $customerItemRepository->find($ShippingCustom->getCustomerItemId());
 
                foreach($ShippingCustom->getCustomerData()->getDetails() as $Detail){
 
                    $CustomerDatas[$ShippingCustom->getCustomerItemId()][] = ($CustomerItem->getInputType() >= CustomerItem::SELECT_TYPE) ? $Detail->getNumValue() : $Detail->getValue();
 
                }
 
            }
 
            $ShippingCustoms[$Shipping->getId()] = $CustomerDatas;
 
            $ShippingNames[$Shipping->getId()] = $Shipping->getShippingMultipleDefaultName();
 
        }
 
        $this->session->set('eccube.front.shopping.nonmember.shipping', serialize($ShippingNames));
 
        $this->session->set('eccube.front.shopping.nonmember.shippingCustom', serialize($ShippingCustoms));
 
    }
 
 
    public function hookFrontShoppingShippingMultipleComplete(EventArgs $event)
 
    {
 
        $form = $event->getArgument('form');
 
        $Order = $event->getArgument('Order');
 
 
        $data = $form['shipping_multiple'];
 
 
        foreach ($data as $multiples) {
 
            foreach ($multiples as $items) {
 
                foreach ($items as $item) {
 
                    $CustomerAddress = $item['customer_address']->getData();
 
                    $customerAddressName = $CustomerAddress->getShippingMultipleDefaultName();
 
                    if ($this->authorizationChecker->isGranted('IS_AUTHENTICATED_FULLY')) {
 
                        foreach($Order->getShippings() as $Shipping){
 
                            $shippingName = $Shipping->getShippingMultipleDefaultName();
 
                            if($customerAddressName == $shippingName){
 
                                if($customerAddressName == $Order->getShippingMultipleDefaultName()){
 
                                    foreach($Order->getOrderCustoms() as $OrderCustom){
 
                                        $CustomerAddressCustom = new CustomerAddressCustom();
 
                                        $CustomerAddressCustom->setCustomerData($OrderCustom->getCustomerData())
 
                                                          ->setCustomerItemId($OrderCustom->getCustomerItemId())
 
                                                          ->setCustomerAddress($CustomerAddress);
 
                                        $CustomerAddress->addCustomerAddressCustom($CustomerAddressCustom);
 
                                    }
 
                                }
 
                                $this->setShippingFromCustomerAddress($Shipping,$CustomerAddress);
 
                            }
 
                        }
 
                    }else{
 
                        //ゲスト購入の場合は削除前に保持されていたShipping情報からデータを復元
 
                        if ($NonMember = $this->orderHelper->getNonMember()) {
 
                            $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
                            $customerItemRepository = $entityManager->getRepository('Plugin\CustomerPlus4\Entity\CustomerItem');
 
                            if ($MemShippings = $this->session->get('eccube.front.shopping.nonmember.shipping')) {
 
                                $MemShippingNames = unserialize($MemShippings);
 
                                $ShippingCustoms = $this->session->get('eccube.front.shopping.nonmember.shippingCustom');
 
                                $ShippingCustoms = unserialize($ShippingCustoms);
 
                                $flg = false;
 
 
                                foreach($Order->getShippings() as $Shipping){
 
                                    $shippingName = $Shipping->getShippingMultipleDefaultName();
 
                                    if($customerAddressName == $shippingName){
 
                                        foreach($MemShippingNames as $memShippingId => $memShippingName){
 
                                            if($customerAddressName == $memShippingName){
 
                                                foreach($ShippingCustoms as $shipping_id => $ShippingCustom){
 
                                                    if($shipping_id == $memShippingId){
 
                                                        foreach($ShippingCustom as $customer_item_id => $Details){
 
                                                            $CustomerData = new CustomerData();
 
                                                            $CustomerItem = $customerItemRepository->find($customer_item_id);
 
                                                            $CustomerData->setCustomerItem($CustomerItem);
 
                                                            foreach($Details as $value){
 
                                                                $detail = new CustomerDataDetail();
 
                                                                $detail->setCustomerData($CustomerData);
 
                                                                $disp_value = $value;
 
                                                                if($CustomerItem->getInputType() == CustomerItem::DATE_TYPE){
 
                                                                    if(!is_null($value)){
 
                                                                        $value = new \DateTime($value);
 
                                                                    }
 
                                                                    $detail->setDateValue($value);
 
                                                                }
 
                                                                if($CustomerItem->getInputType() >= CustomerItem::SELECT_TYPE){
 
                                                                    $detail->setNumValue(intval($value));
 
                                                                    foreach($CustomerItem->getOptions() as $Option){
 
                                                                        if($value == $Option->getId())$disp_value = $Option->getText();
 
                                                                    }
 
                                                                }
 
                                                                $detail->setValue($disp_value);
 
                                                                $CustomerData->addDetail($detail);
 
                                                            }
 
                                                            $CustomerAddressCustom = new CustomerAddressCustom();
 
                                                            $CustomerAddressCustom->setCustomerData($CustomerData)
 
                                                                    ->setCustomerItemId($customer_item_id)
 
                                                                    ->setCustomerAddress($CustomerAddress);
 
                                                            $CustomerAddress->addCustomerAddressCustom($CustomerAddressCustom);
 
                                                        }
 
                                                    }
 
                                                }
 
                                                $flg = true;
 
                                                break;
 
                                            }
 
                                        }
 
                                        $this->setShippingFromCustomerAddress($Shipping,$CustomerAddress);
 
                                    }
 
                                }
 
                                if(!$flg && $customerAddressName == $Order->getShippingMultipleDefaultName()){
 
                                    foreach($Order->getOrderCustoms() as $OrderCustom){
 
                                        $CustomerAddressCustom = new CustomerAddressCustom();
 
                                        $CustomerAddressCustom->setCustomerData($OrderCustom->getCustomerData())
 
                                                ->setCustomerItemId($OrderCustom->getCustomerItemId())
 
                                                ->setCustomerAddress($CustomerAddress);
 
                                        $CustomerAddress->addCustomerAddressCustom($CustomerAddressCustom);
 
                                    }
 
                                    $this->setShippingFromCustomerAddress($Shipping,$CustomerAddress);
 
                                }
 
                            }
 
                        }
 
                    }
 
                }
 
            }
 
        }
 
    }
 
 
    public function hookAdminCustomerCsvExport(EventArgs $event)
 
    {
 
        $ExportCsvRow = $event->getArgument('ExportCsvRow');
 
        if ($ExportCsvRow->isDataNull()) {
 
            $csvService = $event->getArgument('csvService');
 
            $Customer = $event->getArgument('Customer');
 
            $Csv = $event->getArgument('Csv');
 
 
            $csvEntityName = str_replace('\\\\', '\\', $Csv->getEntityName());
 
            if($csvEntityName == 'Plugin\CustomerPlus4\Entity\CustomerCustom'){
 
                $data = $Customer->getViewData($Csv->getFieldName());
 
 
                $ExportCsvRow->setData($data);
 
            }
 
        }
 
    }
 
 
    public function hookAdminOrderCsvExport(EventArgs $event)
 
    {
 
        $ExportCsvRow = $event->getArgument('ExportCsvRow');
 
        if ($ExportCsvRow->isDataNull()) {
 
            $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
            $shippingReposiory = $entityManager->getRepository(ShippingCustom::class);
 
            $csvService = $event->getArgument('csvService');
 
            $OrderItem = $event->getArgument('OrderItem');
 
            $Order = $OrderItem->getOrder();
 
            $Shipping = $OrderItem->getShipping();
 
            $Csv = $event->getArgument('Csv');
 
 
            $csvEntityName = str_replace('\\\\', '\\', $Csv->getEntityName());
 
            $data = null;
 
            if($csvEntityName == 'Plugin\CustomerPlus4\Entity\OrderCustom'){
 
                $data = $Order->getViewData($Csv->getFieldName());
 
            }elseif($csvEntityName == 'Plugin\CustomerPlus4\Entity\ShippingCustom'){
 
                $plgShipping = $shippingReposiory->findOneBy(['Shipping' => $Shipping, 'customer_item_id' =>  $Csv->getFieldName()]);
 
                if($plgShipping){
 
                    $data = $plgShipping->getViewValue();
 
                }
 
            }
 
            $ExportCsvRow->setData($data);
 
        }
 
    }
 
 
    public function insertDatePickerJS(TemplateEvent $event)
 
    {
 
        $twig = '@CustomerPlus4/default/datepicker_js.twig';
 
        $event->addAsset($twig);
 
    }
 
 
    private function insertDatePickerJSAdmin(TemplateEvent $event)
 
    {
 
        $twig = '@CustomerPlus4/admin/datepicker_js.twig';
 
        $event->addAsset($twig);
 
    }
 
 
    private function setShippingFromCustomerAddress($Shipping, $CustomerAddress)
 
    {
 
        $entityManager = $this->container->get('doctrine.orm.entity_manager');
 
        $ShippingCustoms = $Shipping->getShippingCustoms();
 
        if(!is_null($ShippingCustoms) && count($ShippingCustoms) > 0){
 
            foreach($ShippingCustoms as $ShippingCustom){
 
                $Shipping->removeShippingCustom($ShippingCustom);
 
                $entityManager->remove($ShippingCustom);
 
            }
 
        }
 
        $entityManager->flush();
 
        $CustomerAddressCustoms = $CustomerAddress->getCustomerAddressCustoms();
 
        if(!is_null($CustomerAddressCustoms)){
 
            foreach($CustomerAddressCustoms as $CustomerAddressCustom){
 
                $CustomerItem = $entityManager->getRepository(CustomerItem::class)->find($CustomerAddressCustom->getCustomerItemId());
 
                $CustomerData = new CustomerData();
 
                $CustomerData->setCustomerItem($CustomerItem);
 
                foreach($CustomerAddressCustom->getCustomerData()->getDetails() as $Detail){
 
                    $shippingDetail = new CustomerDataDetail();
 
                    $shippingDetail->setCustomerData($CustomerData)
 
                                ->setValue($Detail->getValue())
 
                                ->setDateValue($Detail->getDateValue())
 
                                ->setNumValue($Detail->getNumValue());
 
                    $CustomerData->addDetail($shippingDetail);
 
                }
 
                $ShippingCustom = new ShippingCustom();
 
                $ShippingCustom->setCustomerData($CustomerData)
 
                            ->setCustomerItemId($CustomerAddressCustom->getCustomerItemId())
 
                            ->setShipping($Shipping);
 
                $Shipping->addShippingCustom($ShippingCustom);
 
                $entityManager->persist($CustomerData);
 
                $entityManager->persist($ShippingCustom);
 
            }
 
        }
 
        $entityManager->flush();
 
    }
 
}