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

namespace Webkul\ChatNotification\Plugin;

use Webkul\MobikulCore\Model\ConstantRepo;

class SaveMessage
{
    public function __construct(
        \Webkul\MobikulCore\Helper\Data $helper,
        \Webkul\MobikulCore\Model\DeviceToken $deviceToken,
        \Magento\Framework\App\RequestInterface $request,
        \Magento\Framework\Url\DecoderInterface $urlDecoder,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Webkul\MpBuyerSellerChat\Model\CustomerDataFactory $customerDataFactory
    ) {
        $this->helper = $helper;
        $this->deviceToken = $deviceToken;
        $this->request = $request;
        $this->urlDecoder = $urlDecoder;
        $this->storeManager = $storeManager;
        $this->customerDataFactory = $customerDataFactory;
    }

    public function aroundSaveMessage(
        \Webkul\MpBuyerSellerChat\Model\SaveMessage $subject,
        \Closure $proceed,
        $senderUniqueId,
        $receiverUniqueId,
        $message,
        $dateTime,
        $msgType
    ) {
        $result = $proceed(
            $senderUniqueId,
            $receiverUniqueId,
            $message,
            $dateTime,
            $msgType
        );
        $params = $this->request->getParams();
        $response = json_decode($result, true);
        $receiverType = $params['type'] ?? "";
        if (!$response['errors']) {
            $receiverId = $this->getIdByUniqueId($response['receiver_unique_id']);
            $senderId = $this->getIdByUniqueId($response['sender_unique_id']);
            if (empty($receiverType)) {
                $collection = $this->customerDataFactory->create()
                        ->getCollection()
                        ->addFieldToFilter('unique_id', ['eq' => $response['receiver_unique_id']]);
                $receiverType = $collection->getFirstItem()->getRegisteredAs();
            }
            if ($receiverType == "seller") {
                $sellerId = $receiverId;
                $sellerUniqueId = $response['receiver_unique_id'];
                $sellerName = $response['receiver_name'];
                $customerId = $senderId;
                $customerUniqueId = $response['sender_unique_id'];
                $customerName = $response['sender_name'];
            } elseif ($receiverType == "customer") {
                $customerId = $receiverId;
                $customerUniqueId = $response['receiver_unique_id'];
                $customerName = $response['receiver_name'];
                $sellerId = $senderId;
                $sellerUniqueId = $response['sender_unique_id'];
                $sellerName = $response['sender_name'];
            }
            $message = [
                "id" => rand(1,1000),
                "body" => $response['message'],
                "title" => __("New Message from ").$response['sender_name'],
                "sound" => "default",
                "message" => $response['message'],
                "sellerId" => $sellerId,
                "sellerUniqueId" => $sellerUniqueId,
                "sellerName" => $sellerName,
                "customerId" => $customerId,
                "customerUniqueId" => $customerUniqueId,
                "customerName" => $customerName,
                "sellerProfileUrl" => $this->getProfilePic($sellerId, "seller"),
                "customerProfilePic" => $this->getProfilePic($customerId, "customer"),
                "type" => $receiverType,
                "notificationType" => "chatnotification"
            ];

            if ($msgType == 'image' || $msgType == 'file') {
                $url = $response["message"] ?? "";
                $file = $this->urlDecoder->decode(
                    str_replace('/', '', $url)
                );
                $img = ltrim($file, '/');
                $url = $this->storeManager->getStore()->getBaseUrl(
                    \Magento\Framework\UrlInterface::URL_TYPE_MEDIA
                )."marketplace/chatsystem/".$img;
                $message["image"] = $url;
                $message["banner_url"] = $url;
                unset($message["message"]);
                $message["body"] = __("Received an attachment");
            }

            $url = ConstantRepo::NOTIFICATION_URL;
            $authKey = $this->helper->getConfigData(ConstantRepo::NOTIFICATION_API_KEY);
            $headers = [
                "Authorization:key=".$authKey,
                "Content-Type:application/json",
            ];

            if ($authKey != "") {
                $customerId = 0;
                $chatCustomer = $this->customerDataFactory->create()
                    ->getCollection()
                    ->addFieldToFilter('unique_id', ['eq' => $response['receiver_unique_id']]);
                if ($chatCustomer->getSize()) {
                    $customerId = $chatCustomer->getFirstItem()->getCustomerId();
                }
                if ($customerId) {
                    $tokenCollection = $this->deviceToken->getCollection()->addFieldToFilter(
                        "customer_id",
                        $customerId
                    );
                    if ($tokenCollection->getSize()) {
                        $this->getDeviceToken($tokenCollection, $message, $url, $headers);
                    }
                }
            }
        }
        return $result;
    }

    public function getDeviceToken($tokenCollection, $message, $url, $headers)
    {
        foreach ($tokenCollection as $eachToken) {
            $fields = [
                "to" => $eachToken->getToken(),
                "data" => $message,
                "priority" => "high",
                "time_to_live" => 30,
                "delay_while_idle" => true,
                "content_available" => true
            ];
            if ($eachToken->getOs() == "ios") {
                $fields["notification"] = $message;
            }

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
            $result = curl_exec($ch);
            if ($this->isJson($result)) {
                $result = json_decode($result, true);
                if ($result["success"] == 0 && $result["failure"] == 1) {
                    $eachToken->delete();
                }
            }
        }
    }

    public function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    public function getIdByUniqueId($uniqueId)
    {
        $chatCustomer = $this->customerDataFactory->create()
                    ->getCollection()
                    ->addFieldToFilter('unique_id', ['eq' => $uniqueId]);
        return $chatCustomer->getFirstItem()->getCustomerId();
    }

    public function getProfilePic($customerId, $registeredAs)
    {
        $collection = $this->customerDataFactory->create()
                        ->getCollection()
                        ->addFieldToFilter('customer_id', ['eq' => $customerId])
                        ->addFieldToFilter('registered_as', ['eq' => $registeredAs]);
        if ($collection->getSize()) {
            $url = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).
            'mpchatsystem/profile/'.$customerId;
            if ($collection->getFirstItem()->getImage()) {
                return $url.'/'.$collection->getFirstItem()->getImage();
            }
        }
        return "";
    }
}
