<?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($request)
    {
        $response = Http::withHeaders([
            'Authorization' => 'Basic ' . get_config('one_signal_key'),
            'Content-Type'  => 'application/json',
        ])->post('https://api.onesignal.com/notifications', [
            'app_id'          => get_config('one_signal_id'), // ⚠️ use app_id here, not API key
            'included_segments' => ['All'],

            'headings' => ['en' => $request->heading],
            'contents' => ['en' => $request->message],

            'url'              => $request->url,
            'chrome_web_icon'  => $request->icon_url,
            'chrome_web_image' => $request->icon_url, // use a separate field for large image
        ]);

        return $response->json();
    }
}
