<?php
declare(strict_types=1);

function upload_image(string $field, string $destDirAbs, ?string $current = null): ?string {
  if (empty($_FILES[$field]['name'])) return $current;

  if (!is_dir($destDirAbs)) @mkdir($destDirAbs, 0755, true);

  $allowed = ['jpg','jpeg','png','webp'];
  $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
  if (!in_array($ext, $allowed, true)) return $current;

  $name = time() . '_' . bin2hex(random_bytes(6)) . '.' . $ext;
  $tmp  = $_FILES[$field]['tmp_name'];

  if (!is_uploaded_file($tmp)) return $current;
  if (!move_uploaded_file($tmp, rtrim($destDirAbs,'/').'/'.$name)) return $current;

  return $name;
}