<?php
/**
 * Ragreen - Image Upload Helper
 * Validates and saves an uploaded image file, returning its public path.
 */

require_once __DIR__ . '/../config/config.php';

const ALLOWED_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp'];
const ALLOWED_EXTENSIONS  = ['jpg', 'jpeg', 'png', 'webp'];

/**
 * @param array $file One entry from $_FILES (already isset-checked)
 * @return array{ok: bool, path?: string, error?: string} path is relative, e.g. "products/xyz.jpg"
 */
function save_uploaded_image(array $file, string $subfolder = 'products'): array
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['ok' => false, 'error' => 'Upload failed (error code ' . $file['error'] . ').'];
    }

    if ($file['size'] > MAX_UPLOAD_SIZE) {
        return ['ok' => false, 'error' => 'Image exceeds the 5MB limit.'];
    }

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime, ALLOWED_IMAGE_TYPES, true)) {
        return ['ok' => false, 'error' => 'Only JPG, PNG, or WEBP images are allowed.'];
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, ALLOWED_EXTENSIONS, true)) {
        $ext = str_replace('image/', '', $mime); // fallback
    }

    $targetDir = rtrim(UPLOAD_DIR, '/') . '/' . $subfolder;
    if (!is_dir($targetDir)) {
        mkdir($targetDir, 0775, true);
    }

    $filename = bin2hex(random_bytes(16)) . '.' . $ext;
    $destination = $targetDir . '/' . $filename;

    if (!move_uploaded_file($file['tmp_name'], $destination)) {
        return ['ok' => false, 'error' => 'Could not save the uploaded image.'];
    }

    return ['ok' => true, 'path' => $subfolder . '/' . $filename];
}
