<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
const DROP_PRINT_BUILDER_PAGE_SLUG = 'drop-print-builder';
function drop_print_builder_page_url( int $product_id ): string {
	return add_query_arg(
		array(
			'page'       => DROP_PRINT_BUILDER_PAGE_SLUG,
			'product_id' => absint( $product_id ),
		),
		admin_url( 'admin.php' )
	);
}
function drop_print_builder_register_page() {
	add_dashboard_page(
		'',
		'',
		'edit_products',
		DROP_PRINT_BUILDER_PAGE_SLUG,
		'drop_print_builder_render_page'
	);
}
add_action( 'admin_menu', 'drop_print_builder_register_page', 20 );
function drop_print_builder_current_product_id(): int {
	if ( ! is_admin() || empty( $_GET['page'] ) || DROP_PRINT_BUILDER_PAGE_SLUG !== sanitize_key( wp_unslash( $_GET['page'] ) ) ) {
		return 0;
	}
	return isset( $_GET['product_id'] ) ? absint( wp_unslash( $_GET['product_id'] ) ) : 0;
}
function drop_print_builder_admin_body_class( string $classes ): string {
	if ( drop_print_builder_current_product_id() > 0 ) {
		$classes .= ' drop-print-builder-page';
	}
	return $classes;
}
add_filter( 'admin_body_class', 'drop_print_builder_admin_body_class' );
function drop_print_builder_suppress_notices() {
	if ( drop_print_builder_current_product_id() > 0 ) {
		remove_all_actions( 'admin_notices' );
		remove_all_actions( 'all_admin_notices' );
	}
}
add_action( 'in_admin_header', 'drop_print_builder_suppress_notices', 0 );
function drop_print_builder_render_page() {
	$product_id = drop_print_builder_current_product_id();
	$product    = $product_id > 0 ? wc_get_product( $product_id ) : null;
	if ( ! $product || ! current_user_can( 'edit_product', $product_id ) ) {
		wp_die( esc_html__( 'Product not found or you are not allowed to edit it.', 'drop-print' ) );
	}
	?>
	<div id="drop-print-builder-root" class="drop-print-builder-root">
		<noscript><?php esc_html_e( 'The Drop Print builder requires JavaScript.', 'drop-print' ); ?></noscript>
	</div>
	<?php
}
function drop_print_builder_enqueue_assets( $hook_suffix ) {
	$product_id = drop_print_builder_current_product_id();
	if ( $product_id <= 0 ) {
		return;
	}
	$build_dir  = DROP_PRINT_PLUGIN_PATH . 'assets/js/builder/build/';
	$build_url  = DROP_PRINT_PLUGIN_URL . 'assets/js/builder/build/';
	$asset_file = $build_dir . 'index.asset.php';
	if ( ! file_exists( $asset_file ) || ! file_exists( $build_dir . 'index.js' ) ) {
		wp_die( esc_html__( 'The Drop Print builder assets are missing. Run "npm run build" in the plugin directory.', 'drop-print' ) );
	}
	$asset = require $asset_file;
	wp_enqueue_style( 'dashicons' );
	wp_enqueue_script( 'dropzone-js', DROP_PRINT_PLUGIN_URL . 'assets/js/dropzone.min.js', array(), '5.9.3', true );
	wp_enqueue_script( 'stripe-v3', 'https://js.stripe.com/v3/', array(), '3.0', true );
	if ( file_exists( $build_dir . 'style-index.css' ) ) {
		wp_enqueue_style(
			'drop-print-builder',
			$build_url . 'style-index.css',
			array( 'dashicons' ),
			filemtime( $build_dir . 'style-index.css' )
		);
	}
	wp_enqueue_script(
		'drop-print-builder',
		$build_url . 'index.js',
		array_merge( $asset['dependencies'], array( 'dropzone-js', 'stripe-v3' ) ),
		$asset['version'],
		true
	);
	if ( function_exists( 'wp_set_script_translations' ) ) {
		wp_set_script_translations( 'drop-print-builder', 'drop-print', DROP_PRINT_PLUGIN_PATH . 'languages' );
	}
	$user_settings = drop_print_get_user_settings( get_current_user_id() );
	$meta          = get_post_meta( $product_id, '_drop_print_meta', true );
	$meta          = is_array( $meta ) ? $meta : array();
	$preview_id    = isset( $meta['preview_id'] ) ? absint( $meta['preview_id'] ) : 0;
	$dimensions    = ( isset( $meta['dimensions']['width'], $meta['dimensions']['height'] ) )
		? array( 'width' => absint( $meta['dimensions']['width'] ), 'height' => absint( $meta['dimensions']['height'] ) )
		: null;
	$existing_sizing = array();
	$product_obj     = wc_get_product( $product_id );
	if ( $product_obj && $product_obj->is_type( 'variable' ) ) {
		foreach ( $product_obj->get_children() as $variation_id ) {
			$variation = wc_get_product( $variation_id );
			if ( ! $variation || ! $variation->is_type( 'variation' ) ) {
				continue;
			}
			$sku = get_post_meta( $variation_id, '_drop_print_sku', true );
			if ( empty( $sku ) ) {
				continue;
			}
			$existing_sizing[ $sku ] = array(
				'sizing' => (string) get_post_meta( $variation_id, '_drop_print_sizing', true ),
				'price'  => $variation->get_regular_price(),
			);
		}
	}
	$pro_account_state   = $user_settings['pro_account_state_snapshot'] ?? array();
	$pro_offer_snapshot  = ( is_array( $pro_account_state ) && ! empty( $pro_account_state['upgrade_offer'] ) && is_array( $pro_account_state['upgrade_offer'] ) )
		? $pro_account_state['upgrade_offer']
		: array();
	$payment_method_snapshot = ( is_array( $pro_account_state ) && ! empty( $pro_account_state['payment_method'] ) && is_array( $pro_account_state['payment_method'] ) )
		? $pro_account_state['payment_method']
		: array( 'has_card' => false );
	$hard_proof_snapshot = ( is_array( $pro_account_state ) && ! empty( $pro_account_state['hard_proof'] ) && is_array( $pro_account_state['hard_proof'] ) )
		? $pro_account_state['hard_proof']
		: array();
	wp_localize_script(
		'drop-print-builder',
		'dropPrintBuilderData',
		array(
			'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
			'nonce'               => wp_create_nonce( 'drop_print_nonce' ),
			'productId'           => $product_id,
			'productTitle'        => get_the_title( $product_id ),
			'productStatus'       => get_post_status( $product_id ),
			'backUrl'             => admin_url( 'post.php?post=' . $product_id . '&action=edit' ),
			'productsUrl'         => admin_url( 'edit.php?post_type=product' ),
			'apiBaseUrl'          => defined( 'DROP_PRINT_API_URI' ) ? DROP_PRINT_API_URI : null,
			'clientPluginVersion' => defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '',
			'apiAuthUserB64'      => $user_settings['auth_username_b64'] ?? null,
			'apiAuthPassB64'      => $user_settings['auth_password_b64'] ?? null,
			'maxUploadFileSizeMB' => (int) floor( wp_max_upload_size() / ( 1024 * 1024 ) ),
			'defaultImageResize'  => $user_settings['default_image_resize'] ?? 'fillPrintArea',
			'defaultMedia'        => array(
				'hasDefault' => ! empty( $user_settings['default_media_id'] ) && 'ask' !== $user_settings['default_media_id'],
				'mediaId'    => ( ! empty( $user_settings['default_media_id'] ) && 'ask' !== $user_settings['default_media_id'] )
					? (string) $user_settings['default_media_id']
					: null,
			),
			'defaultCrop'         => array(
				'hasDefault' => ! empty( $user_settings['default_image_resize'] ) && 'ask' !== $user_settings['default_image_resize'],
				'mode'       => ( ! empty( $user_settings['default_image_resize'] ) && 'ask' !== $user_settings['default_image_resize'] )
					? (string) $user_settings['default_image_resize']
					: null,
			),
			'hardProof'           => array(
				'enabled'        => (bool) apply_filters( 'drop_print_hard_proof_enabled', ! empty( $hard_proof_snapshot['enabled'] ) ),
				'price_display'  => (string) ( $hard_proof_snapshot['current']['display'] ?? '' ),
				'price_currency' => (string) ( $hard_proof_snapshot['current']['currency'] ?? '' ),
				'price_standard' => (string) ( $hard_proof_snapshot['standard']['display'] ?? '' ),
				'price_pro'      => (string) ( $hard_proof_snapshot['pro']['display'] ?? '' ),
				'is_pro'         => ! empty( $hard_proof_snapshot['is_pro'] ),
				'auto_production_setting' => (string) ( $user_settings['auto_production'] ?? 'off' ),
			),
			'paymentMethod'       => array(
				'hasCard'  => ! empty( $payment_method_snapshot['has_card'] ),
				'brand'    => $payment_method_snapshot['brand'] ?? null,
				'last4'    => $payment_method_snapshot['last4'] ?? null,
				'expMonth' => $payment_method_snapshot['exp_month'] ?? null,
				'expYear'  => $payment_method_snapshot['exp_year'] ?? null,
			),
			'existingFile'        => ! empty( $meta['file'] ) ? (string) $meta['file'] : null,
			'existingPreviewUrl'  => ! empty( $meta['preview_url'] )
				? (string) $meta['preview_url']
				: ( $preview_id > 0 ? ( wp_get_attachment_url( $preview_id ) ?: null ) : null ),
			'existingSourceIccName' => ! empty( $meta['source_icc_name'] ) ? (string) $meta['source_icc_name'] : null,
			'existingCameraMakeModel' => ! empty( $meta['camera_make_model'] ) ? (string) $meta['camera_make_model'] : null,
			'existingDimensions'  => $dimensions,
			'existingSizing'      => $existing_sizing,
			'logoUrl'             => file_exists( DROP_PRINT_PLUGIN_PATH . 'assets/images/text-logo-small-dark.png' )
				? DROP_PRINT_PLUGIN_URL . 'assets/images/text-logo-small-dark.png'
				: null,
			'countries'           => ( function_exists( 'WC' ) && WC()->countries ) ? WC()->countries->get_countries() : array(),
			'defaultDestination'  => ! empty( $user_settings['default_customer_location'] )
				? (string) $user_settings['default_customer_location']
				: ( function_exists( 'wc_get_customer_default_location' )
					? (string) ( wc_get_customer_default_location()['country'] ?? '' )
					: '' ),
			'dimensionUnit'       => get_option( 'woocommerce_dimension_unit', 'in' ),
		)
	);
}
add_action( 'admin_enqueue_scripts', 'drop_print_builder_enqueue_assets' );
function drop_print_builder_row_action( array $actions, $post ): array {
	if ( $post && 'product' === $post->post_type && current_user_can( 'edit_product', $post->ID ) ) {
		$actions['drop_print_builder'] = sprintf(
			'<a href="%s" aria-label="%s">%s</a>',
			esc_url( drop_print_builder_page_url( (int) $post->ID ) ),
			esc_attr( sprintf( __( 'Edit "%s" with Drop Print', 'drop-print' ), get_the_title( $post ) ) ),
			esc_html__( 'Edit with Drop Print', 'drop-print' )
		);
	}
	return $actions;
}
add_filter( 'post_row_actions', 'drop_print_builder_row_action', 10, 2 );
function drop_print_builder_edit_screen_button( $post ) {
	if ( ! $post || 'product' !== $post->post_type || ! current_user_can( 'edit_product', $post->ID ) ) {
		return;
	}
	?>
	<div class="drop-print-builder-launch-wrap" style="margin: 8px 0 4px;">
		<a href="<?php echo esc_url( drop_print_builder_page_url( (int) $post->ID ) ); ?>"
		   id="drop-print-launch-builder"
		   class="button button-primary button-hero drop-print-builder-launch">
			<span class="dashicons dashicons-art" style="vertical-align: text-bottom; margin-right: 4px;"></span>
			<?php esc_html_e( 'Edit with Drop Print', 'drop-print' ); ?>
		</a>
	</div>
	<?php
}
add_action( 'edit_form_after_title', 'drop_print_builder_edit_screen_button' );
function drop_print_builder_apply_variations_handler() {
	check_ajax_referer( 'drop_print_nonce', 'nonce' );
	$product_id = isset( $_POST['product_id'] ) ? absint( $_POST['product_id'] ) : 0;
	if ( $product_id <= 0 || ! current_user_can( 'edit_product', $product_id ) ) {
		wp_send_json_error( array( 'message' => __( 'Invalid request or insufficient permissions.', 'drop-print' ) ), 403 );
		return;
	}
	$product = wc_get_product( $product_id );
	if ( ! $product ) {
		wp_send_json_error( array( 'message' => __( 'Product not found.', 'drop-print' ) ), 404 );
		return;
	}
	if ( ! function_exists( 'drop_print_save_product_meta' ) ) {
		wp_send_json_error( array( 'message' => __( 'Variation writer unavailable.', 'drop-print' ) ), 500 );
		return;
	}
	if ( ! $product->is_type( 'variable' ) ) {
		wp_set_object_terms( $product_id, 'variable', 'product_type', false );
	}
	drop_print_save_product_meta( $product_id );
	if ( class_exists( 'WC_Product_Variable' ) && method_exists( 'WC_Product_Variable', 'sync' ) ) {
		WC_Product_Variable::sync( $product_id );
	}
	$meta       = get_post_meta( $product_id, '_drop_print_meta', true );
	$meta       = is_array( $meta ) ? $meta : array();
	$variations = isset( $meta['variations'] ) && is_array( $meta['variations'] ) ? $meta['variations'] : array();
	$applied    = array();
	$failed     = array();
	foreach ( $variations as $variation ) {
		$row = array(
			'sku'             => (string) ( $variation['sku'] ?? '' ),
			'price'           => (string) ( $variation['price'] ?? '' ),
			'title'           => (string) ( $variation['title'] ?? '' ),
			'wc_variation_id' => isset( $variation['wc_variation_id'] ) ? (int) $variation['wc_variation_id'] : 0,
		);
		if ( $row['wc_variation_id'] > 0 ) {
			$applied[] = $row;
		} else {
			$failed[] = $row;
		}
	}
	wp_send_json_success(
		array(
			'applied'  => $applied,
			'failed'   => $failed,
			'edit_url' => admin_url( 'post.php?post=' . $product_id . '&action=edit' ),
			'message'  => empty( $failed )
				? __( 'Your prints were saved as product variations.', 'drop-print' )
				: __( 'Some sizes could not be saved - see the product for details.', 'drop-print' ),
		)
	);
}
add_action( 'wp_ajax_drop_print_builder_apply_variations', 'drop_print_builder_apply_variations_handler' );
