<?php
namespace App\Traits;

use Illuminate\Support\Facades\Http;

trait OneSignalPushTrait
{
    public function sendToUser($userId, $title, $message, $url = null, $data = [])
    {
        return $this->sendPush([
            'include_external_user_ids' => [(string) $userId],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $url,
            'data' => $this->normalizeData($data),
        ]);
    }

    public function sendToAllUsers($title, $message, $url = null, $data = [])
    {
        return $this->sendPush([
            'included_segments' => ['All'],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $url,
            'data' => $this->normalizeData($data),
        ]);
    }

    public function sendToGuestsOnly($title, $message, $url = null, $data = [])
    {
        return $this->sendPush([
            'filters' => [
                ['field' => 'external_user_id', 'relation' => 'does_not_exist'],
            ],
            'headings' => ['en' => $title],
            'contents' => ['en' => $message],
            'url' => $url,
            'data' => $this->normalizeData($data),
        ]);
    }

    private function normalizeData($data): object
    {
        if (is_array($data) && count($data) === 0) {
            return new \stdClass();
        }
        return (object) $data;
    }
    private function sendPush(array $payload)
    {
        $payload['app_id'] = config('onesignal.app_id');

        return Http::withHeaders([
            'Authorization' => 'Basic ' . config('onesignal.rest_api_key'),
            'Accept' => 'application/json',
            'Content-Type' => 'application/json',
        ])->post('https://onesignal.com/api/v1/notifications', $payload)->json();
    }
}
