<?php

class upload
{
    private const MAX_FILE_SIZE = 10_000_000;

    public static function img(array $file): array
    {
        return self::store($file, __DIR__ . '/../admin/employeepics', [
            'image/jpeg' => 'jpg',
            'image/png' => 'png',
            'image/gif' => 'gif',
            'image/webp' => 'webp',
        ], true);
    }

    public static function PDF(array $file): array
    {
        return self::store($file, __DIR__ . '/../admin/product_wording', [
            'application/pdf' => 'pdf',
        ], false);
    }

    private static function store(array $file, string $destination, array $allowedMimeTypes, bool $requireValidImage): array
    {
        if (($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            return ['Upload failed. Please select a valid file.'];
        }

        $size = (int) ($file['size'] ?? 0);
        if ($size < 1 || $size > self::MAX_FILE_SIZE) {
            return ['Your uploaded file must be smaller than 10 MB.'];
        }

        $temporaryPath = (string) ($file['tmp_name'] ?? '');
        if (!is_uploaded_file($temporaryPath)) {
            return ['The uploaded file could not be verified.'];
        }

        $fileInfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $fileInfo->file($temporaryPath);
        if (!is_string($mimeType) || !isset($allowedMimeTypes[$mimeType])) {
            return ['The uploaded file type is not allowed.'];
        }

        if ($requireValidImage && @getimagesize($temporaryPath) === false) {
            return ['The uploaded image is invalid.'];
        }

        if (!is_dir($destination) || !is_writable($destination)) {
            return ['Upload folder is not writable. Contact the site administrator.'];
        }

        $filename = bin2hex(random_bytes(16)) . '.' . $allowedMimeTypes[$mimeType];
        if (!move_uploaded_file($temporaryPath, $destination . DIRECTORY_SEPARATOR . $filename)) {
            return ['Failed to upload file. Contact the site administrator.'];
        }

        return ['Upload Successfully!', $filename];
    }
}
