<?php
function handleUpload($file, $targetDir = '../assets/uploads/')
{
    // Check if file was uploaded without errors
    if (!isset($file) || $file['error'] !== UPLOAD_ERR_OK) {
        return null; // No file uploaded or error
    }

    // Ensure target directory exists
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    // Validate file type
    $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mimeType, $allowedTypes)) {
        return ['error' => 'Invalid file type. Only JPG, PNG, GIF, and WebP are allowed.'];
    }

    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('img_', true) . '.' . $extension;
    $targetPath = $targetDir . $filename;

    // Move file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Return public path (relative to admin folder naturally, but we want absolute or relative to root)
        // Since admin is at /admin, and assets is at /assets, the path from root is assets/uploads/...
        // But from admin script context, it's ../assets/uploads/...
        // Let's return the path suitable for DB storage (relative to site root usually best, or absolute URL)
        // We'll return 'assets/uploads/filename' so it works from root index.php
        // adjustments for admin display might be needed (../assets/...)
        return 'assets/uploads/' . $filename;
    }

    return ['error' => 'Failed to move uploaded file.'];
}
?>
