public function acceptAction($id = 0)
{
$response = new Response();
/**
* Find the post using get
*/
$postReply = PostsReplies::findFirstById($id);
if (!$postReply) {
$contentNotExist = ['status' => 'error', 'message' => 'Post reply does not exist'];
return $response->setJsonContent($contentNotExist);
}
if (!$this->checkTokenGetJson('post-' . $postReply->post->id)) {
$csrfTokenError = ['status' => 'error', 'message' => 'This post is outdated. Please try to accept reply again.'];
return $response->setJsonContent($csrfTokenError);
}
$user = Users::findFirstById($this->session->get('identity'));
if (!$user) {
$contentLogIn = ['status' => 'error', 'message' => 'You must log in first to vote'];
return $response->setJsonContent($contentLogIn);
}
if ($postReply->accepted == 'Y') {
$contentAlready = ['status' => 'error', 'message' => 'This reply is already accepted as answer'];
return $response->setJsonContent($contentAlready);
}
if ($postReply->post->deleted) {
$contentDeleted = ['status' => 'error', 'message' => 'Post associated to the reply is deleted'];
return $response->setJsonContent($contentDeleted);
}
if ($postReply->post->accepted_answer == 'Y') {
$contentAlreadyAnswer = ['status' => 'error', 'message' => 'This post already has an accepted answer'];
return $response->setJsonContent($contentAlreadyAnswer);
}
if ($postReply->post->users_id != $user->id && $user->moderator != 'Y') {
$contentCorrect = ['status' => 'error', 'message' => "You can't accept this answer as correct"];
return $response->setJsonContent($contentCorrect);
}
if ($postReply->post->users_id != $postReply->users_id) {
$postReply->post->user->karma += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY;
$postReply->post->user->votes_points += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY;
$points = 30 + intval(abs($user->karma - $postReply->user->karma) / 1000);
$parametersBounty = ['users_id = ?0 AND posts_replies_id = ?1', 'bind' => [$postReply->users_id, $postReply->id]];
$postBounty = PostsBounties::findFirst($parametersBounty);
if ($postBounty) {
$points += $postBounty->points;
}
$postReply->user->karma += $points;
$postReply->user->votes_points += $points;
if ($postReply->users_id != $user->id && $postReply->post->users_id != $user->id) {
$user->karma += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY;
$user->votes_points += Karma::SOMEONE_ELSE_ACCEPT_YOUR_REPLY;
}
}
$postReply->accepted = 'Y';
$postReply->post->accepted_answer = 'Y';
if ($postReply->save()) {
if (!$user->save()) {
foreach ($user->getMessages() as $message) {
$contentError = ['status' => 'error', 'message' => $message->getMessage()];
return $response->setJsonContent($contentError);
}
}
}
if ($user->id != $postReply->users_id) {
$activity = new ActivityNotifications(['users_id' => $postReply->users_id, 'posts_id' => $postReply->post->id, 'posts_replies_id' => $postReply->id, 'users_origin_id' => $user->id, 'type' => 'A']);
$activity->save();
}
return $response->setJsonContent(['status' => 'OK']);
}