<?php

$projectId = $_POST['projectId'];

if ( !$user['admin'] && !$user['superAdmin'] ) {
    if ( !$user['client']['observer'] ) {
        if ( !$exists = $db->cell("SELECT id FROM client_project WHERE clientId = ? AND projectId = ?", $user['client']['id'], $projectId) ) {
            http_response_code(403);
            echo json_encode('You do not have permission to reply to this post');
            exit;
        }
    } else {
        http_response_code(403);
        echo json_encode('You do not have permission to reply to this post');
        exit;
    }
}

$commentId = $_POST['commentId'];
$text      = $_POST['text'];
$createdAt = date('Y-m-d H:i:s');

$db->insert('comment', [
    'parentId'  => $commentId,
    'projectId' => $projectId,
    'text'      => $text,
    'userId'    => $user['id'],
    'createdAt' => $createdAt
]);

$reply               = $db->row("SELECT * FROM comment WHERE parentId = ? AND projectId = ? AND text = ? AND userId = ?", $commentId, $projectId, $text, $user['id']);
$pdo                 = $db->getPdo();
$stmt                = $pdo->prepare("SELECT user.name FROM thumb, user WHERE thumb.commentId = ? AND user.id = thumb.userId");
$exec                = $stmt->execute([$reply['id']]);
$reply['likes']      = $stmt->fetchAll(\PDO::FETCH_COLUMN, 0);
$reply['likeString'] = implode("<br>", $reply['likes']);
$reply['name']       = $db->cell("SELECT name FROM user WHERE id = ?", $user['id']);
$reply['clientId']   = $user['client']['id'];
$replyLikeText       = "0 Likes";

$count               = $db->cell("SELECT COUNT(id) FROM comment WHERE parentId = ?", $commentId);
$userLikes           = []; //prevent error in template

$notif = [
    'projectId'  => $projectId,
    'objectId'   => $reply['id'],
    'objectType' => 'reply',
    'updateType' => 'insert',
    'userId'     => $user['id'],
    'createdAt'  => $createdAt
];
$db->insert('notification', $notif);

ob_start();
include '../template/comment-reply.php';
$commentHtml  = ob_get_clean();
ob_start();
?>
    <a id="btb-post-comment-count-<?php echo $commentId; ?>" class="text-danger" onclick="document.getElementById('textarea-<?php echo $comment['id']; ?>').scrollIntoView();" role="button">
        <?php echo ( $count > 0 ) ? $count : 0; ?> Comments
    </a>
<?php
$countHtml = ob_get_clean();

ob_start();
?>
    <a id="btb-reply-collapse-toggle-<?php echo $commentId; ?>" class="text-danger test" data-bs-toggle="collapse" href="#btb-reply-collapse-<?php echo $commentId; ?>" role="button" onclick="this.textContent = ( this.textContent == 'Show fewer' ) ? 'Show more' : 'Show fewer';">Show fewer</a>
<?php
$toggleHtml = ob_get_clean();

include '../src/send-reply-notification.php';

echo json_encode(['replyId' => $reply['id'], 'commentHtml' => $commentHtml, 'countHtml' => $countHtml, 'toggleHtml' => $toggleHtml]);