<?php

return function ($page, $kirby, $site) {
  if (!$kirby->user() && $page->uri() !== 'login') {
    go('/login');
  }

  $data = $page->toArray();
  $data['template'] = (string) $page->template();
  $data['newInspirations'] = (bool) page('inspirations')->children()->findBy('new', 'true');

  if ($kirby->user()) {
    $userData = [
      "name" => (string) $kirby->user()->name()->or(null),
      "email" => (string) $kirby->user()->email(),
      "role" => (string) $kirby->user()->role(),
      "uuid" => (string) $kirby->user()->uuid()
    ];
  
    if ($kirby->user()->client()->exists() && $kirby->user()->client()->isNotEmpty()) {
      $userData['client'] = [
        "name" => (string) $kirby->user()->client()->toPage()->title(),
        "uuid" => (string) $kirby->user()->client()->toPage()->uuid()
      ];
      if ($kirby->user()->client()->toPage()->logo()->isNotEmpty()) {
        $userData['client']["logo"] = $kirby->user()->client()->toPage()->logo()->toFile()->url();
      }
    }

    if ($kirby->user()->projects()->exists() && $kirby->user()->projects()->isNotEmpty()) {
      $userData['projects'] = $kirby->user()->projects()->toPages()->map(function ($project) {
        return [
          "title" => (string) $project->title(),
          "uri" => (string) $project->uri(),
          "step" => (string) $project->getStepLabel(),
        ];
      })->data;
    }
  }


  return [
    'genericData' => $data,
    'userData' => $userData ?? null
  ];
};