<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Webkul_MpBuyerSellerChatApi
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */

namespace Webkul\MpBuyerSellerChatApi\Model;

use Magento\Store\Model\App\Emulation;
use Magento\Framework\Controller\ResultFactory;
use Webkul\MpBuyerSellerChatApi\Api\SellerCustomerListInterface;

class SellerCustomerList implements SellerCustomerListInterface
{

    /**
     * @param \Webkul\MpBuyerSellerChat\Block\Seller\ActiveModel
     */
    protected $_chatBlock;

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

    /**
     * @var \Magento\Framework\App\RequestInterface
     */
    protected $_request;

    /**
     * @var \Webkul\MpBuyerSellerChatApi\Api\Data\CustomerInterface
     */
    protected $_customerInterface;

    /**
     * @var \Webkul\MpBuyerSellerChatApi\Api\Data\CustomerListInterface
     */
    protected $_customerListInterface;


    /**
     * @var \Webkul\Mobikul\Helper\Data
     */
    protected $_mobikulHelper;

    /**
     * @var \Webkul\Mobikul\Model\DeviceTokenFactory
     */
    protected $_deviceToken;

    /**
     * @var \Magento\Framework\HTTP\PhpEnvironment\Response
     */
    protected $_response;


    /**
     * @param \Webkul\MpBuyerSellerChat\Block\Seller\ActiveModel $chatBlock
     */
    public function __construct(
        Emulation $emulate,
        \Magento\Framework\App\RequestInterface $request,
        \Webkul\MpBuyerSellerChat\Block\Seller\ActiveModel $chatBlock,
        \Webkul\MobikulCore\Helper\Data $mobikulHelper,
        \Magento\Customer\Model\Session $customerSession,
        \Webkul\MpBuyerSellerChatApi\Api\Data\CustomerListInterfaceFactory $customerListInterface,
        \Webkul\MpBuyerSellerChatApi\Api\Data\CustomerInterfaceFactory $customerInterface,
        \Webkul\MobikulCore\Model\DeviceTokenFactory $deviceToken,
        \Magento\Framework\App\ResponseInterface $response
    ) {
        $this->_emulate         = $emulate;
        $this->_request         = $request;
        $this->_response        = $response;
        $this->_chatBlock       = $chatBlock;
        $this->_deviceToken     = $deviceToken;
        $this->_mobikulHelper   = $mobikulHelper;
        $this->_customerSession = $customerSession;
        $this->_customerInterface = $customerInterface;
        $this->_customerListInterface = $customerListInterface;
        $header = $this->_request->getHeader('content-type');
        $postValues = $this->_request->getPostValue();
        if ($header == 'application/json') {
            $postValues = @file_get_contents('php://input');
            if ($postValues) {
                $postValues = json_decode($postValues, true);
            }
        }
        $this->_request->setPostValue($postValues);
    }

    public function getCustomerList()
    {
        $wholeData = $this->_request->getPostValue();
        // $this->_mobikulHelper->printLog($wholeData);
        $storeId   = $wholeData["storeId"] ?? 1;
        $customerToken = $wholeData["customerToken"] ?? "";
        $sellerId      = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey  = $this->_request->getHeader("authKey");
        $authData = $this->_mobikulHelper->isAuthorized($authKey);
        $response = $this->_customerListInterface->create();
        if ($authData["code"] == 1)  {
            if ($sellerId) {
                $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                $this->_customerSession->setCustomerId($sellerId);
                $chatConfigData =  $this->_chatBlock->getChatBoxConfig();
                $customerList   = $this->getCustomerData($chatConfigData["enableUserData"], $chatConfigData["blockedCustomerData"]);
                if (strpos($chatConfigData["sellerChatData"]["sellerImage"], "webapi_rest") !== false) {
                    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                    $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
                    $currentStore = $storeManager->getStore();
                    $media = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
                    $chatConfigData["sellerChatData"]["sellerImage"] = $media."avatar/noimage.png";
                }
                $response->setName($chatConfigData["sellerChatData"]["sellerName"] ?? "");
                $response->setStatus($chatConfigData["sellerChatData"]["chatStatus"] ?? 0);
                $response->setUniqueId($chatConfigData["sellerChatData"]["sellerUniqueId"] ?? "");
                $response->setCustomerList($customerList);
                $response->setProfileImage($chatConfigData["sellerChatData"]["sellerImage"] ?? "");
                $response->setTotalCustomerList(count($customerList));
                $response->setFcmKey($this->_mobikulHelper->getConfigData("mobikul/notification/apikey") ?? "");
                $response->setIosTopic($this->_mobikulHelper->getConfigData("mobikul/notification/iostopic") ?? "");
                $response->setAndroidTopic($this->_mobikulHelper->getConfigData("mobikul/notification/andoridtopic") ?? "");
                $response->setSuccess(true);
                $this->_customerSession->unsCustomerId();
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Invalid Seller"));
            }
        } else {
            $response->setSuccess(false);
            header("token: ".$authData["token"]);
            $this->_response->setHeader("token", $authData["token"], true);
            throw new \Magento\Framework\Oauth\Exception(__("Invalid Request"));
        }
        return $response;
    }

    public function getCustomerData($customerList, $blockedCustomerList)
    {
        $allCustomerListData = [];
        foreach ($customerList as $customerData) {
            if (empty($customerData["customerId"])) {
                continue;
            }
            $blockStatus = in_array($customerData["customerUniqueId"], $blockedCustomerList);
            $customer = $this->_customerInterface->create();
            if (strpos($customerData["customerImage"], "webapi_rest") !== false) {
                $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $storeManager = $_objectManager->get('Magento\Store\Model\StoreManagerInterface'); 
                $currentStore = $storeManager->getStore();
                $media = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
                $customerData["customerImage"] = $media."avatar/noimage.png";
            }
            $customer->setId($customerData["customerId"]);
            $customer->setName($customerData["customerName"]);
            $customer->setEmail($customerData["customerEmail"]);
            $customer->setToken($this->getDeviceToken($customerData["customerId"]));
            $customer->setIsBlocked($blockStatus);
            $customer->setStatus($customerData["chatStatus"]);
            $customer->setUniqueId($customerData["customerUniqueId"]);
            $customer->setProfileImage($customerData["customerImage"]);
            $customer->setCustomerToken($this->_mobikulHelper->getTokenByCustomerDetails(null, null, $customerData["customerId"]));
            $allCustomerListData[] = $customer;
        }
        return $allCustomerListData;
    }

    public function getDeviceToken($customerId)
    {
        $token = $this->_deviceToken->create()
            ->getCollection()
            ->addFieldToFilter("customer_id" , ["eq" => $customerId])
            ->getColumnValues("token");
        return implode(",", $token);
    }
}
