<?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();
    $user = kirby()->user();

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

      $updateData = [
        'isValidated' => 'true',
        // Métadonnées pour le système de notifications dérivées
        'validatedBy' => (string) $user->uuid(),
        'validatedByName' => (string) $user->name(),
        'validatedByEmail' => (string) $user->email(),
        'validatedAt' => $dateTime->format('Y-m-d\TH:i:sP'),
        'validationReadby' => [],
      ];

      // Si un dialogUri est fourni (validation depuis PDF), le stocker
      if (isset($data->dialogUri) && !empty($data->dialogUri)) {
        $updateData['validationDialogUri'] = (string) $data->dialogUri;
      }

      $newPage = $page->update($updateData);

      // Note: Les notifications sont maintenant dérivées.
      // Plus besoin d'appeler createNotification().

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