<?php

namespace Modules\Core\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Core\Entities\User;
use NotificationChannels\WebPush\PushSubscription;
use function PHPSTORM_META\elementType;

class NotificationController extends Controller
{
    /**
     * this function used to get notification
     * @return Response
     */
    function getNotifications(){
        $data=Auth::user()->notifications;
        return response()->json([
            'data'  => $data,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    /**
     * this function used to get unread notification
     * @return Response
     */
    function getUnreadNotifications(){
        $data=Auth::user()->notifications->where('read_at',null);
        return $data;
    }
    /**
     * this function used to mark as read un read notifications
     * @return Response
     */
    function notification_read(){
        Auth::user()->unreadNotifications
            ->markAsRead();
        return response()->json([
            'data'  => true,
            'message'=>__('mg.done'),
            'status' => 200
        ]);
    }

    /**
     * this function used to get token and end point for notifications subscription
     * @param Request $request
     * @return Response
     */
    function subscription(Request $request){
        $check=PushSubscription::where('user_id',Auth::user()->id)->first();
        if($check!=null){
            $check->update([
                'endpoint'=>$request->endpoint,
                'public_key'=>$request->public_key,
                'auth_token'=>$request->auth_token
                ]);
        }else{
            PushSubscription::create([
                'user_id'=>Auth::user()->id,
                'endpoint'=>$request->endpoint,
                'public_key'=>$request->public_key,
                'auth_token'=>$request->auth_token
            ]);
        }
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }
    function sub(Request $request){
        $user = User::find(1);
        $user->updatePushSubscription($request->endpoint, $request->key, $request->token);
    }
    function deleteSubscription(){
        PushSubscription::where('user_id',Auth::user()->id)->delete();
        return response()->json([
            'data'  => true,
            'message'=>'ok',
            'status' => 200
        ]);
    }


}
