<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class SendNotificationToFirebase implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $tokens;
    protected $notif_data;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tokens,$notif_data)
    {
        $this->tokens = $tokens;
        $this->notif_data = $notif_data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        // TODO : Put this in .env
        $SERVER_API_KEY = 'AAAAF5vE_jc:APA91bGGwwnvfL-I5CurHd0IJBM4kewkE5zdFrAe6VkGyaJMYewBBqcGdsR5SsAZ3MfOfhOHvsYA_lowYjh7oYxEFwprGOk3Z8QxbCzqcxjm28Y7VkgVOoH9L_E2xG1rOC7rx508nXlO';

        $data = [
            "registration_ids" => $this->tokens,
            "data" => $this->notif_data
        ];
        $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);

        curl_close($ch);
    }
}
