<?php
/**
 * Image Upload Helper for Chatbot AI.
 *
 * @package Replyan_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class Replyan_AI_Upload {
	/**
	 * Handle image upload securely using wp_handle_upload.
	 *
	 * @param array $file The $_FILES['image'] entry.
	 * @return string|WP_Error The uploaded file URL or a WP_Error object.
	 */
	public static function handle_image_upload( array $file ) {
		if ( empty( $file ) ) {
			return new WP_Error( 'no_file', __( 'No file uploaded.', 'replyan-ai' ) );
		}

		// Validate image type
		$allowed_types = array( 'image/jpeg', 'image/png', 'image/gif', 'image/webp' );
		if ( ! in_array( $file['type'], $allowed_types, true ) ) {
			return new WP_Error( 'invalid_type', __( 'Only JPG, PNG, GIF, and WEBP images are allowed.', 'replyan-ai' ) );
		}

		// Validate file size (e.g. 5MB)
		$max_size = 5 * 1024 * 1024;
		if ( $file['size'] > $max_size ) {
			return new WP_Error( 'file_too_large', __( 'File size exceeds limit of 5MB.', 'replyan-ai' ) );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';
		$upload = wp_handle_upload( $file, array( 'test_form' => false ) );

		if ( isset( $upload['error'] ) ) {
			return new WP_Error( 'upload_failed', $upload['error'] );
		}

		return $upload['url'];
	}
}
