<?php
namespace Plugin\Atobaraidotcom4\Service;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Event\EccubeEvents;
use Eccube\Event\EventArgs;
use Plugin\Atobaraidotcom4\Repository\ConfigRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Plugin\Atobaraidotcom4\Service\AtobaraidotcomRequestService;

// SymfonyのWorkflowコンポーネントのイベントを使用します。
use Symfony\Component\Workflow\Event\Event;

class OrderStateMachine implements EventSubscriberInterface {

    /**
     * コンストラクタ
     *
     */
    public function __construct(
        ConfigRepository $configRepository,
        ContainerInterface $container,
        AtobaraidotcomRequestService $atobaraidotcomRequestService
    ) {
        $this->Config = $configRepository->get();
        $this->container = $container;
        $this->atobaraidotcomRequestService = $atobaraidotcomRequestService;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            'workflow.order.transition.cancel' => [['cancel']],
            EccubeEvents::ADMIN_ORDER_EDIT_INDEX_COMPLETE => [['onAdminOrderEditIndexComplete']],
        ];
    }

    /**
     * 対応状況が注文取消しに変わったときの処理
     * 
     * @param Event $event
     */
    public function cancel(Event $event)
    {
        // 注文取消しになった受注データ
        $Order = $event->getSubject()->getOrder();
        // $method_class1 = Plugin\Atobaraidotcom4\Service\Method\AtobaraidotcomMethod::class;
        // $method_class2 = $Order->getPayment()->getMethodClass();
        logs('atobaraidotcom')->info($method_class1);
        logs('atobaraidotcom')->info($method_class2);
        if (strpos(Plugin\Atobaraidotcom4\Service\Method\AtobaraidotcomMethod::class, $Order->getPayment()->getMethodClass()) !== false) {
        // 通信処理
            logs('atobaraidotcom')->info('受注キャンセル Start');

            if (!empty($this->Config->getEnterpriseId()) && !empty($this->Config->getApiUserId())) {

                $arrCancelRequests['EnterpriseId'] = $this->Config->getEnterpriseId();
                $arrCancelRequests['ApiUserId'] = $this->Config->getApiUserId();
                $arrCancelRequests['OrderId'] = array($Order->getAtobaraidotcomSystemOrderId());
                $arrCancelRequests['Reason'] = array("リアルタイムではない注文です。");

                $arrXML = $this->atobaraidotcomRequestService->sendRequest( $this->container->getParameter('WC_TRUSTRING_ATOBARAIDOTCOM_CANCEL'), $arrCancelRequests);

                $xml_obj = simplexml_load_string($arrXML);

                $arrCancelResponse = $this->atobaraidotcomRequestService->xml2arr($xml_obj);

                if ($arrCancelResponse["status"] == "success" && $arrCancelResponse["result"]["cancelStatus"] == "success") {
                
                    $Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】キャンセル成功。");
    
                } else {
                    $Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】キャンセル失敗。手動でご確認ください。");
                }
                // var_dump($delivery_option);
            }
            logs('atobaraidotcom')->info('受注キャンセル End');
        }
    }

    public function onAdminOrderEditIndexComplete(EventArgs $event)
    {
        $OriginOrder = $event->getArgument('OriginOrder');
        $TargetOrder = $event->getArgument('TargetOrder');

        if (strpos(Plugin\Atobaraidotcom4\Service\Method\AtobaraidotcomMethod::class, $TargetOrder->getPayment()->getMethodClass()) == false) {
            return;
        }

        logs('atobaraidotcom')->info('update_tracking Order ID:'.$TargetOrder->getId());
        $TargetTrackingNumber = $TargetOrder->getShippings()->first()->getTrackingNumber();
        $OriginTrackingNumber = $OriginOrder->getShippings()->first()->getTrackingNumber();
        // if ($TargetTrackingNumber == $OriginTrackingNumber) {
        //     logs('atobaraidotcom')->info('update_tracking TargetTrackingNumber:'.$TargetTrackingNumber.' OriginTrackingNumber:'.$TargetTrackingNumber);
        //     return;
        // }
        $order_id = $TargetOrder->getId();

        logs('atobaraidotcom')->info('update_tracking SystemOrderId:'.$TargetOrder->getAtobaraidotcomSystemOrderId());
        try {
                
                $arrRequests['EnterpriseId'] =  $this->Config->getEnterpriseId();
                $arrRequests['ApiUserId'] = $this->Config->getApiUserId();
                $arrRequests['OrderId'] = $TargetOrder->getAtobaraidotcomSystemOrderId();
                $arrRequests['DelivId'] = $this->Config->getDelivery();
                $arrRequests['JournalNum'] = $TargetTrackingNumber;

                // if (empty($OriginTrackingNumber)) {
                    $arrXML = $this->atobaraidotcomRequestService->sendRequest( $this->container->getParameter('WC_TRUSTRING_ATOBARAIDOTCOM_SHIPPING'), $arrRequests);
                // } else {
                //     $arrXML = $this->atobaraidotcomRequestService->sendRequest( $this->container->getParameter('WC_TRUSTRING_ATOBARAIDOTCOM_JNUMMOD'), $arrRequests);
                // }
                
                $xml_obj = simplexml_load_string($arrXML);
                $arrResponse = $this->atobaraidotcomRequestService->xml2arr($xml_obj);

                // var_dump($arrResponse);
                // die();

                $error_message = array();
                $error_code_table = $this->atobaraidotcomRequestService->get_error_code();

                if ($arrResponse["status"] == "success") {
                     $TargetOrder->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】伝票番号登録 【成功】".$arrResponse["delivName"].$arrResponse["journalNum"]);
                } else {
                    foreach ($arrResponse["messages"] as $key => $value) {
                        if (empty($error_code_table[$key]["FrontendMess"])) {
                            array_push( $error_message , $value );
                        } else {
                            array_push( $error_message , $error_code_table[$key]["FrontendMess"] );
                        }
                        logs('atobaraidotcom')->info(date('Y年m月d日 H時i分s秒')." 【後払い.com】 【エラーコード】 ".$key." 【出力メッセージ】 ".$value . " 【エラー条件】 " . $error_code_table[$key]["DetailMess"]);
                        $TargetOrder->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】 【エラーコード】 ".$key." 【出力メッセージ】 ".$value . " 【エラー条件】 " . $error_code_table[$key]["DetailMess"]);
                    }
                } 

        } catch (\Exception $e) {
            log_error('予期しないエラー', [$e->getMessage()]);
            logs('atobaraidotcom')->info('予期しないエラー'.$e->getMessage());
        }
    }
}