<?php
namespace App\Modules\Mobile\Worker;

use Illuminate\Support\Facades\Auth;
use App\Models\MobileNotification;
use App\Http\Resources\Mobile\Notifications as MobileNotificationResource;

class Notification
{
    public function fetchNotifications($payload){
        $workerID = Auth::user()->id;
        $notificationType = $payload->type;

        return MobileNotificationResource::collection(
            MobileNotification::where('worker_id', $workerID)
            ->where('type', $notificationType)
            ->orderByDesc('id')
            ->paginate(10)

        )->additional(['meta' => [
            'total_unread_notifications' => $this->getTotalUnreadNotification($payload),
        ]])
        ->response()
        ->setStatusCode(201);
    }

    public function setToRead($id){
        
        $notifData = array(
            'is_read' => true,
        );
        $updateTransaction = $this->updateNotification($id, $notifData);

        if($updateTransaction){
            return response()->json(['success' => 'Successfully Set to Read.']); 
        }
        return response()->json(['error' => 'Something went wrong.']); 
    }

    public function updateNotification($id, $data){
        return MobileNotification::where('id', $id)->update($data);
    }

    public function getTotalUnreadNotification($payload)
    {
        $workerID = Auth::user()->id;
        $notificationType = $payload->type;
        return MobileNotification::where('worker_id', $workerID)
            ->where('type', $notificationType)
            ->where('is_read', false)
            ->get()
            ->count();
    }
}