<?php
class SmallPict_Basic_Optimizer {
	private $aws;

	public function __construct( $aws ) {
		$this->aws = $aws;
	}

	public function handle_upload( $upload, $context ) {
		if ( ! in_array( $upload['type'], array( 'image/jpeg', 'image/png', 'image/gif' ) ) ) {
			return $upload;
		}

		

		$memory = 128;
		

		try {
			$payload = array(
				'image_data' => base64_encode( file_get_contents( $upload['file'] ) ),
				'is_pro'     => false, // default to false
			);

			

			$res = $this->aws->invoke_lambda( $payload );

			if ( isset( $res['optimized_image'] ) ) {
				file_put_contents( $upload['file'], base64_decode( $res['optimized_image'] ) );
			}
		} catch ( Exception $e ) {
			// error_log("SmallPict Opt Failed: " . $e->getMessage());
		}

		return $upload;
	}

	private function ensure_max_payload( $file_path ) {
		$filesize = filesize( $file_path );
		$limit    = 4 * 1024 * 1024;

		if ( $filesize > $limit ) {
			$editor = wp_get_image_editor( $file_path );
			if ( ! is_wp_error( $editor ) ) {
				$size = $editor->get_size();
				if ( $size['width'] > 2000 || $size['height'] > 2000 ) {
					$editor->resize( 2000, 2000, false );
					$editor->set_quality( 80 );
					$editor->save( $file_path );
					clearstatcache();
				}
			}
		}
		return $file_path;
	}
}
