<?php

namespace App\Notifications;

use App\Channels\OneSignalChannel;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class PushNotificationPropertyUser extends Notification implements ShouldQueue
{

    use Queueable;

    public $tries = 2;
    public $timeout = 60;

    public $param;

    public function __construct(
        $param
    )
    {
        $this->param = $param;
    }

    public function via($notifyRoutes)
    {
        return [OneSignalChannel::class];
    }

    public function toOneSignal($notifyRoutes)
    {

        $oneSignalService = App::make("App\Core\Service\OneSignalService");
        $userPropertyMappingService = App::make("App\Core\Service\UserPropertyMappingService");

        $restUrl = 'https://onesignal.com/api/v1/notifications';

        if (isset($this->param['property_id']) && !empty($this->param['property_id'])) {

            $propertyUserListRequest = [
                'criteria' => [
                    ['field' => 'status', 'condition' => '=', 'value' => 1],
                    ['field' => 'property_id', 'condition' => '=', 'value' => $this->param['property_id']],
                ],
                'with' => ['user']
            ];
            $propertyUserList = $userPropertyMappingService->select($propertyUserListRequest);

            if ($propertyUserList['status'] == 'success') {
                $propertyUserListCollection = collect($propertyUserList['data']);
                $oneSignalPlayerIds = $propertyUserListCollection->where('user.onesignal_key', '!=', null)->pluck('user.onesignal_key')->toArray();

                if (!empty($oneSignalPlayerIds)) {

                    $payloadJson = [
                        'include_player_ids' => $oneSignalPlayerIds,
                        'headings' => [
                            'en' => $this->param['subject']
                        ],
                        'contents' => [
                            'en' => $this->param['message']
                        ]
                    ];

                    if (isset($this->param['subtitle'])) {
                        $payloadJson['subtitle'] = [
                            'en' => $this->param['subtitle']
                        ];
                    }

                    if (isset($this->param['url'])) {
                        //$payloadJson['url'] = $this->param['url'];
                        $payloadJson['data']['url'] = $this->param['url'];
                    }

                    $sendOneSignalPushNotification = $oneSignalService->sendOneSignalPushNotification($restUrl, $payloadJson);

                }


            }


        }

    }
}
