<?php
namespace nur\sery\web;

use nur\sery\cl;
use nur\sery\file\web\Upload;

class uploads {
  private static function parse_files(array &$files, string $pkey, array $values, string $lastkey): void {
    foreach ($values as $key => $value) {
      if (is_array($value)) {
        self::parse_files($files, "$pkey.$key", $value, $lastkey);
      } else {
        cl::pset($files, "$pkey.$key.$lastkey", $value);
      }
    }
  }

  /** @var array */
  private static $_files;

  static function _files(?array $_files=null): ?array {
    if (self::$_files === null) {
      $files = [];
      if ($_files === null) $_files = $_FILES;
      foreach ($_files as $pkey => $values) {
        $name = $values["name"] ?? null;
        $type = $values["type"] ?? null;
        $error = $values["error"] ?? null;
        if (is_scalar($name) && is_scalar($type) && is_scalar($error)) {
          $files[$pkey] = $values;
        } else {
          self::parse_files($files, $pkey, $values["name"], "name");
          self::parse_files($files, $pkey, $values["type"], "type");
          self::parse_files($files, $pkey, $values["tmp_name"], "tmp_name");
          self::parse_files($files, $pkey, $values["error"], "error");
          self::parse_files($files, $pkey, $values["size"], "size");
          $full_path = $values["full_path"] ?? null;
          if ($full_path !== null) {
            self::parse_files($files, $pkey, $full_path, "full_path");
          }
        }
      }
      self::$_files = $files;
    }
    return self::$_files;
  }

  static function get(string $pkey, bool $required=true, bool $check=true): Upload {
    $_files = self::_files();
    return new Upload(cl::pget($_files, $pkey), $required, $check);
  }

  static function all(string $pkey, bool $required=true, bool $check=true) {
    $_files = self::_files();
    $uploads = [];
    foreach (cl::pget($_files, $pkey) as $file) {
      $uploads[] = new Upload($file, $required, $check);
    }
    return $uploads;
  }
}
