<?php
namespace Plugin\Atobaraidotcom4\Service\Method;

use Doctrine\ORM\EntityManagerInterface;
use Eccube\Common\Constant;
use Eccube\Common\EccubeConfig;
use Eccube\Entity\Master\OrderStatus;
use Eccube\Entity\TaxRule;
use Eccube\Entity\Order;
use Eccube\Repository\OrderRepository;
use Eccube\Repository\Master\OrderStatusRepository;
use Eccube\Service\CartService;
use Eccube\Service\MailService;
use Eccube\Service\Payment\PaymentDispatcher;
use Eccube\Service\Payment\PaymentMethodInterface;
use Eccube\Service\Payment\PaymentResult;
use Eccube\Service\PurchaseFlow\PurchaseContext;
use Eccube\Service\PurchaseFlow\PurchaseFlow;
use Plugin\Atobaraidotcom4\Repository\ConfigRepository;
use Plugin\Atobaraidotcom4\Service\AtobaraidotcomRequestService;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Form\FormInterface;
use Twig_Environment;


/**
 * 決済モジュール 決済処理 基底クラス
 */
class AtobaraidotcomMethod implements PaymentMethodInterface
{
    protected $mission_code;

    public function __construct(
        EntityManagerInterface $entityManager,
        Twig_Environment $twig,
        EccubeConfig $eccubeConfig,
        OrderRepository $orderRepository,
        OrderStatusRepository $orderStatusRepository,
        CartService $cartService,
        MailService $mailService,
        PurchaseFlow $shoppingPurchaseFlow,
        ConfigRepository $configRepository,
        AtobaraidotcomRequestService $atobaraidotcomRequestService,
        ContainerInterface $container
    ) {
        $this->entityManager = $entityManager;
        $this->twig = $twig;
        $this->eccubeConfig = $eccubeConfig;
        $this->orderRepository = $orderRepository;
        $this->orderStatusRepository = $orderStatusRepository;
        $this->cartService = $cartService;
        $this->mailService = $mailService;
        $this->purchaseFlow = $shoppingPurchaseFlow;
        $this->atobaraidotcomRequestService = $atobaraidotcomRequestService;
        $this->container = $container;
        $this->Config = $configRepository->get();
    }

    /**
     * {@inheritdoc}
     */
    public function verify()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $this->purchaseFlow->prepare($this->Order, new PurchaseContext());

        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function checkout()
    {
        logs('atobaraidotcom')->info('pay process start. order_id = ' . $this->Order->getId());

        // リクエストパラメータをセット
        $arrParameter = $this->setParameter($this->Order);

        // データ送信(POST)
        logs('atobaraidotcom')->info('send data ');
        // var_dump($arrParameter);
        // die();
        $arrXML = $this->atobaraidotcomRequestService->sendRequest( $this->container->getParameter('WC_TRUSTRING_ATOBARAIDOTCOM_ORDER'), $arrParameter);

        $xml_obj = simplexml_load_string($arrXML);

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

        logs('atobaraidotcom')->info('status :'.$arrResponse["status"]);
        
        if ($arrResponse["status"] == "success") {
            $this->Order->setAtobaraidotcomSystemOrderId($arrResponse["systemOrderId"]);
            // ================================================================
            if ($arrResponse["orderStatusCd"] == "0") {
                // Pharse 2 一旦保留
                // // orderStatus cd="0" -> 与信中
                $this->Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】与信中 【注文ID】".$arrResponse["systemOrderId"]);
                // // Update systemOrderId
                // // ---------------------------------
                // $this->purchaseFlow->commit($this->Order, new PurchaseContext());

                // $OrderStatus = $this->orderStatusRepository->find(OrderStatus::NEW);
                // $this->Order->setOrderStatus($OrderStatus);
        
                // $result = new PaymentResult();
                // $result->setSuccess(true);

                // return $result;
                // Pharse 2 一旦保留

                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($arrResponse["systemOrderId"]);
                    $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);
                    logs('atobaraidotcom')->info('DELIVLIST LOAD status :'.$arrResponse["status"]);
                    // $arrResponse = Atobaraidotcom_Config::sendRequest(WC_TRUSTRING_ATOBARAIDOTCOM_DELIVLIST, $arrRequests);
                    // $xml_obj = simplexml_load_string($arrResponse);

                    // $arrResponse = Atobaraidotcom_Config::xml2arr($xml_obj,2);
                    // var_dump($arrResponse);
                    if ($arrCancelResponse["status"] == "success" && $arrCancelResponse["result"]["cancelStatus"] == "success") {
                        // var_dump($arrResponse["result"]["delivId"]);
                        // foreach ($arrResponse["resultdeliv"] as $key => $value) {
                        //     $delivery_option[$value["name"]] = $value["delivId"];
                        // }
                        
                        // array_push($delivery_option, array( $arrResponse["result"]["delivId"] => $arrResponse["result"]["name"]));
                        
                        $this->Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】キャンセル成功。");
        
                        $result = new PaymentResult();
                        $result->setErrors(array("現在のお支払方法は使用不可となっております。別のお支払方法をお選びください。"));
                        $result->setSuccess(false);
                        return $result;
                    } else {
                        $this->Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】キャンセル失敗。手動でご確認ください。");

                        $this->purchaseFlow->commit($this->Order, new PurchaseContext());

                        $OrderStatus = $this->orderStatusRepository->find(OrderStatus::NEW);
                        $this->Order->setOrderStatus($OrderStatus);
                
                        $result = new PaymentResult();
                        $result->setSuccess(true);

                        return $result;
                    }
                    // var_dump($delivery_option);
                }

            } elseif ($arrResponse["orderStatusCd"] == "1") {
                // orderStatus cd="1" -> 与信OK
                $this->Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】与信OK 【注文ID】".$arrResponse["systemOrderId"]);
                // Update systemOrderId
                // ---------------------------------
                $this->purchaseFlow->commit($this->Order, new PurchaseContext());

                // 購入時のステータスを　IN_PROGRESS から　NEW　に変更
                //$OrderStatus = $this->orderStatusRepository->find(OrderStatus::IN_PROGRESS);
                $OrderStatus = $this->orderStatusRepository->find(OrderStatus::NEW);
                $this->Order->setOrderStatus($OrderStatus);
        
                $result = new PaymentResult();
                $result->setSuccess(true);

                return $result;
            } else {
                // orderStatus cd="2" -> 与信NG
                $this->Order->appendNote("\n".date('Y年m月d日 H時i分s秒')." 【後払い.com】与信NG 【注文ID】".$arrResponse["systemOrderId"]);
        
                $result = new PaymentResult();
                $result->setErrors(array("現在のお支払方法は使用不可となっております。別のお支払方法をお選びください。"));
                $result->setSuccess(false);
                return $result;
            }

        } else {
            $error_message = array();
            $error_code_table = $this->atobaraidotcomRequestService->get_error_code();
            $result = new PaymentResult();
            $result->setSuccess(false);

            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"]);
                $result->setErrors($error_message);
            }
            
            return $result;
        }

        
    }

    /**
     * {@inheritdoc}
     */
    public function setFormType(FormInterface $form)
    {
        $this->form = $form;
    }

    /**
     * {@inheritdoc}
     */
    public function setOrder(Order $Order)
    {
        $this->Order = $Order;
    }

    /**
     * {@inheritdoc}
     */
    public function setRequest(Request $request)
    {
        $this->request = $request;
    }

    /**
     * リクエストパラメータを設定
     *
     * @param \Eccube\Entity\Order $Order
     * @return array
     */
    function setParameter($Order)
    {

        // =============================================================================================================
        $arrRequests['O_ReceiptOrderDate'] = date('Y/m/d');
        $arrRequests['O_EnterpriseId'] = $this->Config->getEnterpriseId();
        $arrRequests['O_SiteId'] = $this->Config->getSiteId();
        $arrRequests['O_ApiUserId'] = $this->Config->getApiUserId();
        $arrRequests['O_Ent_OrderId'] = "CUBE-".$Order->getId();

        $arrRequests['O_UseAmount'] = $Order->getPaymentTotal();

        $arrRequests['C_PostalCode'] = $Order->getPostalCode();
        $arrRequests['C_UnitingAddress'] = $Order->getPref().$Order->getAddr01().$Order->getAddr02();
        $arrRequests['C_NameKj'] = $Order->getName01()." ".$Order->getName02();
        $arrRequests['C_Phone'] = $Order->getPhonenumber();
        $arrRequests['C_MailAddress'] = $Order->getEmail();

        $arrShippings = $Order->getShippings();
        $Shipping = $arrShippings[0];

        $arrRequests['O_AnotherDeliFlg'] = "1";
        $arrRequests['D_PostalCode'] = $Shipping->getPostalCode();
        $arrRequests['D_UnitingAddress'] = $Shipping->getPref().$Shipping->getAddr01().$Shipping->getAddr02();
        $arrRequests['D_DestNameKj'] = $Shipping->getName01()." ".$Shipping->getName02();
        $arrRequests['D_Phone'] = $Shipping->getPhonenumber();
        // テスト
        // $arrRequests['O_TestOrderFlg'] = "1";
        // テスト注文の与信をＯＫで返す場合は0、ＮＧで返す場合は1、手動与信とする場合は2 または未設定
        // $arrRequests['O_TestCreditResult'] = "2";
        // テスト
        // C_SeparateShipment
        $i = 1;
        foreach ($Order->getOrderItems() as $orderItem) {
            if ($orderItem->isProduct()) {
                $arrRequests['I_ItemNameKj_'.$i] = $orderItem->getProductName()."-".$orderItem->getProductCode();
                $arrRequests['I_UnitPrice_'.$i] = $orderItem->getPriceIncTax();
                $arrRequests['I_ItemNum_'.$i] = $orderItem->getQuantity();
                $arrRequests['I_TaxRate_'.$i] = $orderItem->getTaxRate();
                $i = $i + 1;
            }
        }
        if ($Order->getDiscount()) {
            $arrRequests['I_ItemNameKj_'.$i] = "値引・ポイント";
            $arrRequests['I_UnitPrice_'.$i] = "-".$Order->getDiscount();
            $arrRequests['I_ItemNum_'.$i] = "1";
            $arrRequests['I_TaxRate_'.$i] = $this->Config->getTax();
        }
        if ($Order->getDeliveryFeeTotal()) {
            $arrRequests['I_ItemCarriage'] = $Order->getDeliveryFeeTotal();
        }
        $arrRequests['I_ItemCharge'] = $Order->getCharge();
        $arrRequests['O_Ent_Note'] = $Order->getNote();

        return $arrRequests;
    }


}
