<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
function drop_print_handle_check_dimensions() {
	try {
		check_ajax_referer( 'drop_print_nonce', 'nonce' );
		if ( ! current_user_can( 'upload_files' ) || ! current_user_can( 'edit_products' ) ) {
			throw new Exception( __( 'Permission denied.', 'drop-print' ), 403 );
		}
		$product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
		if ( ! isset( $_FILES['file_chunk'] )
			|| empty( $_FILES['file_chunk']['tmp_name'] )
			|| ! is_uploaded_file( $_FILES['file_chunk']['tmp_name'] )
			|| ! isset( $_FILES['file_chunk']['error'] )
			|| UPLOAD_ERR_OK !== $_FILES['file_chunk']['error']
		) {
			$error_code = isset($_FILES['file_chunk']['error']) ? absint($_FILES['file_chunk']['error']) : UPLOAD_ERR_NO_FILE;
			throw new Exception( sprintf( __( 'Upload Error for dimension check chunk: Code %d', 'drop-print' ), $error_code ), 400 );
		}
		$chunk_tmp_name = $_FILES['file_chunk']['tmp_name'];
		$image_info = @getimagesize( $chunk_tmp_name );
		if ( false === $image_info || empty( $image_info[0] ) || empty( $image_info[1] ) ) {
			throw new Exception( __( 'Dimensions not found in file header chunk.', 'drop-print' ), 400 );
		}
		$width  = absint( $image_info[0] );
		$height = absint( $image_info[1] );
		wp_send_json_success(
			array(
				'width'  => $width,
				'height' => $height,
			)
		);
	} catch ( Exception $e ) {
		$error_code = is_int( $e->getCode() ) && $e->getCode() >= 400 ? $e->getCode() : 400;
		wp_send_json_error(
			array( 'message' => $e->getMessage() ),
			$error_code
		);
	}
}
add_action( 'wp_ajax_drop_print_check_dimensions', 'drop_print_handle_check_dimensions' );
