<?php

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

    $user = kirby()->user();    

    $client = kirby()->user()->client()->toPage()->uuid();

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

    $projectData = [
      "slug" => esc(Str::slug($data->title)),
      "template" => "project",
      "content" => [
        "title" => esc($data->title),
        "requestDetails" => esc("Demande de " . $user->name() . " (" . $user->email() . ") : \n\n" . $data->details),
        "client" => [$client],
        "isClientRequest" => "true",
        "isDTLEnabled" => esc($data->isDTLEnabled),
        // Métadonnées pour le système de notifications dérivées
        "requestAuthor" => (string) $user->uuid(),
        "requestAuthorName" => (string) $user->name(),
        "requestAuthorEmail" => (string) $user->email(),
        "requestDate" => $formattedDate,
        "requestReadby" => [],
      ]
    ];

    $projects = page("projects");
    try {
      $newProject = $projects->createChild($projectData);

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

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