<?php

use Kirby\Uuid\Uuid;

return function ($page, $site, $kirby) {
  $error = "";
  $json = [];
  $type = "html";
  if ($kirby->request()->is('POST')) {
    $action = $kirby->request()->get("action");
    if ($action == "createGame") {
      // $name = $kirby->request()->get("name");
      $name = Uuid::generate($length = 8);
      $tournament = $kirby->request()->get("tournament");
      $content = [
        'title' => $name
      ];
      try {

        $kirby->impersonate('kirby');
        $id = $site->find($tournament)->createChild([
          'content'  => $content,
          'slug'     => Str::slug($name),
          'template' => 'xoi',
          'isDraft' => false
        ]);
        $json["status"] = "ok";
        $json["url"] = $id->url();
      } catch (\Exception $e) {
        $error = $e->getMessage();
      }
    }
    $data = $kirby->request()->get("name");
  }
  return [
    'type' => $type,
    'json' => $json,
    'error' => $error
  ];
};