<?php

return [
  'pattern' => '(:all)update-comment.json',
  'method' => 'POST',
  'action'  => function () {
    $json = file_get_contents('php://input');
    $data = json_decode($json);

    $page = page($data->location->page->uri);
    $file = $page->file($data->location->file->uuid);
    $isReply = $data->location->parent->id ?? false;

    $comments = $file->comments()->isEmpty() == true ? [] : Yaml::decode($file->comments()->value());

    foreach ($comments as $key => &$comment) {
      if ($isReply) {
        if ($comment['id'] === $data->location->parent->id) {
          foreach ($comment['replies'] as $replyKey => $reply) {
            if ($reply['id'] === $data->id) {
              $comment['replies'][$replyKey]["text"] = $data->text;
              $comment['replies'][$replyKey]["date"] = $data->date;
              $comment['replies'] = array_values($comment['replies']);
            }
          }
        }
      } else {
        if ($comment['id'] === $data->id) {
          $comments[$key]["text"] = $data->text;
          $comments[$key]["date"] = $data->date;
        }
      }
    }

    $comments = array_values($comments);

    $newFile = $file->update([
      'comments' => $comments
    ]);
    
    echo json_encode(getFileData($newFile));
    exit;
  }
];