<?php

function provider_upload_image(string $fieldName = 'provider_image'): array
{
    if (!isset($_FILES[$fieldName]) || !is_array($_FILES[$fieldName])) {
        return ['ok' => true, 'path' => ''];
    }

    $file = $_FILES[$fieldName];
    $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);

    if ($error === UPLOAD_ERR_NO_FILE) {
        return ['ok' => true, 'path' => ''];
    }

    if ($error !== UPLOAD_ERR_OK) {
        return ['ok' => false];
    }

    $tmpName = (string)($file['tmp_name'] ?? '');
    $size = (int)($file['size'] ?? 0);
    $originalName = (string)($file['name'] ?? '');
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp'];

    if ($tmpName === '' || $size <= 0 || $size > 2 * 1024 * 1024 || !in_array($extension, $allowedExtensions, true)) {
        return ['ok' => false];
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmpName);
    $allowedMimes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];

    if (!in_array($mime, $allowedMimes, true)) {
        return ['ok' => false];
    }

    $uploadDir = __DIR__ . '/../assets/images/uploads/providers';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        return ['ok' => false];
    }

    $fileName = 'provider-' . bin2hex(random_bytes(8)) . '.' . $extension;
    $targetPath = $uploadDir . '/' . $fileName;

    if (!move_uploaded_file($tmpName, $targetPath)) {
        return ['ok' => false];
    }

    return ['ok' => true, 'path' => 'assets/images/uploads/providers/' . $fileName];
}
