<?php

/**
 * Webkul Software.
 *
 *
 *
 * @category  Webkul
 * @package   Webkul_GdprCompliance
 * @author    Webkul <support@webkul.com>
 * @copyright Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html ASL Licence
 * @link      https://store.webkul.com/license.html
 */
namespace Webkul\GdprCompliance\Model;

use Magento\Catalog\Model\ProductFactory;
use Magento\Framework\Webapi\Rest\Request;
use Webkul\MobikulCore\Helper\Data as HelperData;
use Magento\Customer\Api\CustomerRepositoryInterface;

class DeleteCustomerManagement extends ApiHandler implements \Webkul\GdprCompliance\Api\DeleteCustomerManagementInterface  
{
    /**
     * deviceTokenFactory variable
     *
     * @var \Webkul\MobikulCore\Model\DeviceTokenFactory
     */
    protected $deviceTokenFactory;
    /**
     * customerSession variable
     *
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;
    /**
     * coreSession variable
     *
     * @var \Magento\Framework\Session\SessionManagerInterface
     */
    protected $coreSession;
    /**
     * _customerRepository variable
     *
     * @var CustomerRepositoryInterface
     */
    protected $_customerRepository;
    
    /**
     * Constructor function
     *
     * @param \Webkul\MobikulCore\Model\DeviceTokenFactory $deviceTokenFactory
     * @param \Magento\Customer\Model\Session $customerSession
     * @param \Magento\Framework\Session\SessionManagerInterface $coreSession
     * @param HelperData $helper
     * @param CustomerRepositoryInterface $customerRepository
     * @param \Magento\Framework\ObjectManagerInterface $objectManager
     * @param \Magento\Framework\Json\Helper\Data $jsonHelper
     * @param \Magento\Framework\Webapi\Rest\Response $response
     * @param \Magento\Framework\Webapi\Rest\Request $request
     */
    public function __construct(
        \Webkul\MobikulCore\Model\DeviceTokenFactory $deviceTokenFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\Session\SessionManagerInterface $coreSession,
        HelperData $helper,
        CustomerRepositoryInterface $customerRepository,
        \Magento\Framework\ObjectManagerInterface $objectManager,
        \Magento\Framework\Json\Helper\Data $jsonHelper,
        \Magento\Framework\Webapi\Rest\Response $response,
        \Magento\Framework\Webapi\Rest\Request $request
    )
    {
        $this->deviceTokenFactory = $deviceTokenFactory;
        $this->customerSession = $customerSession;
        $this->coreSession = $coreSession;
        $this->_customerRepository = $customerRepository;
        parent::__construct($jsonHelper, $response, $request, $objectManager, $helper);
    }

    /**
     * delete customer.
     *
     * @api
     *
     * @param string $customerToken customer customerToken
     *
     * @return Webkul\GdprCompliance\Api\Data\ResponseInterface
     */
    public function deletecustomer($customerToken)
    {
        try {
            $this->customerId = $this->helper->getCustomerByToken($customerToken) ?? 0;
            if (!$this->customerId && $customerToken != "") {
                $returnArray['success'] = false;
                $returnArray["message"] = __(
                    "Customer you are requesting does not exist, so you need to logout."
                );

                return $this->getResponse($returnArray);
                    
            }
            $customer = $this->_customerRepository->getById($this->customerId);
            $customerEmail = $customer->getEmail();
            $blockedEmails = $this->helper->getConfigData("gdpr_compliance/general/emails") ?? "";
            $blockedEmails = array_map('trim', explode(",", $blockedEmails));
            if (in_array($customerEmail, $blockedEmails)) {
                $returnArray['success'] = false;
                $returnArray["message"] = __(
                    "Customer you are requesting is not allowed to delete his/her account."
                );
                return $this->getResponse($returnArray);
            }
            $collection = $this->deviceTokenFactory 
                ->create()
                ->getCollection()
                ->addFieldToFilter("customer_id", $this->customerId);
                
            foreach ($collection as $eachToken) {
                $this->deviceTokenFactory->create()->load($eachToken->getId())->setCustomerId(0)->save();
            }
            $this->customerSession->unsetAll();
            $this->coreSession->unsetAll();
            $this->_customerRepository->deleteById($this->customerId);
            $returnArray['success'] = true;
            $returnArray['message'] = __("Customer removed successfully.");
            return $this->getResponse($returnArray);
        } catch (\Exception $e) {
            $this->helper->printLog($e->getMessage());
            $returnArray['success'] = false;
            $returnArray['message'] = __($e->getMessage());
            return $this->getResponse($returnArray);
        } 
    }

    /**
     * getJsonResponse returns json response.
     *
     * @param array $responseContent
     *
     * @return Webkul\GdprCompliance\Api\Data\ResponseInterface
     */
    protected function getJsonResponse($responseContent = [])
    {
        $res = $this->_objectManager->get("\Webkul\GdprCompliance\Api\Data\ResponseInterface");
        $res->setSuccess($responseContent['success']);
        $res->setMessage($responseContent['message']);
        return $res;
    }

}