<?php
namespace Webkul\MpPaypal\Controller\Seller;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;

class CreateOrder extends Action implements CsrfAwareActionInterface
{
    protected $_publicActions = ['createorder'];

    /**
     * @var Magento\Customer\Model\Session
     */
    protected $_customerSession;

    /**
     * @var Magento\Framework\Registry
     */
    protected $_coreRegistry;

    /**
     * @var Webkul\Marketplace\Helper\Data
     */
    protected $_marketplaceHelper;

    /**
     * @var string
     */
    public $sellermail;

    /**
     * @var string
     */
    public $quoteId;

    /**
     * @param Context $context
     * @param Session $customerSession
     * @param \Magento\Checkout\Model\Session $checkoutSession
     * @param \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory
     * @param \Webkul\Marketplace\Helper\Data $marketplaceHelper
     * @param \Webkul\MpPaypal\Helper\Data $helper
     * @param \Magento\Framework\UrlInterface $url
     * @param \Webkul\MpPaypal\Model\Paypal\Adapter $adapter
     * @param \Webkul\MpPaypal\Gateway\Config\Config $modConfig
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Customer\Model\CustomerFactory $customerFactory
     */
    public function __construct(
        Context $context,
        Session $customerSession,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\Controller\Result\JsonFactory $jsonResultFactory,
        \Webkul\Marketplace\Helper\Data $marketplaceHelper,
        \Webkul\MpPaypal\Helper\Data $helper,
        \Magento\Framework\UrlInterface $url,
        \Webkul\MpPaypal\Model\Paypal\Adapter $adapter,
        \Webkul\MpPaypal\Gateway\Config\Config $modConfig,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Customer\Model\CustomerFactory $customerFactory
    ) {
        parent::__construct($context);
        $this->_customerSession = $customerSession;
        $this->adapter = $adapter;
        $this->jsonResultFactory = $jsonResultFactory;
        $this->checkoutSession = $checkoutSession;
        $this->_marketplaceHelper = $marketplaceHelper;
        $this->helper = $helper;
        $this->jsonHelper = $jsonHelper;
        $this->url = $url;
        $this->modConfig = $modConfig;
        $this->storeManager = $storeManager;
        $this->productFactory = $productFactory;
        $this->customerFactory = $customerFactory;
    }

    public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
    {
        return null;
    }

    public function validateForCsrf(RequestInterface $request): ?bool
    {
        return true;
    }

    public function execute()
    {
        $requestData = $this->getRequest()->getParams();
        $originalRequest = [];
        $originalRequest['original'] = $requestData;

        /**
         * purchase_units creationg
         */
        $originalRequest['original']['intent'] = 'CAPTURE';
        $originalRequest['original']['purchase_units'] = $this->createPurchaseUnit();
        $originalRequest['original']['application_context']['return_url'] = $this->url->getUrl('checkout');
        $originalRequest['original']['application_context']['cancel_url'] = $this->url->getUrl('checkout');
        $this->helper->logDataInLogger(
            'request createOrder '.$this->jsonHelper->jsonEncode($originalRequest['original'])
        );
        $returnData = $this->adapter->_create($originalRequest);
        $finalData = $this->jsonHelper->jsonDecode($returnData);
        $finalData['email_address'] = $this->sellermail;
        $finalData['quote_id'] = $this->quoteId;
        $resultJson = $this->jsonResultFactory->create();
        $this->helper->logDataInLogger('response createOrder '.$this->jsonHelper->jsonEncode($finalData));
        return $resultJson->setData($this->jsonHelper->jsonEncode($finalData));
    }

    public function createPurchaseUnit()
    {
        $request = [];
        /**
         * get data from quote
         */

        $quote = $this->checkoutSession->getQuote();
        $this->quoteId = $quote->getId();
        $finalCart = $this->helper->createFinalCart($quote);
        $i=0;
        $currencyCode = $this->storeManager->getStore()->getCurrentCurrencyCode();
        foreach ($finalCart as $sellers) {
            $this->helper->logDataInLogger('response seller '.$this->jsonHelper->jsonEncode($sellers));
            if ($sellers['seller']) {
                $seller = $this->customerFactory->create()->load($sellers['seller']);
                $request[$i]['payee']['email_address'] = $seller->getEmail();
                $this->sellermail = $seller->getEmail();
                $request[$i]['payment_instruction']['disbursement_mode'] = $this->modConfig
                ->getPaymentMode();

                $request[$i]['amount']['value'] = round(
                    $sellers['price'] - $sellers['discount'],
                    2
                );
                if (!$this->_marketplaceHelper->getConfigTaxManage()) {
                    $request[$i]['amount']['value'] += round($sellers['taxamount'], 2);
                }
                $request[$i]['amount']['currency_code'] = $currencyCode;

                /**
                 * breakdown definition
                 */
                $request[$i]['amount']['breakdown']['item_total']['currency_code'] = $currencyCode;
                $request[$i]['amount']['breakdown']['item_total']['value'] = round($sellers['price'], 2);
                if ($this->_marketplaceHelper->getConfigTaxManage()) {
                    $request[$i]['amount']['breakdown']['item_total']['value'] -= round($sellers['taxamount'], 2);
                }
                $request[$i]['amount']['breakdown']['shipping']['currency_code'] = $currencyCode;
                $request[$i]['amount']['breakdown']['shipping']['value'] = round($sellers['shippingprice'], 2);
                $request[$i]['amount']['breakdown']['tax_total']['currency_code'] = $currencyCode;
                $request[$i]['amount']['breakdown']['tax_total']['value'] = round($sellers['taxamount'], 2);
                $request[$i]['amount']['breakdown']['discount']['value'] = round($sellers['discount'], 2);
                $request[$i]['amount']['breakdown']['discount']['currency_code'] = $currencyCode;
                $items = explode(',', $sellers['products']);
                $k=0;

                $commission = round($sellers['commission'], 2);
                if (!$this->_marketplaceHelper->getConfigTaxManage()) {
                    $commission += round($sellers['taxamount'], 2);
                }
                $request[$i]['payment_instruction']['platform_fees'][$k]['amount']
                ['value'] = $commission;
                $request[$i]['payment_instruction']['platform_fees'][$k]['amount']
                ['currency_code'] = $currencyCode;
                $request[$i]['payment_instruction']['platform_fees'][$k]['payee']
                ['email_address'] = $this->modConfig->getPartnerEmail();
                
                foreach ($items as $item) {
                    /**
                     * add items to bucket
                     */
                    $product = $this->productFactory->create()->load($item);
                    $request[$i]['items'][$k]['name'] = $product->getName();
                    $request[$i]['items'][$k]['sku'] = $product->getSku();
                    $request[$i]['items'][$k]['quantity'] = $sellers['qty'];
                    $request[$i]['items'][$k]['unit_amount']['currency_code'] = $currencyCode;
                    $request[$i]['items'][$k]['unit_amount']['value'] = round($product->getPrice(), 2);
                    $k++;
                }

                /**
                 * manage shipping address
                 */
                if (!empty($quote->getShippingAddress()->getShippingMethod())) {
                    $request[$i]['shipping']['shipping_method'] = $quote->getShippingAddress()->getShippingMethod();
                    $request[$i]['shipping']['address']['address_line_1'] = implode(
                        ',',
                        $quote->getShippingAddress()->getStreet()
                    );
                    $request[$i]['shipping']['address']['address_line_2'] = $quote->getShippingAddress()->getCity();
                    $request[$i]['shipping']['address']['country_code'] = $quote->getShippingAddress()->getCountryId();
                    $request[$i]['shipping']['address']['postal_code'] = $quote->getShippingAddress()->getPostcode();
                    $request[$i]['shipping']['address']['admin_area_2'] = $quote->getShippingAddress()->getCity();
                    $request[$i]['shipping']['address']['admin_area_1'] = $quote->getShippingAddress()->getCity();
                }
                $i++;
            } else {
                /**
                 * for admin
                 */
                $i--;
                if ($request[$i]['amount']['value']) {
                    $request[$i]['amount']['value'] +=round($sellers['price'], 2);
                } else {
                    $request[$i]['amount']['value'] = round($sellers['price'], 2);
                }

                $request[$i]['amount']['breakdown']['shipping']['value'] = round($sellers['price'], 2);
            }
        }
        return $request;
    }
}
