<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;
use Dashboard\Services\AvatarService;
use PDO;

class NotificationController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_NOTIFICATIONS');
    }

    public function index()
    {
        $notifications = db()->prepare("SELECT N.*, A.username, A.realname FROM Notifications N INNER JOIN Accounts A ON N.accountID = A.id WHERE N.type IN (?, ?, ?, ?) ORDER BY N.id DESC LIMIT 100");
        $notifications->execute(array(1, 2, 3, 4));

        if (auth()->user()->data('lastReadDate')) {
            $updateAccountNoticationInfo = db()->prepare("UPDATE AccountNoticationInfo SET lastReadDate = ? WHERE accountID = ?");
            $updateAccountNoticationInfo->execute(array(datetime(), auth()->user()->id()));
        }
        else {
            $insertAccountNoticationInfo = db()->prepare("INSERT INTO AccountNoticationInfo (accountID, lastReadDate) VALUES (?, ?)");
            $insertAccountNoticationInfo->execute(array(auth()->user()->id(), datetime()));
        }

        $notifications = array_map(function($notification) {
						$notification['avatar'] = AvatarService::get($notification['accountID'], $notification['realname']);
						
						return $notification;
				}, $notifications->fetchAll(PDO::FETCH_ASSOC));

        return view('notifications.index', compact('notifications'));
    }
}