<?php
if (!function_exists('save_upload')) {
    function save_upload(string $fieldName, string $subDir = 'attachments'): ?string {
        if (empty($_FILES[$fieldName]['tmp_name'])) return null;
        $file = $_FILES[$fieldName];
        if ($file['error'] !== UPLOAD_ERR_OK) return null;

        $allowed = ['image/jpeg','image/png','image/gif','application/pdf'];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mime = $finfo->file($file['tmp_name']);
        if (!in_array($mime, $allowed)) return null;
        if ($file['size'] > 5 * 1024 * 1024) return null;

        $ext = ['image/jpeg'=>'jpg','image/png'=>'png','image/gif'=>'gif','application/pdf'=>'pdf'][$mime];
        $dir = __DIR__ . '/../uploads/' . $subDir . '/';
        if (!is_dir($dir)) mkdir($dir, 0755, true);

        $fname = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        if (move_uploaded_file($file['tmp_name'], $dir . $fname)) {
            return 'uploads/' . $subDir . '/' . $fname;
        }
        return null;
    }
}
