<?php

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

    $user = kirby()->user();
    $project = page($data->projectUri);

    $date = new DateTime();
    $formattedDate = $date->format(DateTime::ISO8601);

    try {
      $project->update([
        "hasOptimizationRequest" => "true",
        "optimizationRequestDetails" => esc("De la part de " . $user->name() . " (" . $user->email() . ") : \n\n" . "Objet : " . $data->subject . "\n" . $data->details),
        // Métadonnées pour le système de notifications dérivées
        "optimizationAuthor" => (string) $user->uuid(),
        "optimizationAuthorName" => (string) $user->name(),
        "optimizationAuthorEmail" => (string) $user->email(),
        "optimizationDate" => $formattedDate,
        "optimizationReadby" => [],
      ]);

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

      return [
        "status" => "success",
      ];
    } catch (\Throwable $th) {
      return [
        "status" => "error",
        "message" => "Can't update project " . $project->title()->value() . ". " . $th->getMessage() . " in " . $th->getFile() . " line " . $th->getLine()
      ];
    }
  }
];
