<?php

namespace App\Core\Service;

use App\Exceptions\ApiErrorException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;

use Log;
use Exception;


class OneSignalService
{

    public function __construct(

    )
    {
        $this->restClient = new Client();
    }

    public function sendOneSignalPushNotification($restUrl , $payloadJson)
    {

        $oneSignalAppId = '1d4372b2-4f8f-47c3-aab0-a9e38f2ad4c3';

        $payloadJson['app_id'] = $oneSignalAppId;

        $response = ['status' => false, 'message' => ''];
        try {

            $result = $this->restClient->post(
                $restUrl,
                [
                    'headers' => [
                        'Authorization' => 'Basic ODQ2NGEzMTUtM2Y2OS00MzczLWE2MmEtMjNkN2ZiYzg0ZTY5',
                        'Content-Type' => 'application/json',
                    ],
                    'body' => json_encode($payloadJson)
                ]
            );

            $getResponseBody = $result->getBody()->getContents();
            $getResponseData = $getResponseBody ? json_decode($getResponseBody,1) : [];

            if(isset($getResponseData['errors']) && !empty($getResponseData['errors'])) {
                $response['message'] = isset($getResponseData['errors']) ? implode(',', $getResponseData['errors']) : 'Servis Hatası!';
            } else {
                $response = [
                    'status' => true,
                    'data' => $getResponseData,
                ];
            }

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return $response;
    }


}
