<?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\ChatInterface;
use Magento\Framework\App\Filesystem\DirectoryList;

class ChatHistory implements ChatInterface
{

    /**
     * @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\CustomerListInterface
     */
    protected $_customerListInterface;

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

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

    /**
     * @var \Webkul\MpBuyerSellerChatApi\Api\Data\ChatHistoryInterfaceFactory
     */
    protected $_chatHistory;

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\LoadHistory
     */
    protected $_loadHistory;

    /**
     * @var \Webkul\MpBuyerSellerChat\Api\Data\MessageInterfacefactory
     */
    protected $_messageFactory;

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\CustomerAvailable
     */
    protected $_customerAvailable;

    /**
     * @var \Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterfaceFactory
     */
    protected $_saveChatInterface;

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\SaveMessage
     */
    protected $_saveMessage;

    // /**
    //  * @var Webkul\Marketplace\Data\Translate
    //  */
    // protected $googleTranslate;

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\ChangeStatus
     */
    protected $_changeStatus;

    /**
     * @var \Magento\MediaStorage\Model\File\UploaderFactory
     */
    protected $_fileUploaderFactory;

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\CustomerDataFactory
     */
    protected $chatCustomerFactory;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $_storeManager;

    protected $_saveCustomer;

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

    /**
     * @var \Webkul\MpBuyerSellerChat\Model\EnableSellerChat
     */
    protected $_enableSellerChat;
    

    /**
     * @param Emulation                                                         $emulate,
     * @param \Magento\Framework\Filesystem                                     $filesystem,
     * @param \Webkul\Mobikul\Helper\Data                                       $mobikulHelper,
     * @param \Magento\Framework\App\RequestInterface                           $request,
     * @param \Magento\Customer\Model\Session                                   $customerSession,
     * @param \Magento\Framework\App\ResponseInterface                          $response,
     * @param \Webkul\Marketplace\Helper\Translate                              $googleTranslate,
     * @param \Webkul\MpBuyerSellerChat\Model\LoadHistory                       $loadHistory,
     * @param \Magento\Store\Model\StoreManagerInterface                        $storeManager,
     * @param \Webkul\MpBuyerSellerChat\Model\SaveMessage                       $saveMessage,
     * @param \Webkul\MpBuyerSellerChat\Model\ChangeStatus                      $changeStatus,
     * @param \Webkul\MpBuyerSellerChat\Model\CustomerAvailable                 $customerAvailable,
     * @param \Magento\MediaStorage\Model\File\UploaderFactory                  $fileUploaderFactory,
     * @param \Webkul\MpBuyerSellerChat\Model\CustomerDataFactory               $chatCustomerFactory,
     * @param \Webkul\MpBuyerSellerChat\Api\Data\MessageInterfaceFactory        $messageFactory,
     * @param \Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterfaceFactory    $saveChatInterface,
     * @param \Webkul\MpBuyerSellerChatApi\Api\Data\ChatHistoryInterfaceFactory $chatHistoryInterface
     */
    public function __construct(
        Emulation $emulate,
        \Magento\Framework\Filesystem $filesystem,
        \Webkul\MobikulCore\Helper\Data $mobikulHelper,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Framework\App\ResponseInterface $response,
        // \Webkul\Marketplace\Helper\Translate $googleTranslate,
        \Webkul\MpBuyerSellerChat\Model\LoadHistory $loadHistory,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Webkul\MpBuyerSellerChat\Model\SaveMessage $saveMessage,
        \Webkul\MpBuyerSellerChat\Model\ChangeStatus $changeStatus,
        \Webkul\MpBuyerSellerChat\Model\SaveCustomer $saveCustomer,
        \Webkul\MpBuyerSellerChat\Model\EnableSellerChat $enableSellerChat,
        \Webkul\MpBuyerSellerChat\Model\CustomerAvailable $customerAvailable,
        \Magento\MediaStorage\Model\File\UploaderFactory $fileUploaderFactory,
        \Webkul\MpBuyerSellerChat\Model\CustomerDataFactory $chatCustomerFactory,
        \Webkul\MpBuyerSellerChat\Api\Data\MessageInterfaceFactory $messageFactory,
        \Webkul\MpBuyerSellerChatApi\Api\Data\CustomerInterface $customerInterface,
        \Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterfaceFactory $saveChatInterface,
        \Webkul\MpBuyerSellerChatApi\Api\Data\ChatHistoryInterfaceFactory $chatHistoryInterface
    ) {
        $this->_emulate             = $emulate;
        $this->_request             = $request;
        $this->_response            = $response;
        $this->_filesystem          = $filesystem;
        $this->_saveMessage         = $saveMessage;
        $this->_loadHistory         = $loadHistory;
        $this->_saveCustomer        = $saveCustomer;
        $this->_chatHistory         = $chatHistoryInterface;
        $this->_changeStatus        = $changeStatus;
        $this->_storeManager        = $storeManager;
        $this->_mobikulHelper       = $mobikulHelper;
        $this->_messageFactory      = $messageFactory;
        $this->_customerSession     = $customerSession;
        // $this->googleTranslate      = $googleTranslate;
        $this->_enableSellerChat    = $enableSellerChat;
        $this->_customerInterface   = $customerInterface;
        $this->_customerAvailable   = $customerAvailable;
        $this->_saveChatInterface   = $saveChatInterface;
        $this->chatCustomerFactory  = $chatCustomerFactory;
        $this->_fileUploaderFactory = $fileUploaderFactory;
        $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->_mobikulHelper->printLog($postValues);
        $this->_mobikulHelper->printLog($this->_request->getFiles());
        $this->_request->setPostValue($postValues);
    }

    /**
     * return seller customer chat history
     *
     * @return Webkul\MpBuyerSellerChatApi\Api\Data\ChatHistoryInterface
     */
    public function getChatHistory()
    {
        $this->_mobikulHelper->printLog("getChatHistory");
        $wholeData        = $this->_request->getPostValue();
        $type             = $wholeData["type"]             ?? "";
        $storeId          = $wholeData["storeId"]          ?? 1;
        $loadTime         = $wholeData["loadTime"]         ?? "";
        $receiverId       = $wholeData["receiverId"]       ?? "";
        $customerToken    = $wholeData["customerToken"]    ?? "";
        $senderUniqueId   = $wholeData["senderUniqueId"]   ?? "";
        $receiverUniqueId = $wholeData["receiverUniqueId"] ?? "";
        $customerId       = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey          = $this->_request->getHeader("authKey");
        $authData         = $this->_mobikulHelper->isAuthorized($authKey);
        $response         = $this->_chatHistory->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                // if (!$this->_customerSession->getCustomerId()) {
                //     $this->_customerSession->setCustomerId($customerId);
                //     $customer = $this->_customerSession->getCustomer();
                //     $this->_customerSession->setCustomerAsLoggedIn($customer);
                // }
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $urlDecoder = $objectManager->create('\Magento\Framework\Url\DecoderInterface');
                $history = $this->_loadHistory->loadHistory($senderUniqueId, $receiverUniqueId, $loadTime);
                $availability = json_decode($this->_customerAvailable->check($receiverId, $type), true);
                $response->setSuccess(true);
                $response->setStatus((boolean)$availability["available"] ?? false);
                $response->setLocale($availability["locale"] ?? "en");
                $msglist['messageList'] = [];
                $msgArray = json_decode($history);
                foreach ($msgArray->messages as $key => $value) {
                    if ($value->message_type == "image") {
                        $url = $value->message;
                        $file = $urlDecoder->decode(
                            str_replace('/', '', $url)
                        );
                        $img = ltrim($file, '/');
                        $url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."marketplace/chatsystem/".$img;
                        $value->message = $url;
                    } elseif ($value->message_type == "file") {
                        $url = $value->message;
                        $file = $urlDecoder->decode(
                            str_replace('/', '', $url)
                        );
                        $img = ltrim($file, '/');
                        $url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."marketplace/chatsystem/".$img;
                        $value->message = $url;
                    }
                    $msglist['messageList'][] = $value;
                }
                $response->setMessageList(json_encode($msglist));
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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;
    }

    /**
     * return translated message data
     *
     * @return Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterface
     */
    public function saveMessage()
    {
        $this->_mobikulHelper->printLog("saveMessage");
        $wholeData        = $this->_request->getPostValue();
        $type             = $wholeData["type"]             ?? "";
        $source           = $wholeData["source"]           ?? "";
        $target           = $wholeData["target"]           ?? "";
        $msgType          = $wholeData["msgType"]          ?? "";
        $storeId          = $wholeData["storeId"]          ?? 1;
        $message          = $wholeData["message"]          ?? "";
        $dateTime         = $wholeData["dateTime"]         ?? "";
        $receiverId       = $wholeData["receiverId"]       ?? "";
        $customerToken    = $wholeData["customerToken"]    ?? "";
        $senderUniqueId   = $wholeData["senderUniqueId"]   ?? "";
        $receiverUniqueId = $wholeData["receiverUniqueId"] ?? "";
        $customerId       = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey          = $this->_request->getHeader("authKey");
        $authData         = $this->_mobikulHelper->isAuthorized($authKey);
        $response         = $this->_saveChatInterface->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                $this->_customerSession->setCustomerId($customerId);
                $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                $customer = $this->_customerInterface;
                if ($msgType == "image" || $msgType == "file") {
                    $files = $this->_request->getFiles();
                    if (!empty ($files["message"])) {
                        $message = $files["message"]["name"];
                        $imageUploadPath = $this->_filesystem->getDirectoryRead(
                            DirectoryList::MEDIA
                        )->getAbsolutePath(
                            'marketplace/chatsystem'
                        );
                        if (!is_dir($imageUploadPath))  {
                            mkdir($imageUploadPath, 0755, true);
                        }
                        try  {
                            $uploader = $this->_fileUploaderFactory->create(["fileId"=>"message"]);
                            $uploader->setAllowedExtensions(["jpeg", "jpg", "png", "gif", "zip", "doc", "pdf", "rar", "txt", "odt", "mp4", "mkv", "apk"]);
                            $uploader->setAllowRenameFiles(false);
                            $uploader->setFilesDispersion(false);
                            $uploader->save($imageUploadPath);
                        } catch (\Exception $e)  {
                            echo $e->getMessage();die;
                        }
        
                    }
                }
                if (!$senderUniqueId || $senderUniqueId == "") {
                    $responseData = $this->_saveCustomer->save($message, $receiverId, $receiverUniqueId, $dateTime);
                    $responseData = json_decode($responseData, true);
                    $customer->setId($responseData["customerId"]);
                    $customer->setName($responseData["customerName"]);
                    $customer->setEmail($responseData["customerEmail"]);
                    $customer->setStatus($responseData["chatStatus"]);
                    $customer->setUniqueId($responseData["customerUniqueId"]);
                    $customer->setProfileImage($responseData["customerImage"]);
                    $response->setCustomer($customer);
                } else {
                    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                    $urlDecoder = $objectManager->create('\Magento\Framework\Url\DecoderInterface');
                    $responseData = $this->_saveMessage->saveMessage($senderUniqueId, $receiverUniqueId, $message, $dateTime, $msgType);
                    if ($msgType == "image") {
                        $url = json_decode($responseData, true)["message"] ?? "";
                        $code = $url;
                        $file = $urlDecoder->decode(
                            str_replace('/', '', $url)
                        );
                        $img = ltrim($file, '/');
                        $url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."marketplace/chatsystem/".$img;
                        $response->setAttachmentUrl($url);
                    } elseif ($msgType == "file") {
                        $url = json_decode($responseData, true)["message"] ?? "";
                        $code = $url;
                        $file = $urlDecoder->decode(
                            str_replace('/', '', $url)
                        );
                        $img = ltrim($file, '/');
                        $url = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA)."marketplace/chatsystem/".$img;
                        $response->setAttachmentUrl($url);
                    }
                }
                $response->setCustomer($customer);
                $availability = json_decode($this->_customerAvailable->check($receiverId, $type), true);
                $response->setSuccess(true);
                $response->setStatus((boolean)$availability["available"] ?? false);
                $response->setLocale($availability["locale"] ?? "en");
                $message = (string)json_encode($message);
                // $result = $this->googleTranslate->translate([$message], $source, $target);
                $response->setTranslatedMessage($code ?? $message);
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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;
    }

    /**
     * change status
     *
     * @return Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterface
     */
    public function changeStatus()
    {
        $this->_mobikulHelper->printLog("changeStatus");
        $wholeData     = $this->_request->getPostValue();
        $type          = $wholeData["type"]          ?? "";
        $status        = $wholeData["status"]        ?? "";
        $storeId       = $wholeData["storeId"]       ?? 1;
        $customerToken = $wholeData["customerToken"] ?? "";
        $customerId = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey    = $this->_request->getHeader("authKey");
        $authData   = $this->_mobikulHelper->isAuthorized($authKey);
        $response   = $this->_saveChatInterface->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                $this->_customerSession->setCustomerId($customerId);
                $this->_changeStatus->changeStatus($status, $type);
                $this->_customerSession->unsetCustomerId();
                $this->_emulate->stopEnvironmentEmulation($environment);
                $response->setSuccess(true);
                $response->setMessage(__("status changed"));
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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;
    }

    /**
     * upload profile pic
     *
     * @return Webkul\MpBuyerSellerChatApi\Api\Data\SaveChatInterface
     */
    public function uploadProfilePic()
    {
        $this->_mobikulHelper->printLog("uploadProfilePic");
        $wholeData     = $this->_request->getPostValue();
        $type          = $wholeData["type"]          ?? "";
        $storeId       = $wholeData["storeId"]       ?? 1;
        $customerToken = $wholeData["customerToken"] ?? "";
        $customerId    = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey       = $this->_request->getHeader("authKey");
        $authData      = $this->_mobikulHelper->isAuthorized($authKey);
        $response      = $this->_saveChatInterface->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                $path = $this->_filesystem->getDirectoryRead(
                    DirectoryList::MEDIA
                )->getAbsolutePath(
                    'mpchatsystem/profile/'.$customerId
                );
                $url = $this ->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
                        'mpchatsystem/profile/'.$customerId;
                try {
                    /** @var $uploader \Magento\MediaStorage\Model\File\Uploader */
                    $uploader = $this->_fileUploaderFactory->create(['fileId' => 'file']);
                    $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                    $uploader->setAllowRenameFiles(true);
                    $uploader->setFilesDispersion(false);
                    $uploader->setAllowCreateFolders(true);
                    $result = $uploader->save($path);
                    $collection = $this->chatCustomerFactory->create()
                        ->getCollection()
                        ->addFieldToFilter('customer_id', ['eq' => $customerId])
                        ->addFieldToFilter('registered_as', ['eq' => $type]);
                    if ($collection->getSize()) {
                        $entityId = $collection->getFirstItem()->getEntityId();
                        $model = $this->chatCustomerFactory->create()->load($entityId);
                        $model->setImage($result['file']);
                        $model->setId($entityId);
                        $model->setEntityId($entityId);
                        $model->save();
                    }
                    $response->setSuccess(true);
                    $response->setAttachmentUrl($url.'/'.$result['file']);
                    $response->setMessage(
                        __('Image updated successfully.')
                    );
                } catch (\Exception $e) {
                    $response->setMessage(
                        $e->getMessage()
                    );
                }
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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 changeChatStatus()
    {
        $this->_mobikulHelper->printLog("changeChatStatus");
        $wholeData     = $this->_request->getPostValue();
        
        $storeId       = $wholeData["storeId"]             ?? 1;
        $blockReason   = $wholeData["blockReason"]         ?? "";
        $customerToken = $wholeData["customerToken"]       ?? "";
        $customerUniqueId = $wholeData["customerUniqueId"] ?? "";
        $customerId    = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey       = $this->_request->getHeader("authKey");
        $authData      = $this->_mobikulHelper->isAuthorized($authKey);
        $response      = $this->_saveChatInterface->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                try {
                    $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                    $data = [
                        "customerUniqueId" => $customerUniqueId,
                        "block_reason"   => $blockReason
                    ];
                    $this->_request->setParam("customerData", $data);
                    $responseData = $this->_customerAvailable->blockCustomer($customerId);
                    $responseData = json_decode($responseData, true);
                    $response->setSuccess(!$responseData["errors"]);
                    $response->setMessage($responseData["msg"]);
                } catch (\Exception $e) {
                    $response->setMessage(
                        $e->getMessage()
                    );
                }
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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 enableChat()
    {
        $this->_mobikulHelper->printLog("enableChat");
        $wholeData     = $this->_request->getPostValue();
        $storeId       = $wholeData["storeId"]             ?? 1;
        $customerToken = $wholeData["customerToken"]       ?? "";
        $customerId    = $this->_mobikulHelper->getCustomerByToken($customerToken) ?? 0;
        $authKey       = $this->_request->getHeader("authKey");
        $authData      = $this->_mobikulHelper->isAuthorized($authKey);
        $response      = $this->_saveChatInterface->create();
        if ($authData["code"] == 1) {
            if ($customerId) {
                try {
                    $environment = $this->_emulate->startEnvironmentEmulation($storeId);
                    $customer = $this->_customerInterface;
                    $this->_customerSession->setCustomerId($customerId);
                    $responseData = $this->_enableSellerChat->enable();
                    $responseData = json_decode($responseData, true);
                    $customer->setId($responseData["customer_id"]);
                    $customer->setStatus($responseData["chat_status"]);
                    $customer->setUniqueId($responseData["unique_id"]);
                    $response->setCustomer($customer);
                    $response->setSuccess(!$responseData["error"]);
                    $response->setMessage($responseData["message"]);
                } catch (\Exception $e) {
                    $response->setMessage(
                        $e->getMessage()
                    );
                }
                $this->_emulate->stopEnvironmentEmulation($environment);
            } else {
                $response->setSuccess(false);
                $response->setMessage(__("Something went wrong."));
            }
        } 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;
    }
}
