<?php

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

    $page = page($data->briefUri);
    $project = $page->parent();
    
    try {
      $newPage = $page->update([
        'isValidated' => 'true'
      ]);

      $timezone = new DateTimeZone('Europe/Paris');
      $dateTime = new DateTime('now', $timezone);

      $notification = [
        'location' => [
          'page' => $page,
        ],
        'date' => $dateTime->format('Y-m-d\TH:i:sP'),
        'text' => "Nouveau brief", 
        'author' => kirby()->user(),
        'id' => Str::uuid(),
        'type' => 'content'
      ];

      $project->createNotification($notification);

      return [
        "success" => "'" . $project->title()->value() . "' brief validated."
      ];
    } catch (\Throwable $th) {
      return [
        "error" => "Can't validate '" . $page->title()->value() . "' brief.",
        'details' => $th->getMessage()
      ];
    }
  }
];
