<?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);

    try {
      $newProject = $project->update([
        "hasOptimizationRequest" => "true",
        "optimizationRequestDetails" => esc("De la part de " . kirby()->user()->name() . " (" . kirby()->user()->email() . ") : \n\n" . "Objet : " . $data->subject . "\n" . $data->details)
      ]);
    } catch (\Throwable $th) {
      return [
        "status" => "error",
        "message" => "Can't update project " . $project->title()->value() . ". " . $th->getMessage() . " in " . $th->getFile() . " line " . $th->getLine()
      ];
    }

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

      $notificationData = [
        "location" => [
          "page" => $newProject
        ],
        "date" => (string) $formattedDate,
        "text" => nl2br("Objet : " . $data->subject . "\n" .  esc($data->details)),
        "author" => $user,
        "id" => Str::uuid(),
        "type" => "appointment-request",
      ];

      $newProject->createNotification($notificationData);

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