<?php
function handle_upload(array $file, array $allowedTypes, int $maxBytes, string $targetDir): array
{
    if (!isset($file['error']) || $file['error'] !== UPLOAD_ERR_OK) {
        return ['ok' => false, 'error' => 'File gagal diupload.'];
    }

    if ($file['size'] > $maxBytes) {
        return ['ok' => false, 'error' => 'Ukuran file terlalu besar.'];
    }

    $mime = mime_content_type($file['tmp_name']);
    if (!in_array($mime, $allowedTypes, true)) {
        return ['ok' => false, 'error' => 'Tipe file tidak didukung.'];
    }

    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0755, true);
    }

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $safeName = bin2hex(random_bytes(8)) . '.' . strtolower($ext);
    $destination = rtrim($targetDir, '/\\') . DIRECTORY_SEPARATOR . $safeName;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        return ['ok' => false, 'error' => 'Gagal menyimpan file.'];
    }

    return ['ok' => true, 'filename' => $safeName];
}
