<?php

namespace Corals\User\Communication\Http\Controllers\API;

use Corals\Foundation\Http\Controllers\APIBaseController;
use Corals\User\Communication\DataTables\NotificationDataTable;
use Corals\User\Communication\Http\Requests\NotificationRequest;
use Corals\User\Communication\Models\Notification;
use Corals\User\Communication\Services\NotificationService;
use Corals\User\Communication\Transformers\API\NotificationPresenter;
use Illuminate\Http\Request;

class NotificationController extends APIBaseController
{
    protected $notificationService;

    public function __construct(NotificationService $notificationService)
    {
        $this->notificationService = $notificationService;
        $this->notificationService->setPresenter(new NotificationPresenter);

        $this->title = 'Notification::module.notification.title';
        $this->title_singular = 'Notification::module.notification.title_singular';

        parent::__construct();
    }

    public function index(NotificationRequest $request, NotificationDataTable $dataTable)
    {
        $notifications = $dataTable->query(new Notification());

        return $this->notificationService->index($notifications, $dataTable);
    }

    public function getUnReadNotificationsByUser(NotificationRequest $request)
    {
        $dataTable = new NotificationDataTable();
        $notifications = ($dataTable->query(new Notification()))->whereNull('read_at');

        return $this->notificationService->index($notifications, $dataTable);
    }

    public function toggleReadAt(Request $request, Notification $notification)
    {
        if (user()->cant('update', $notification)) {
            abort(403);
        }

        try {
            $notification->toggleReadAt();

            return apiResponse([], trans('Corals::messages.success.updated', ['item' => 'notification']));
        } catch (\Exception $exception) {
            return apiExceptionResponse($exception);
        }
    }

    public function markAllAsRead(Request $request)
    {
        if (user()->cant('Notification::my_notification.update')) {
            abort(403);
        }

        try {
            $notifications = user()->unreadNotifications;
            $notifications->markAsRead();

            $messageText = '';
            $successCount = count($notifications);


            if ($successCount) {
                $messageText .= trans_choice('Notification::validation.messages.notification.success_record',
                    $successCount, ['value' => $successCount, 'action' => 'Mark all as read']);
            }

            if (!$successCount) {
                $messageText .= trans('Notification::validation.messages.notification.no_record_selected');
            }

            return apiResponse([], $messageText);
        } catch (\Exception $exception) {
            return apiExceptionResponse($exception);
        }
    }
}
