<?php
if ( !$user || $user['client']['observer'] ) {
    http_response_code(403);
    echo json_encode('You do not have permission to like this');
    exit;
}

$commentId = $_POST['cid'];

$objectId   = $commentId;
$objectType = 'thumb';
$dt         = date('Y-m-d H:i:s');

$liked = $db->row("SELECT * FROM thumb WHERE commentId = ? AND userId = ?", $commentId, $user['id']);
if ( $liked ) {
    $db->delete('thumb', ['commentId' => $liked['commentId'], 'userId' => $user['id']]);
    $buttonIcon = '<i class="bi bi-hand-thumbs-up"></i>';

    $updateType = 'delete';
} else {
    $db->insert('thumb', ['commentId' => $commentId, 'userId' => $user['id'], 'createdAt' => $dt]);
    $buttonIcon = '<i class="bi bi-hand-thumbs-up-fill text-danger"></i>';

    $updateType = 'insert';
}

$notif = [
    'projectId'  => $db->cell("SELECT projectId FROM comment WHERE id = ?", $commentId),
    'objectId'   => $objectId,
    'objectType' => $objectType,
    'updateType' => $updateType,
    'userId'     => $user['id'],
    'createdAt'  => $dt
];
$db->insert('notification', $notif);

$count    = $db->cell("SELECT COUNT(commentId) FROM thumb WHERE commentId = ?", $commentId);
$likeText = ( $count == 1 )
    ? $count.' Like'
    : $count.' Likes'
;
$pdo      = $db->getPdo();
$stmt     = $pdo->prepare("SELECT user.name FROM thumb, user WHERE thumb.commentId = ? AND thumb.userId = user.id");
$exec     = $stmt->execute([$commentId]);
$result   = $stmt->fetchAll(\PDO::FETCH_COLUMN, 0);
$likedBy  = implode("<br>", $result);

echo json_encode(['buttonIcon' => $buttonIcon, 'likeText' => $likeText, 'likedBy' => $likedBy]);
exit;