<?php

namespace App\Broadcasting;

use App\Components\Functions;
use App\Models\Token;
use App\Models_v2\DatabaseNotification;
use App\Models_v2\MessageRead;
use App\User;
use Illuminate\Notifications\Notification;
use LaravelFCM\Message\OptionsBuilder;
use LaravelFCM\Message\PayloadDataBuilder;
use LaravelFCM\Message\PayloadNotificationBuilder;

class PushNotification {
	/**
	 * Create a new channel instance.
	 *
	 * @return void
	 */
	public function __construct() {
		//
	}

	/**
	 * Authenticate the user's access to the channel.
	 *
	 * @param \App\User $user
	 *
	 * @return array|bool
	 */

	public function send( $notifiable, Notification $notification ) {
		$message = $notification->toPush( $notifiable );
		if ( isset( $message['find_session_id'] ) ) {
			$findSessionId = $message['find_session_id'];

			$dbNotification = DatabaseNotification::find( $notification->id );
			if ( ! empty( $dbNotification ) ) {
				$dbNotification->forceFill( [					'find_session_id' => $findSessionId
				] )
				               ->save();
			}
		}

		$userId = $notifiable->id;
		$tokens = Token::query()
		               ->where( 'user_id', $userId )
		               ->groupBy( 'token' )
		               ->pluck( 'token' )
		               ->toArray();

		$user               = User::query()->find( $userId );
		$unreadNotification = $user->unreadNotifications()->count();
		$unreadMessage      = MessageRead::query()
		                                 ->where( 'user_id', $user->id )
		                                 ->whereNull( 'read_at' )
		                                 ->count();
		$badge              = $unreadMessage + $unreadNotification;
		$notificationId     = $notification->id;
		$content            = strip_tags( $message['body'] );
		$title              = $message['title'];


		$type = $message['type'];
		if ( isset( $message['object_id'] ) ) {
			$objectId = $message['object_id'];
		} else {
			$objectId = 0;
		}

		$optionBuilder = new OptionsBuilder();
		$optionBuilder->setTimeToLive( 60 * 20 );

		$notificationBuilder = new PayloadNotificationBuilder( $title );

		$notificationBuilder->setBody( $content )
		                    ->setBadge( $badge )
		                    ->setSound( 'default' );

		$dataBuilder = new PayloadDataBuilder();

		$payloadArr['notification_id'] = $notificationId;

		$payloadArr['title']     = $title;
		$payloadArr['badge']     = $badge;
		$payloadArr['body']      = $content;
		$payloadArr['object_id'] = $objectId;
		$payloadArr['type']      = $type;

		$payloadArr['sound']     = 'default';

		if ( isset( $message['conversation_id'] ) ) {
			$payloadArr['conversation_id'] = $message['conversation_id'];
		}


		$dataBuilder->addData( $payloadArr );

		$option       = $optionBuilder->build();
		$notification = $notificationBuilder->build();

		$data = $dataBuilder->build();

		if(!empty($tokens)) {
			foreach ( $tokens as $token ) {
				$res = \FCM::sendTo( $token, $option, $notification, $data );
			}
		}

		$user = User::find($userId);
		if($user)
        {
            $androidToken = $user->android_token;
            $iosToken = $user->ios_token;
            if(!empty($androidToken)) {
                $checkTokenV2 = Token::query()->where('token', $androidToken)->first();
                if(!$checkTokenV2) {
                    \FCM::sendTo($androidToken, $option, $notification, $data);
                }
            }
            if(!empty($iosToken)) {
                $checkTokenV2 = Token::query()->where('token', $iosToken)->first();
                if(!$checkTokenV2) {
                    \FCM::sendTo($iosToken, $option, $notification, $data);
                }
            }
        }

		// Send notification to the $notifiable instance...
	}

	public function join( User $user ) {
		//
	}
}
