<?php

return [
  'pattern' => 'upload-pdf.json',
  'method' => 'POST',
  'action' => function () {    
    $kirby = kirby();
    $request = $kirby->request();

    $files = $request->files();
    $data = $request->data();

    $upload = $files->get('file') ?? null;

    $pageUri = $request->query()->get('pageUri');
    $page = page($pageUri);

    if (!$page) {
      return [
        'error' => 'Invalid page.',
      ];
    }

    try {
      $name = crc32($upload['name'] . microtime()) . '_' . $upload['name'];
      
      $existingFileId = $page->pdf()->id() ?? null;

      if ($existingFileId) {
        $existingFile = $kirby->file($existingFileId);
        if ($existingFile) {
          $existingFile->delete();
        }
      }

      $newFile = $page->createFile([
        'source'   => $upload['tmp_name'],
        'filename' => $name,
        'template' => 'pdf',
        'content'  => [
            'date' => date('Y-m-d h:i')
        ]
      ]);      

      $newPage = $page->update([
        "pdf" => $newFile->id()
      ]);

      return getFileData($newFile);

    } catch (Exception $e) {
      return [
        'error' => $e->getMessage() . " in " . $e->getFile() . " line " . $e->getLine(),
      ];
    }
  }
];
