<?php

namespace App\EventSubscriber;


use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\Customer;
use App\Entity\Message;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;



class messageSubscriber implements EventSubscriberInterface
{
    private $security;


    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public static function getSubscribedEvents()
    {
        return [
            KernelEvents::VIEW =>   ['setMessage', EventPriorities::POST_WRITE],


        ];
    }


    public function setMessage(ViewEvent $event)
    {

        $message =  $event->getControllerResult();
        $method = $event->getRequest()->getMethod();

        if ($message instanceof Message &&  $method === "POST") {

            $regId = '841014821140';
            $dType = 0;
            $arrNotification = array();
            $arrNotification["body"] = "PHP Push Notification";
            $arrNotification["title"] = "PHP Push Notification";
            $arrNotification["sound"] = "default";

            $this->sendPushNotification($regId, $arrNotification,   $dType);
        }
    }


    public function sendPushNotification($registatoin_ids, $notification, $device_type)
    {

        $apiKey = 'AAAAc_kpHXM:APA91bGtlBHBhweMEQufz-Fa9Z4OtjsFaB5Nz5Rf2vLA6q7dKAsV44uW3tnBWlVPMzutoAVioAQw_bf6uOD1B9o2k_6HYYBW3ultbngfV8i8KQF2Cv6Fcmi72Z5Rw51GiO6lA30Y9ee0';

        $url = 'https://fcm.googleapis.com/fcm/send';
        if ($device_type == "Android") {
            $fields = array(
                'to' => $registatoin_ids,
                'data' => $notification
            );
        } else {
            $fields = array(
                'to' => $registatoin_ids,
                'notification' => $notification
            );
        }


        $headers = array('Authorization:key=' .  $apiKey, 'Content-Type:application/json');

        // Open connection
        $ch = curl_init();
        // Set the url, number of POST vars, POST data
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // Disabling SSL Certificate support temporarly
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($ch));
        }
        curl_close($ch);
    }
}
