<?php

namespace App\Http\Controllers\Dashboard;

use Carbon\Carbon;
use App\Http\Controllers\Controller;

class NotificationsController extends Controller
{
    public $notifications;
    private $notificationsLimit = 10;

    public function __construct() {
        $this->middleware("auth");
        $this->notifications = null;
    }

    public function notifications() {
        return view("dashboard.notifications.index")->with([
            "notifications" => $this->decode(auth()->user()->notifications, true)
        ]);
    }

    public function getNotifications() {
        return auth()->user()->readNotifications;
    }

    public function getUnreadNotifications() {
        return auth()->user()->unreadNotifications;
    }

    public function markNotificationsAsRead() {
        return auth()->user()->unreadNotifications->markAsRead();
    }

    public function showNotifications() {

        $this->notifications = collect();

        if($this->getUnreadNotifications()->count() == 0) {
            $this->notifications->push($this->getNotifications()->take($this->notificationsLimit));
            $this->notifications = $this->notifications->flatten();
            return response()->json($this->decode($this->notifications->reverse()));
        }

        if($this->getUnreadNotifications()->count() > 10) {
            $this->notifications->push($this->getUnreadNotifications()->take($this->notificationsLimit));
        } else {
            $readNotifications = $this->notificationsLimit - $this->getUnreadNotifications()->count();
            $this->notifications->push($this->getUnreadNotifications());
            $this->notifications->push($this->getNotifications()->take($readNotifications));
        }

        $this->notifications = $this->notifications->flatten();

        return response()->json($this->decode($this->notifications->reverse()));
    }

    public function decode($notifications, $isShowOnly = false) {

        $response = array();
        $decoded = json_decode($notifications);

        foreach($decoded as $notification) {
            $isRead = empty($notification->read_at) ? false : true;
            array_push($response, [
                "isRead" => $isRead,
                // "from" => $notification->data->from,
                "url" => $notification->data->url,
                "message" => $notification->data->message,
                "ago" => Carbon::parse($notification->created_at)->diffForHumans(),
            ]);
        }

        if(!$isShowOnly) {
            $this->markNotificationsAsRead();
        }

        return $response;
    }
}
