<?php
// $validPredicates = ( $user['superAdmin'] )
//     ? [
//         'like'    => "(objectType = 'thumb' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
//         'comment' => "(objectType = 'comment' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
//         'reply'   => "(objectType = 'reply' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
//         'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
//         'visit'   => "(objectType = 'visit' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))"
//     ]
//     : [
//         'like'    => "(objectType = 'thumb' AND (updateType = 'insert'))",
//         'comment' => "(objectType = 'comment' AND (updateType = 'insert'))",
//         'reply'   => "(objectType = 'reply' AND (updateType = 'insert'))",
//         'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update'))"
//     ]
// ;
if ( $user['admin'] && !$user['superAdmin'] ) {
    $validPredicates = [
        'like'    => "(objectType = 'thumb' AND (updateType = 'insert'))",
        'comment' => "(objectType = 'comment' AND (updateType = 'insert'))",
        'reply'   => "(objectType = 'reply' AND (updateType = 'insert'))",
        'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update'))"
    ];
} elseif ( isset($user['client']) ) {
    if ( $user['client']['social'] ) {
        $validPredicates = [
            'like'    => "(objectType = 'thumb' AND (updateType = 'insert'))",
            'comment' => "(objectType = 'comment' AND (updateType = 'insert'))",
            'reply'   => "(objectType = 'reply' AND (updateType = 'insert'))",
            'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update'))"
        ];
    } else {
        $validPredicates = [
            'comment' => "(objectType = 'comment' AND (updateType = 'insert'))",
            'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update'))"
        ];
    }
} elseif ( $user['superAdmin'] ) {
    $validPredicates = [
        'like'    => "(objectType = 'thumb' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
        'comment' => "(objectType = 'comment' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
        'reply'   => "(objectType = 'reply' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
        'task'    => "(objectType = 'task' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))",
        'visit'   => "(objectType = 'visit' AND (updateType = 'insert' OR updateType = 'update' OR updateType = 'delete'))"
    ];
}

if ( isset($_COOKIE['btbFilters']) ) {
    parse_str($_COOKIE['btbFilters'], $filters);
}

$predicates = ( $filters )
    ? []
    : array_values($validPredicates)
;

foreach ( $filters as $key => $value ) {
    if ( $validPredicates[$key] ) {
        $predicates[] = $validPredicates[$key];
    }
}

$andWhere    = implode(' OR ', $predicates);
$andWhereAll = implode(' OR ', array_values($validPredicates));

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);

    $sql = "SELECT * FROM notification WHERE projectId IN($where) AND ($andWhere) ORDER BY createdAt DESC LIMIT 0,50";

    // $latestNotification = $db->cell("SELECT createdAt FROM notification WHERE projectId IN($where) AND ($andWhereAll) ORDER BY createdAt DESC LIMIT 0,1");
    $laterNotifications = $db->run("SELECT * FROM notification WHERE projectId IN($where) AND ($andWhereAll) AND createdAt > (SELECT latestDate FROM notification_view WHERE userId = ?) ORDER BY createdAt DESC", $user['id']);
} else {
    $sql = "SELECT * FROM notification WHERE ($andWhere) ORDER BY createdAt DESC LIMIT 0,50";

    // $latestNotification = $db->cell("SELECT createdAt FROM notification WHERE ($andWhereAll) ORDER BY createdAt DESC LIMIT 0,1");
    $laterNotifications = $db->run("SELECT * FROM notification WHERE ($andWhereAll) AND createdAt > (SELECT latestDate FROM notification_view WHERE userId = ?) ORDER BY createdAt DESC", $user['id']);
}
$notifications = $db->run($sql);

$latestDate = ( isset($laterNotifications[0]['createdAt']) )
    ? $laterNotifications[0]['createdAt']
    : '1970-01-01 00:00:00'
;

$hasNewNotifications = ( isset($hasNewNotifications) )
    ? $hasNewNotifications
    : false
;

// if user has not viewed any notifications, or if this request came from ajax/fetch-notifications.php and hasNewNotifications is true
$blink = ( !$db->cell("SELECT id FROM notification_view WHERE userId = ?", $user['id']) || $hasNewNotifications )
    ? true
    // : $db->cell("SELECT latestDate FROM notification_view WHERE userId = ? AND latestDate < ?", $user['id'], $latestNotification)
    : $db->cell("SELECT latestDate FROM notification_view WHERE userId = ? AND latestDate < ?", $user['id'], $latestDate)
;

$objectTypes = [];
if ( $blink && $filters ) {
    foreach ( $laterNotifications as $laterNotification ) {
        $objectTypes[] = $laterNotification['objectType'];
    }
}

$pageSql = "SELECT CEILING(COUNT(*) / 10) FROM comment WHERE sheetId = ? AND createdAt >= (SELECT createdAt FROM comment WHERE id = ? AND sheetId = ?) ORDER BY createdAt DESC";

$deleted = [];
// $deletedNotifications = $db->run("SELECT objectId FROM notification WHERE updateType = 'delete' AND objectType != 'thumb'");
$deletedNotifications = $db->run("SELECT id FROM notification WHERE updateType = 'delete' AND objectType != 'thumb'");
foreach ( $deletedNotifications as $deletedNotification ) {
    $deleted[] = @$deletedNotification['objectId'];
}

foreach ( $notifications as $key => $notification ) {
    $notifications[$key]['project'] = $db->row("SELECT * FROM project WHERE id = ?", $notification['projectId']);

    switch ( $notification['objectType'] ) {

        case 'comment' :
            $notifications[$key]['user']['name'] = ( $notification['userId'] )
                ? $db->cell("SELECT name FROM user WHERE id = ?", $notification['userId'])
                : $notification['createdByName']
            ;

            $notifications[$key]['page'] = $db->cell($pageSql, $notifications[$key]['project']['sheetId'], $notification['objectId'], $notifications[$key]['project']['sheetId']);
            if ( $notifications[$key]['page'] == 0 ) {
                $notifications[$key]['page'] = 1;
            }
            
            break;
        
        case 'reply' :
            $reply            = $db->row("SELECT * FROM comment WHERE id = ?", $notification['objectId']);
            $repliedToComment = $db->row("SELECT * FROM comment WHERE id = ?", $reply['parentId']);

            $notifications[$key]['user']['name'] = $db->cell("SELECT name FROM user WHERE id = ?", $reply['userId']);

            $notifications[$key]['page'] = $db->cell($pageSql, $notifications[$key]['project']['sheetId'], $repliedToComment['id'], $notifications[$key]['project']['sheetId']);
            if ( $notifications[$key]['page'] == 0 ) {
                $notifications[$key]['page'] = 1;
            }
            
            break;

        case 'task' :
            $notifications[$key]['task']             = $db->row("SELECT * FROM task WHERE id = ?", $notification['objectId']);
            // $notifications[$key]['task']['category'] = $db->cell("SELECT title FROM task WHERE rowId = ?", $notifications[$key]['task']['parentId']);
            $notifications[$key]['user']['name']     = ( $notification['userId'] )
                ? $db->cell("SELECT name FROM user WHERE id = ?", $notification['userId'])
                : $notification['createdByName']
            ;
            break;

        case 'thumb' :
            $likedComment = $db->row("SELECT * FROM comment WHERE id = ?", $notification['objectId']);

            $notifications[$key]['scrollTo']['anchor'] = $likedComment['id'];
            $notifications[$key]['scrollTo']['text']   = ( $likedComment['parentId'] )
                ? 'reply'
                : 'post'
            ;

            $notifications[$key]['user']['name'] = $db->cell("SELECT name FROM user WHERE id = ?", $notification['userId']);

            $notifications[$key]['page'] = $db->cell($pageSql, $notifications[$key]['project']['sheetId'], $likedComment['parentId'] ?? $likedComment['id'], $notifications[$key]['project']['sheetId']);
            if ( $notifications[$key]['page'] == 0 ) {
                $notifications[$key]['page'] = 1;
            }

            break;
        
        case 'visit' :
            $notifications[$key]['user'] = $db->row("SELECT * FROM user WHERE id = ?", $notification['userId']);
            // $notifications[$key]['role'] = 
            break;
    }
}

include '../template/notifications-dropdown.php';