<?php
/**
 * Webkul Software.
 * 
 * PHP version 7.0+
 *
 * @category  Webkul
 * @package   Webkul_MobikulCore
 * @author    Webkul <support@webkul.com>
 * @copyright 2010-2019 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\MobikulCore\Controller\Adminhtml\Notification;

class Push extends \Webkul\MobikulCore\Controller\Adminhtml\Notification
{
    public function execute()
    {
        $resultRedirect  = $this->resultRedirectFactory->create();
        $notificationId  = $this->initCurrentNotification();
        if (!empty($notificationId)) {
            $model       = $this->notificationRepository->getById($notificationId);
            $baseTmpPath = "mobikul/notification/";
            $target      = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA).$baseTmpPath;
            $bannerUrl   = "";
            if ($model->getFilename() != "") {
                $bannerUrl = $target.$model->getFilename();
            }
            $message     = [
                "id"               => $model->getId(),
                "body"             => $model->getContent(),
                "title"            => $model->getTitle(),
                "sound"            => "default",
                "message"          => $model->getContent(),
                "store_id"         => $model->getStoreId(),
                "banner_url"       => $bannerUrl,
                "notificationType" => $model->getType()
            ];
            if ($model->getType() == "category" && $model->getProCatId() != "") {
                // for category //////////////////////////////////////////////////////////
                $message["categoryName"] = $this->categoryResource->getAttributeRawValue($model->getProCatId(), "name", 1);
                $message["categoryId"] = $model->getProCatId();
            } elseif ($model->getType() == "product" && $model->getProCatId() != "") {
                // for product ///////////////////////////////////////////////////////////
                $message["productName"] = $this->productResource->getAttributeRawValue($model->getProCatId(), "name", 1);
                $message["productId"] = $model->getProCatId();
            }
            $url = "https://fcm.googleapis.com/fcm/send";
            $authKey = $this->helper->getConfigData("mobikul/notification/apikey");
            $headers = [
                "Authorization : key=".$authKey,
                "Content-Type  : application/json"
            ];
            // for android ///////////////////////////////////////////////////////////////
            $topic  = $this->helper->getConfigData("mobikul/notification/andoridtopic");
            $fields = [
                "to"                => "/topics/".$topic,
                "data"              => $message,
                "priority"          => "high",
                "time_to_live"      => 30,
                "delay_while_idle"  => true,
                "content_available" => true
            ];
            $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, $this->jsonHelper->jsonEncode($fields));
            $result = curl_exec($ch);
            curl_close($ch);
            if ($this->isJson($result)) {
                $this->messageManager->addSuccess(__("Notification pushed successfully for android."));
            } else {
                $this->messageManager->addError(__("Sorry something went wrong for android."));
            }
            // for ios //////////////////////////////////////////////////////////////////////////
            $topic  = $this->helper->getConfigData("mobikul/notification/iostopic");
            $fields = [
                "to"                => "/topics/".$topic,
                "data"              => $message,
                "priority"          => "high",
                "time_to_live"      => 30,
                "notification"      => $message,
                "delay_while_idle"  => true,
                "content_available" => true
            ];
            $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, $this->jsonHelper->jsonEncode($fields));
            $result = curl_exec($ch);
            curl_close($ch);
            if ($this->isJson($result)) {
                $this->messageManager->addSuccess(__("Notification pushed successfully for iOS."));
            } else {
                $this->messageManager->addError(__("Sorry something went wrong for iOS."));
            }
        } else {
            $this->messageManager->addSuccess(__("Invalid Notification."));
        }
        return $resultRedirect->setPath("mobikul/notification/edit", ["id"=>$this->initCurrentNotification()]);
    }

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

    protected function initCurrentNotification()
    {
        return (int)$this->getRequest()->getParam("id");
    }
}
