<?php

$blacklist = [
    '/clients/src/log-action.php',
    '/clients/ajax/fetch-notifications.php'
];

$timeOfVisit = date('Y-m-d H:i:s');

if ( !in_array($_SERVER['REQUEST_URI'], $blacklist) && !isset($_COOKIE['btbImpersonate']) ) {
    $action['userId']    = $user['id'];
    $action['tokenId']   = $auth_token['id'];
    $action['action']    = 'pageview';
    $action['target']    = $_SERVER['REQUEST_URI'];
    $action['mode']      = $_POST['mode'];
    $action['view']      = $_COOKIE['btbView'];
    $action['createdAt'] = $timeOfVisit;

    $visitedToday = $db->row("SELECT * FROM action WHERE userId = ? AND SUBSTR(createdAt, 1, 10) = ?", $user['id'], date('Y-m-d'));
    $db->insert('action', $action);

    if ( !$visitedToday && !isset($_COOKIE['btbImpersonate']) ) {
        $db->insert('notification', [
            'projectId'  => NULL,
            'objectId'   => $db->cell("SELECT id FROM action WHERE userId = ? AND tokenId = ? AND action = ? AND target = ? AND createdAt = ?", $action['userId'], $acction['tokenId'], $action['action'], $action['target'], $action['createdAt']),
            'objectType' => 'visit',
            'updateType' => 'insert',
            'userId'     => $user['id'], 
            'createdAt'  => $timeOfVisit
        ]);

        if ( $user['client'] ) {
            include 'send-visit-email.php';
        }
    }
}