<?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'))"
    ];
}

$filters = ( isset($_POST['filters']) )
    ? $_POST['filters']
    : false
;
// $log = "post: ".print_r($_POST['filters'], true)."\n";
// $log .= "filters: ".print_r($filters, true)."\n";

$predicates = ( $filters )
    ? []
    : array_values($validPredicates)
;
// $log .= "predicates: ".print_r($predicates, true)."\n";

$cookie = [];
foreach ( $filters as $filter ) {
    // $log .= "filter: $filter\n";
    if ( $validPredicates[$filter] ) {
        $predicates[] = $validPredicates[$filter];
        $cookie[]     = "$filter=1";
    }
}
// $log .= "predicates post-loop: ".print_r($predicates, true)."\n";
// $log .= "cookie post-loop: ".print_r($cookie, true)."\n";

$andWhere    = implode(' OR ', $predicates);
$andWhereAll = implode(' OR ', array_values($validPredicates));
$setCookie   = implode('&', $cookie);
// $log .= "andwhere: $andWhere\n";
// $log .= "setCookie: $setCookie\n";

if ( $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";
} else {
    $sql = "SELECT * FROM notification WHERE ($andWhere) ORDER BY createdAt DESC LIMIT 0,50";
}

// $log  .= "sql: $sql\n\n";
// $file = fopen(PATH_LOGS.'/btb.filter-notifications.log', "a");
// fwrite($file, $log);
// fclose($file);

$notifications = $db->run($sql);

$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]['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']);
            break;
    }
}

setcookie('btbFilters', $setCookie, time() + (60*60*24*30*12), '/clients', URL_COOKIES);

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