<?php
namespace App\Helpers;

class NotificationHelpers
{


    static function send(string $device_id, string $title, string $body)
    {
        $apiKey = env('FCM_SERVER_KEY');
        $curl = curl_init();

        curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://fcm.googleapis.com/fcm/send',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS =>'{
        "registration_ids": 
        [
            "'.$device_id.'"
        ],
        "notification":{
            "body":"'.$body.'",
            "title":"'.$title.'"
            
        }
        }',
        CURLOPT_HTTPHEADER => array(
            'Authorization: key='.$apiKey,
            'Content-Type: application/json'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
       



    }

    /**
     * Send Notifications to phone
     */

    
    static function sendNotification($device_token, $title, $body, array $dataContent = [])
    {
        $firebaseToken = $device_token;
        
        $SERVER_API_KEY = env('FCM_SERVER_KEY');
        $data = [
            "registration_ids" => [$firebaseToken],
            "notification" => [
                "title" => $title,
                "body" => $body,
            ]
        ];
        if (!empty($dataContent)) {
            $data['data'] = $dataContent;
        }
        $dataString = json_encode($data);
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
 
        $response = curl_exec($ch);
        /*
        $notif =  Notifications::create([
            'user' => $id,
            'nom' => $title,
            'notifications' => $body,
        ]);
*/ 
        return $response;
        

    }


}