<?php

return [
  'pattern' => 'upload-images.json',
  'method' => 'POST',
  'action' => function () {
    if ($uploads = kirby()->request()->files()) {  
      $pageUri = kirby()->request()->query()->get('pageUri');
      $page = page($pageUri);
      
      $alerts  = [];
      $success = '';
      $newFiles = [];
      $allFiles = [];

      foreach ($uploads->get('images') as $upload) {
        // check for duplicate
        $files      = $page->files();
        $duplicates = $files->filter(function ($file) use ($upload) {
          $pos              = strpos($file->filename(), '_');
          $originalSafename = substr($file->filename(), $pos + 1);

          return $originalSafename === F::safeName($upload['name']) &&
                  $file->mime() === $upload['type'] &&
                  $file->size() === $upload['size'];
        });

        if ($duplicates->count() > 0) {
          $alerts[$upload['name']] = "The file already exists";
        }
        
        try {
          $name = crc32($upload['name'].microtime()). '_' . $upload['name'];
          $newFile = $page->createFile([
            'source'   => $upload['tmp_name'],
            'filename' => $name,
            'template' => 'default',
            'content' => [
                'date' => date('Y-m-d h:m')
            ]
          ]);

          $newFiles[] = $newFile;
          
          $success = 'Your file upload was successful';

          $allFiles[] = (string) $newFile->uuid();
        } catch (Exception $e) {
          $alerts[$upload['name']] = $e->getMessage();
        }
      }
      
      $images = array_map(function ($file) {
        return [
          'url' => $file->url(),
          'uuid' => $file->uuid()
        ];
      }, $newFiles);
      
      $newPage = $page->update([
        'clientBriefImages' => $allFiles
      ]);

      return compact('images', 'alerts', 'success');
    }

    return [
      'error' => 'Aucun fichier reçu.',
    ];
  }
];
