<?php

return [
  'pattern' => 'upload-images.json',
  'method' => 'POST',
  'action' => function () {
    
    $kirby = kirby();
    $request = $kirby->request();
    
    $files = $request->files();
    $data = $request->data();
    
    $pageUri = $request->query()->get('pageUri');
    if (!$pageUri) {
      return [
        'error' => 'Page non trouvée.'
      ];
    }


    $page = page($pageUri);
    $allFiles = $page->moodboard()->isNotEmpty() ? $page->moodboard()->toFiles()->pluck('uuid', ',') : [];
    $alerts  = [];
    $success = [];

    // Copy images selected from site banks with incoming properties
    if (!empty($data['imageUris'])) {      
      foreach ($data['imageUris'] as $imageUri) {
        $imageData = json_decode($imageUri, true);

        $existingFile = $page->file($imageData['name']);
        $source = null;

        if (!$existingFile) {
          try {
            $source = page('materials')->file($imageData['uuid'])->copy($page);
          } catch (\Throwable $th) {
            $alerts[$source->name()] = $th->getMessage();
          }
        } else {
          $allFiles = array_filter($allFiles, function ($uuid) use ($existingFile) {
            return $uuid != $existingFile->uuid();
          });
          $source = $existingFile;
        }

        try {
          $updatedFile = $source->update([
            'description' => $imageData['description'],
            'tags' => $imageData['tags'],
          ]);
          $allFiles[] = $updatedFile->uuid();
        } catch (\Throwable $th) {
          $alert[$source->name()] = $th->getMessage();
        }
      }
    }

    // Upload new images
    if ($uploads = $files->get('images')) {
      $imagesMeta = $data['imagesMeta'];
      $existingFiles = $page->files();
      $existingFileMap = [];
      foreach ($existingFiles as $file) {
        $pos              = strpos($file->filename(), '_');
        $originalSafename = substr($file->filename(), $pos + 1);
        $existingFileMap[$originalSafename . '|' . $file->mime() . '|' . $file->size()] = $file->uuid();
      }

      foreach ($uploads as $index => $upload) {
        $description = $imagesMeta[$index]['description'] ?? null;
        $tags = json_decode($imagesMeta[$index]['tags'], true) ?? [];

        // check for duplicate
        $files      = $page->files();
        $duplicates = $files->filter(function ($file) use ($upload) {
          // get original safename without prefix
          $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) {
          $existingFile = $duplicates->first();
          $newFile = $existingFile->update([
            'description' => $description,
            'tags' => $tags
          ]);

          $allFiles = array_filter($allFiles, function ($uuid) use ($existingFile) {
            return $uuid != $existingFile->uuid();
          });

          $allFiles[] = $newFile->uuid();
          $success[$newFile->name()] = 'Successfully updated.';
          continue;
        } else {          
          try {
            
            $name = crc32($upload['name'].microtime()). '_' . $upload['name'];
            $newFile = $page->createFile([
              'source'   => $upload['tmp_name'],
              'filename' => $name,
              'template' => 'image',
              'content' => [
                  'date' => date('Y-m-d h:m'),
                  'description' => $description,
                  'tags' => $tags,
              ]
            ]);
            $allFiles[] = $newFile->uuid();
            $success[$newFile->name()] = 'Successfully added.';
          } catch (Throwable $th) {
            $alerts[$upload['name']] = $th->getMessage() . ' line ' . $th->getLine();
          }
        }
      }
    }
    
    // Empty page update needed to updates its files data
    $newPage = $page->update([]);
    if (!empty($allFiles)) {
      $newPage = $page->update([
        'moodboard' => $allFiles
      ]);
    }
    

    $images = [];
    foreach ($newPage->moodboard()->toFiles() as $image) {
      $images[] = [
        'url' => $image->url(),
        'uuid' => (string) $image->uuid(),
        'tags' => $image->tags()->split(),
        'name' => $image->filename(),
        'description' => $image->description()->value(),
      ];
    }
    return compact('images', 'alerts', 'success');
  }
];
