<?php
declare(strict_types=1);
function storeUpload(array $file,string $privateDir): string {
    $allowed=['image/jpeg'=>'jpg','image/png'=>'png','application/pdf'=>'pdf'];
    if (($file['error']??UPLOAD_ERR_NO_FILE)!==UPLOAD_ERR_OK || ($file['size']??0)<1 || $file['size']>5*1024*1024) {
        throw new RuntimeException('Upload error or size limit exceeded.');
    }
    $tmp=(string)$file['tmp_name'];
    if (!is_uploaded_file($tmp)) throw new RuntimeException('Invalid upload source.');
    $mime=(new finfo(FILEINFO_MIME_TYPE))->file($tmp);
    if (!isset($allowed[$mime])) throw new RuntimeException('File type not allowed.');
    if (!is_dir($privateDir) && !mkdir($privateDir,0700,true)) throw new RuntimeException('Storage unavailable.');
    $name=bin2hex(random_bytes(16)).'.'.$allowed[$mime];
    if (!move_uploaded_file($tmp,rtrim($privateDir,'/').'/'.$name)) throw new RuntimeException('Cannot store file.');
    return $name;
}
