<?php

namespace App\Http\Traits;

use Edujugon\PushNotification\PushNotification;

use App\Models\Message;

use App\Models\FcmToken;

/**
 * Trait FcmNotification
 *
 * @package App\Http\Traits
 */
trait FcmNotification
{

    /*
     * Log push notifications into files
     */
    protected static $debug = false;

    /**
     * Send fcm message to usergroup
     *
     * @param \App\Models\Message $message
     * @return bool
     */
    public static function pushNotification(Message $message)
    {
        // Retrieve group and user
        $users = $message->group->users;

        $data = $message->apiOutputData(
            [
                'groupname'      => $message->group->groupname,
                'group_nb_users' => $users->count()
            ]
        );
        $tokensCollection = FcmToken::select('token')
            ->whereIn('useroid', $users->pluck('oid'))
            ->where('useroid', '!=', $message->useroid)
            ->get()
            ->pluck('token')
            ->toArray();

        self::sendAndroidNotifications($tokensCollection, $data);

        return true;
    }

    /**
     * Send fcm message to provided tokens
     *
     * @param array $tokens
     * @param array $data
     */
    private static function sendAndroidNotifications($tokens, $data)
    {
        if (self::$debug) {
            self::writeLog(' >>>>> Push start ' . date("Y-m-d H:i:s") . ' <<<<<< ');
        }

        if (0 == count($tokens)) {
            if (self::$debug) {
                self::writeLog('No Android tokens found');
            }

            return;
        }

        $pushNotification = (new PushNotification('fcm'))->setMessage([
            'data'  => $data,
            'sound' => 'default'
        ])
            ->setDevicesToken($tokens)
            ->send();

        self::removeTokens(
            $pushNotification->getUnregisteredDeviceTokens()
        );

        if (self::$debug) {
            self::writeLog('- Android feedback: ' . json_encode($pushNotification->getFeedback()));
            self::writeLog('- Android tokens: ' . implode(', ', $tokens));
            self::writeLog('- Android unregistered tokens: ' . implode(', ', $pushNotification->getUnregisteredDeviceTokens()));
        }
    }

    /**
     * Remove unregistered tokens from DB
     *
     * @param array $tokens
     */
    private static function removeTokens($tokens)
    {
        if ( ! is_array($tokens) || 0 == count($tokens)) {
            return;
        }

        FcmToken::whereIn('token', $tokens)->delete();
    }

    /**
     * Write log file
     *
     * @param string $data
     * @return void
     */
    private static function writeLog($data)
    {
        file_put_contents(storage_path() . '/push_logs/fcm_notifications.log', $data . "\n", FILE_APPEND);
    }
}