<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpBuyerSellerChat
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Webkul\MpBuyerSellerChat\Controller\Ajax;

use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Model\Session;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Exception\InputException;
use \Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\Metadata\FormFactory;
use Magento\Directory\Helper\Data as HelperData;
use Magento\Framework\Reflection\DataObjectProcessor;
use Magento\Customer\Model\CustomerExtractor;

class CreatePost extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @var \Magento\Framework\Serialize\Serializer\Json
     */
    protected $serializerJson;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var \Magento\Framework\Controller\Result\RawFactory
     */
    protected $resultRawFactory;

    /**
     * @var AccountManagementInterface
     */
    protected $accountManagement;

    /**
     * @var Session
     */
    protected $session;

    /**
     * @var CustomerRepositoryInterface
     */
    protected $customerRepository;

    /**
     * @var CustomerExtractor
     */
    protected $customerExtractor;

    /**
     * @var \Webkul\MpBuyerSellerChat\Helper\Data
     */
    protected $mpChatHelper;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param CustomerRepositoryInterface $customerRepository
     * @param \Magento\Framework\Serialize\Serializer\Json $serializerJson
     * @param \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory
     * @param \Magento\Framework\Controller\Result\RawFactory $resultRawFactory
     * @param CustomerExtractor $customerExtractor
     * @param AccountManagementInterface $accountManagement
     * @param Session $customerSession
     * @param \Webkul\MpBuyerSellerChat\Helper\Data $mpChatHelper
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        CustomerRepositoryInterface $customerRepository,
        \Magento\Framework\Serialize\Serializer\Json $serializerJson,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        CustomerExtractor $customerExtractor,
        AccountManagementInterface $accountManagement,
        Session $customerSession,
        \Webkul\MpBuyerSellerChat\Helper\Data $mpChatHelper
    ) {
        $this->storeManager = $storeManager;
        $this->serializerJson = $serializerJson;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->resultRawFactory = $resultRawFactory;
        $this->accountManagement = $accountManagement;
        $this->session = $customerSession;
        $this->customerRepository = $customerRepository;
        $this->customerExtractor = $customerExtractor;
        $this->mpChatHelper = $mpChatHelper;
        parent::__construct($context);
    }

    public function execute()
    {
        $credentials = null;
        $httpBadRequestCode = 400;

        /** @var \Magento\Framework\Controller\Result\Raw $resultRaw */
        $resultRaw = $this->resultRawFactory->create();
        try {
            $credentials = $this->serializerJson->unserialize($this->getRequest()->getContent());
            
        } catch (\Exception $e) {
            return $resultRaw->setHttpResponseCode($httpBadRequestCode);
        }
        if (!$credentials || $this->getRequest()->getMethod() !== 'POST' || !$this->getRequest()->isXmlHttpRequest()) {
            return $resultRaw->setHttpResponseCode($httpBadRequestCode);
        }
        $this->_request->setParams($credentials);
        $response = [
            'errors' => false,
            'message' => __('')
        ];
        try {
            $redirectUrl = $this->session->getBeforeAuthUrl();
            // Get Website ID
            $websiteId  = $this->storeManager->getWebsite()->getWebsiteId();

            // Instantiate object (this is the most important part)
            $customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
            $customer->setWebsiteId($websiteId);
            $this->session->setIsCharSystemRegistration(true);
            $customer = $this->accountManagement
                ->createAccount($customer, null, $redirectUrl);
            
            $this->_eventManager->dispatch(
                'customer_register_success',
                ['account_controller' => $this, 'customer' => $customer]
            );

            $this->session->setCustomerDataAsLoggedIn($customer);
            $this->mpChatHelper->setCustomerId($customer->getId());

            $response = [
                'errors' => false,
                'message' => __('You have registered succesfully, check your email to set you password.')
            ];
            $this->session->setIsCharSystemRegistration(false);
            /** @var \Magento\Framework\Controller\Result\Json $resultJson */
            $resultJson = $this->resultJsonFactory->create();
            return $resultJson->setData($response);
        } catch (StateException $e) {
            // @codingStandardsIgnoreStart
            $message = __(
                'There is already an account with this email address.'
            );
            $customer = $this->customerRepository->get($credentials['email']);
            $response = [
                'errors' => true,
                'message' => $message
            ];
            $resultJson = $this->resultJsonFactory->create();
            return $resultJson->setData($response);
        } catch (InputException $e) {
            $response = [
                'errors' => true,
                'message' => $e->getMessage()
            ];
            $resultJson = $this->resultJsonFactory->create();
            return $resultJson->setData($response);
        }
    }
}