<?php
namespace Plugin\Atobaraidotcom4\Controller\Admin;

use Eccube\Controller\AbstractController;
use Eccube\Entity\Order;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Plugin\Atobaraidotcom4\Repository\ConfigRepository;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Plugin\Atobaraidotcom4\Service\AtobaraidotcomRequestService;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Eccube\Repository\OrderRepository;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;

class OrderController extends AbstractController
{
    /**
     * @var ValidatorInterface
     */
    protected $validator;
    /**
     * @var OrderRepository
     */
    protected $orderRepository;
    /**
     * コンストラクタ
     *
     */
    public function __construct(
        ConfigRepository $configRepository,
        ContainerInterface $container,
        AtobaraidotcomRequestService $atobaraidotcomRequestService,
        ValidatorInterface $validator,
        PurchaseFlow $shoppingPurchaseFlow,
        OrderRepository $orderRepository
    ) {
        $this->Config = $configRepository->get();
        $this->container = $container;
        $this->atobaraidotcomRequestService = $atobaraidotcomRequestService;
        $this->validator = $validator;
        $this->orderRepository = $orderRepository;
        $this->purchaseFlow = $shoppingPurchaseFlow;
    }

    /**
     * 受注編集 > 決済のキャンセル処理
     *
     * @Route("/%eccube_admin_route%/atobaraidotcom/order/update_tracking", name="atobaraidotcom4_admin_order_update_tracking")
     */
    public function atobaraidotcom4_update_tracking(Request $request)
    {
        if (!($request->isXmlHttpRequest() && $this->isTokenValid())) {
            return $this->json(['status' => 'NG'], 400);
        }


        logs('atobaraidotcom')->info('update_tracking Order ID:'.$request->get('id'));
        $trackingNumber = mb_convert_kana($request->get('tracking_number'), 'a', 'utf-8');
        $order_id = $request->get('id');
        // $Order = $app['eccube.repository.order']->find($order_id);
        $Order = $this->orderRepository->find($order_id);
        /** @var \Symfony\Component\Validator\ConstraintViolationListInterface $errors */

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

        $errors = $this->validator->validate(
            $trackingNumber,
            [
                new Assert\Length(['max' => $this->eccubeConfig['eccube_stext_len']]),
                new Assert\Regex(
                    ['pattern' => '/^[0-9a-zA-Z-]+$/u', 'message' => trans('admin.order.tracking_number_error')]
                ),
            ]
        );
        if ($errors->count() != 0) {
            // log_info('送り状番号入力チェックエラー');
            $messages = [];
            /** @var \Symfony\Component\Validator\ConstraintViolationInterface $error */
            foreach ($errors as $error) {
                $messages[] = $error->getMessage();
            }

            return $this->json(['status' => 'NG', 'messages' => $messages], 400);
        }
        logs('atobaraidotcom')->info('update_tracking SystemOrderId:'.$Order->getAtobaraidotcomSystemOrderId());
        try {
                
                $arrRequests['EnterpriseId'] =  $this->Config->getEnterpriseId();
                $arrRequests['ApiUserId'] = $this->Config->getApiUserId();
                $arrRequests['OrderId'] = $Order->getAtobaraidotcomSystemOrderId();
                $arrRequests['DelivId'] = $this->Config->getDelivery();
                $arrRequests['JournalNum'] = $trackingNumber;

                $arrXML = $this->atobaraidotcomRequestService->sendRequest( $this->container->getParameter('WC_TRUSTRING_ATOBARAIDOTCOM_SHIPPING'), $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") {
                     $Order->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"]);
                        $Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】 【エラーコード】 ".$key." 【出力メッセージ】 ".$value . " 【エラー条件】 " . $error_code_table[$key]["DetailMess"]);
                    }
                } 

            // $shipping->setTrackingNumber($trackingNumber);
            // $this->entityManager->flush($shipping);
            // log_info('送り状番号変更処理完了', [$shipping->getId()]);
            $message = ['status' => 'OK', 'tracking_number' => $trackingNumber];
            logs('atobaraidotcom')->info('update_tracking END ');

            return $this->json($message);
        } catch (\Exception $e) {
            log_error('予期しないエラー', [$e->getMessage()]);

            return $this->json(['status' => 'NG'], 500);
        }

    }
}