<?php

if (!$kirby->user()) {
  return json_encode([
    'page' => $genericData,
    'user' => []
  ]);
}

function getProjectData($project)
{  

    $data = [
    'title'                  => $project->title()->value(),
    'url'                    => $project->url(),
    'uri'                    => '/' . $project->uri(),
    'modified'               => $project->modified('Y-MM-d'),
    'currentStep'            => $project->currentStep()->value(),
    'status'                 => $project->status(),
    'logo'                   => $project->client()->toPage() ? $project->client()->toPage()->logo()->toFile()->url() : '',
    'steps'                  => $project->getSteps(),
    'notifications'          => Yaml::decode($project->notifications()->value),
    'uuid'                   => (string) $project->uuid(),
    'slug'                   => (string) $project->slug(),
    'isDTLEnabled'           => $project->isDTLEnabled()->isTrue(),
    'hasOptimizationRequest' => $project->hasOptimizationRequest()->isTrue(),
  ];

    if ($project->isDTLEnabled()) {
        $data['designToLight'] = processDTLProposals($project);
    }

    return $data;
}

try {
    $children = $kirby->user()->role() == 'admin' ? $page->childrenAndDrafts()->map(fn($project) => getProjectData($project))->values() : $kirby->user()->projects()->toPages()->map(fn($project) => getProjectData($project))->values();
} catch (\Throwable $th) {
    throw new Exception($th->getMessage() . ' line ' . $th->getLine() . ' in file ' . $th->getFile(), 1);
    $children = [];
}

$specificData = [
  'children' => $children,
];

$pageData = array_merge($genericData, $specificData);

echo json_encode([
  'page' => $pageData,
  'user' => $userData,
]);
