<?php
declare(strict_types=1);

function upload_product_image(string $fieldName = 'image'): string {
    if (!isset($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
        return 'default.jpg';
    }

    $tmp = $_FILES[$fieldName]['tmp_name'];
    $info = getimagesize($tmp);

    if ($info === false) {
        throw new RuntimeException('File bukan gambar valid.');
    }

    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
    ];

    $mime = $info['mime'] ?? '';

    if (!isset($allowed[$mime])) {
        throw new RuntimeException('Format gambar harus JPG, PNG, atau WEBP.');
    }

    if ($_FILES[$fieldName]['size'] > 2 * 1024 * 1024) {
        throw new RuntimeException('Ukuran gambar maksimal 2MB.');
    }

    $dir = dirname(__DIR__, 2) . '/uploads/products';

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

    $name = bin2hex(random_bytes(20)) . '.' . $allowed[$mime];
    $dest = $dir . '/' . $name;

    if (!move_uploaded_file($tmp, $dest)) {
        throw new RuntimeException('Upload gambar gagal.');
    }

    return $name;
}

function upload_multiple_product_images(string $fieldName = 'images'): array {
    if (empty($_FILES[$fieldName]['name'][0])) {
        return [];
    }

    $uploaded = [];

    foreach ($_FILES[$fieldName]['name'] as $i => $name) {
        if ($_FILES[$fieldName]['error'][$i] !== UPLOAD_ERR_OK) {
            continue;
        }

        $_FILES['_single_image'] = [
            'name' => $_FILES[$fieldName]['name'][$i],
            'type' => $_FILES[$fieldName]['type'][$i],
            'tmp_name' => $_FILES[$fieldName]['tmp_name'][$i],
            'error' => $_FILES[$fieldName]['error'][$i],
            'size' => $_FILES[$fieldName]['size'][$i],
        ];

        $uploaded[] = upload_product_image('_single_image');
    }

    unset($_FILES['_single_image']);

    return $uploaded;
}
