<?php

if ( !$user ) {
    http_response_code(403);
    exit;
}

if ( !isset($_POST['latestDate']) ) {
    http_response_code(400);
    exit;
}

$latestDate = ( $d = $db->cell("SELECT latestDate FROM notification_view WHERE userId = ? AND latestDate > ?", $user['id'], $_POST['latestDate']) )
    ? $d
    : $_POST['latestDate']
;

if ( isset($user['client']) ) {
    $projects = $db->run("SELECT projectId FROM client_project WHERE clientId = ?", $user['client']['id']);

    $array = [];
    foreach ( $projects as $project ) {
        $array[] = $project['projectId'];
    }
    $where = implode(',', $array);

    $hasNewNotifications = ( $user['client']['social'] )
        //social enabled
        ? $db->cell("SELECT id FROM notification WHERE createdAt > ? AND projectId IN($where) AND ((objectType = 'task' AND (updateType = 'insert' OR updateType = 'update')) OR (objectType = 'comment' AND updateType = 'insert') OR (objectType = 'thumb' AND updateType = 'insert') OR (objectType = 'reply' AND updateType = 'insert')) ORDER BY createdAt DESC LIMIT 0,50", $latestDate)
        //social not enabled
        : $db->cell("SELECT id FROM notification WHERE createdAt > ? AND projectId IN($where) AND ((objectType = 'task' AND (updateType = 'insert' OR updateType = 'update')) OR (objectType = 'comment' AND updateType = 'insert')) ORDER BY createdAt DESC LIMIT 0,50", $latestDate)
    ;
} else if ( !isset($user['client']) && !$user['superAdmin'] && $user['admin'] ) {
    $hasNewNotifications = $db->cell("SELECT id FROM notification WHERE createdAt > ? AND ((objectType = 'task' AND (updateType = 'insert' OR updateType = 'update')) OR (objectType = 'comment' AND updateType = 'insert') OR (objectType = 'thumb' AND updateType = 'insert') OR (objectType = 'reply' AND updateType = 'insert')) ORDER BY createdAt DESC LIMIT 0,50", $latestDate);
} else {
    //super admins see all notifications
    $hasNewNotifications = $db->cell("SELECT id FROM notification WHERE createdAt > ? ORDER BY createdAt DESC LIMIT 0,50", $latestDate);
}

if ( !$hasNewNotifications ) {
    http_response_code(200);
    exit;
}

include '../src/load-notifications.php';