<?php

namespace App\Modules\Company\Notification;

use App\Http\Resources\Company\Notification as NotificationsResource;
use App\Models\Notifications as NotificationsModel;
use App\Traits\SortingTraits;
use App\Traits\UserTraits;

class Notification {
    use SortingTraits, UserTraits;

    public function getData($payload)
    {
        // sorting
        $sortField = $this->sortField($payload, 'created_at');
        $sortOrder = $this->sortOrder($payload, 'desc');

        $companyId = $this->getCurrentUser()->company_id;
        return NotificationsResource::collection(
            NotificationsModel::select(
                'notifications.id',
                'notifications.link',
                'notifications.message',
                'notifications.is_read',
                'notifications.created_at')
                ->where('notifications.company_id', $companyId)
                ->orderBy($sortField, $sortOrder)
                ->paginate(20)
        )->additional(['meta' => [
            'total_unread_notifications' => $this->getTotalUnreadNotifications($companyId),
        ]])->response()->setStatusCode(201);
    }

    public function getTotalUnreadNotifications($companyId)
    {
        return NotificationsModel::where('notifications.company_id', $companyId)
            ->where('notifications.is_read', 0)
            ->get()
            ->count();
    }

    public function readNotifications($payload)
    {
        $id = $payload->id;
        $company_id = $this->getCurrentUser()->company_id;
        NotificationsModel::where('id', $id)
            ->where('company_id', $company_id)
            ->update(['is_read' => 1]);
        return response()->json(201);
    }
}