<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
require_once ABSPATH . 'wp-admin/includes/media.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/image.php';
function drop_print_add_admin_menu_settings_page() {
	add_menu_page(
		__( 'Drop Print Settings', 'drop-print' ),
		__( 'Drop Print', 'drop-print' ),
		'manage_options',
		'drop-print-settings',
		'drop_print_render_settings_page',
		DROP_PRINT_PLUGIN_URL . 'assets/images/icon-drop-print-settings.png',
		99
	);
}
add_action( 'admin_menu', 'drop_print_add_admin_menu_settings_page' );
function drop_print_client_enqueue_admin_scripts_conditional( $hook_suffix ) {
	$client_settings_page_hook = 'toplevel_page_drop-print-settings';
	if ( 'index.php' === $hook_suffix || $client_settings_page_hook === $hook_suffix ) {
		wp_enqueue_script(
			'drop-print-client-settings-js',
			DROP_PRINT_PLUGIN_URL . 'assets/js/admin/drop-print-settings.js',
			array( 'jquery' ),
			defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
			true
		);
		$upgrade_config = function_exists( 'drop_print_get_pro_upgrade_client_config' ) ? drop_print_get_pro_upgrade_client_config( __( 'Settings', 'drop-print' ), 'settings_page' ) : array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce' => wp_create_nonce( 'drop_print_pro_upgrade_workflow_action' ),
			'request_session_action' => 'drop_print_request_pro_upgrade_session',
			'account_state_action' => 'drop_print_poll_pro_upgrade_account_state',
			'surface_label' => __( 'Settings', 'drop-print' ),
			'origin_surface' => 'settings_page',
			'site_label' => get_bloginfo( 'name' ),
			'poll_interval_ms' => 5000,
			'poll_max_attempts' => 72,
			'client_plugin_version' => defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
			'labels' => array(
				'modal_title' => __( 'Upgrade to Drop Print Pro', 'drop-print' ),
				'loading' => __( 'Preparing your Pro upgrade…', 'drop-print' ),
				'opening_checkout' => __( 'Opening checkout…', 'drop-print' ),
				'polling' => __( 'Checking your account state…', 'drop-print' ),
				'success' => __( 'Pro upgrade complete.', 'drop-print' ),
				'close' => __( 'Close', 'drop-print' ),
				'open_checkout' => __( 'Open checkout', 'drop-print' ),
				'retry' => __( 'Try again', 'drop-print' ),
				'error_prefix' => __( 'Error:', 'drop-print' ),
				'expired' => __( 'The upgrade session expired. Please start again.', 'drop-print' ),
				'not_ready' => __( 'Upgrade session is not ready yet.', 'drop-print' ),
			),
		);
		wp_enqueue_script(
			'drop-print-pro-unlock-animation',
			DROP_PRINT_PLUGIN_URL . 'assets/js/shared/drop-print-pro-unlock-animation.js',
			array( 'jquery' ),
			defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
			true
		);
		wp_enqueue_script(
			'drop-print-pro-upgrade-session',
			DROP_PRINT_PLUGIN_URL . 'assets/js/shared/drop-print-pro-upgrade.js',
			array( 'jquery', 'drop-print-pro-unlock-animation' ),
			defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
			true
		);
		wp_localize_script( 'drop-print-pro-upgrade-session', 'dropPrintProUpgradeData', $upgrade_config );
		wp_enqueue_style(
			'drop-print-pre-production-styles',
			DROP_PRINT_PLUGIN_URL . 'assets/css/production.css',
			array(),
			defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3'
		);
		if ( $client_settings_page_hook === $hook_suffix ) {
			wp_enqueue_style(
				'drop-print-settings-styles',
				DROP_PRINT_PLUGIN_URL . 'assets/css/settings.css',
				array( 'drop-print-pre-production-styles' ),
				defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3'
			);
		}
	}
}
add_action( 'admin_enqueue_scripts', 'drop_print_client_enqueue_admin_scripts_conditional' );
function drop_print_check_server_status_on_settings_page() {
	if ( ! defined( 'DROP_PRINT_API_URI' ) || empty( DROP_PRINT_API_URI ) ) {
		return array( 'status' => false, 'message' => __( 'API URI Not Defined', 'drop-print' ), 'code' => null );
	}
	$response = wp_remote_get( esc_url_raw( DROP_PRINT_API_URI ), array( 'timeout' => 15 ) );
	if ( is_wp_error( $response ) ) {
		return array( 'status' => false, 'message' => sprintf(__( 'The Drop Print API Server is offline. If this is persistent, contact support quoting: "%s"', 'drop-print' ), $response->get_error_message()), 'code' => $response->get_error_code() );
	}
	$status_code = wp_remote_retrieve_response_code( $response );
	if ( 200 === $status_code ) {
		return array( 'status' => true, 'message' => __( 'Online', 'drop-print' ), 'code' => $status_code );
	}
	else {
		return array( 'status' => false, 'message' => sprintf( __( 'Offline (HTTP %d)', 'drop-print' ), $status_code ), 'code' => $status_code );
	}
}
function drop_print_handle_disconnect_user_on_settings_page() {
	if ( isset( $_POST['drop_print_disconnect_user'] ) && check_admin_referer( 'drop_print_disconnect_user_action' ) ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'drop-print' ) );
		}
		$user_id = get_current_user_id();
		if ( $user_id > 0 ) {
			delete_user_meta( $user_id, 'drop_print_user_settings' );
		}
		wp_safe_redirect( admin_url( 'admin.php?page=drop-print-settings&disconnected=1' ) );
		exit;
	}
}
add_action( 'admin_init', 'drop_print_handle_disconnect_user_on_settings_page' );
function drop_print_handle_refresh_user_data_on_settings_page() {
	if ( isset( $_POST['drop_print_refresh_user_data'] ) && check_admin_referer( 'drop_print_refresh_user_data_action' ) ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'drop-print' ) );
		}
		$user_id = get_current_user_id();
		$result  = array( 'status' => false, 'message' => __( 'User not found or unable to refresh.', 'drop-print' ) );
		if ( $user_id > 0 && function_exists( 'drop_print_client_refresh_data_and_status' ) ) {
			$result = drop_print_client_refresh_data_and_status( $user_id );
		}
		$query_arg = $result['status'] ? 'refreshed' : 'refresh_failed';
		$message   = urlencode( $result['message'] );
		wp_safe_redirect( admin_url( 'admin.php?page=drop-print-settings&' . $query_arg . '=1&message=' . $message . '&refreshed_by_action=true' ) );
		exit;
	}
}
add_action( 'admin_init', 'drop_print_handle_refresh_user_data_on_settings_page' );
function drop_print_handle_save_user_settings_on_settings_page() {
	if ( ! isset( $_POST['save_user_settings_drop_print'] ) || ! check_admin_referer( 'drop_print_save_user_settings_nonce' ) ) {
		return;
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'drop-print' ) );
	}
	$user_id = get_current_user_id();
	if ( $user_id === 0 ) {
		add_settings_error( 'general', 'settings_save_failed', esc_html__( 'Could not save settings: User not identified.', 'drop-print' ), 'error' );
		return;
	}
	$settings                       = drop_print_get_user_settings( $user_id );
	$defaults                       = drop_print_get_default_user_settings();
	$settings['default_media_id']   = isset( $_POST['default_media_id'] ) ? sanitize_key( wp_unslash( $_POST['default_media_id'] ) ) : $defaults['default_media_id'];
	$settings['default_image_resize'] = isset( $_POST['default_image_resize'] ) ? sanitize_key( wp_unslash( $_POST['default_image_resize'] ) ) : $defaults['default_image_resize'];
	$settings['default_shipping_method'] = isset( $_POST['default_shipping_method'] ) ? sanitize_key( wp_unslash( $_POST['default_shipping_method'] ) ) : $defaults['default_shipping_method'];
	$settings['place_order_blocked_text'] = isset( $_POST['place_order_blocked_text'] ) ? sanitize_text_field( wp_unslash( $_POST['place_order_blocked_text'] ) ) : $defaults['place_order_blocked_text'];
	$settings['us_sales_tax_collected'] = isset( $_POST['us_sales_tax_collected'] ) && in_array( wp_unslash( $_POST['us_sales_tax_collected'] ), array( 'true', 'false' ), true ) ? sanitize_text_field( wp_unslash( $_POST['us_sales_tax_collected'] ) ) : $defaults['us_sales_tax_collected'];
	$settings['encryption'] = isset( $_POST['encryption'] );
	$settings['auto_production'] = isset( $_POST['auto_production'] ) ? sanitize_text_field( wp_unslash( $_POST['auto_production'] ) ) : $defaults['auto_production'];
	if ( isset( $_FILES['packing_slip'] ) && isset( $_FILES['packing_slip']['error'] ) && UPLOAD_ERR_OK === $_FILES['packing_slip']['error'] ) {
		$file_info = wp_check_filetype_and_ext( $_FILES['packing_slip']['tmp_name'], $_FILES['packing_slip']['name'] );
		if ( $file_info['type'] !== 'image/png' ) {
			add_settings_error( 'packing_slip_upload', 'invalid_file_type', esc_html__( 'Invalid file type. Please upload a PNG file.', 'drop-print' ), 'error' );
		} else {
			$attachment_id = media_handle_upload( 'packing_slip', 0 );
			if ( is_wp_error( $attachment_id ) ) {
				add_settings_error( 'packing_slip_upload', 'upload_error', sprintf( esc_html__( 'Packing slip upload failed: %s', 'drop-print' ), $attachment_id->get_error_message() ), 'error' );
			} else {
				$old_attachment_id = $settings['packing_slip_attachment_id'] ?? 0;
				if ( $old_attachment_id && $old_attachment_id != $attachment_id ) {
					wp_delete_attachment( $old_attachment_id, true );
				}
				$settings['packing_slip_attachment_id'] = $attachment_id;
				add_settings_error( 'packing_slip_upload', 'upload_success', sprintf( esc_html__( 'Packing slip "%s" uploaded successfully.', 'drop-print' ), esc_html( basename( get_attached_file( $attachment_id ) ) ) ), 'updated' );
			}
		}
	} elseif ( isset( $_FILES['packing_slip'], $_FILES['packing_slip']['error'] ) && UPLOAD_ERR_NO_FILE !== $_FILES['packing_slip']['error'] ) {
		add_settings_error( 'packing_slip_upload', 'upload_error_generic', esc_html__( 'Packing slip upload failed. Please check file size and type.', 'drop-print' ) . ' (Error Code: ' . esc_html( (int) $_FILES['packing_slip']['error'] ) . ')', 'error' );
	}
	update_user_meta( $user_id, 'drop_print_user_settings', $settings );
	add_settings_error( 'general', 'settings_saved', esc_html__( 'Settings saved successfully for current user!', 'drop-print' ), 'updated' );
}
add_action( 'admin_init', 'drop_print_handle_save_user_settings_on_settings_page' );
function drop_print_render_settings_page() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'drop-print' ) );
	}
	$user_id = get_current_user_id();
	if ( $user_id === 0 ) {
		echo '<div class="notice notice-error"><p>' . esc_html__( 'Cannot display settings: User not identified.', 'drop-print' ) . '</p></div>';
		return;
	}
	$pro_activated_notice          = '';
	$refresh_notice                = '';
	$get_pro_param                 = isset( $_GET['pro'] ) ? sanitize_key( $_GET['pro'] ) : '';
	$get_refreshed_by_action_param = isset( $_GET['refreshed_by_action'] ) ? sanitize_key( $_GET['refreshed_by_action'] ) : '';
	$get_refreshed_param           = isset( $_GET['refreshed'] ) ? sanitize_key( $_GET['refreshed'] ) : '';
	$get_refresh_failed_param      = isset( $_GET['refresh_failed'] ) ? sanitize_key( $_GET['refresh_failed'] ) : '';
	$get_message_param             = isset( $_GET['message'] ) ? sanitize_text_field( wp_unslash( $_GET['message'] ) ) : '';
	if ( $get_pro_param === 'true' && ! $get_refreshed_by_action_param ) {
		if ( function_exists( 'drop_print_client_refresh_data_and_status' ) ) {
			$refresh_result = drop_print_client_refresh_data_and_status( $user_id );
			if ( $refresh_result['status'] ) {
				$pro_activated_notice = '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Congratulations! Your Drop Print Pro account has been successfully activated and your details refreshed.', 'drop-print' ) . '</p></div>';
			} else {
				$pro_activated_notice = '<div class="notice notice-warning is-dismissible"><p>' . esc_html__( 'Pro account activated! However, we could not automatically refresh your details. Please use the refresh button below. Message: ', 'drop-print' ) . esc_html( $refresh_result['message'] ) . '</p></div>';
			}
		} else {
			$pro_activated_notice = '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Congratulations! Your Drop Print Pro account has been successfully activated. Please refresh your data.', 'drop-print' ) . '</p></div>';
		}
	}
	if ( $get_refreshed_by_action_param ) {
		if ( $get_refreshed_param === '1' && $get_message_param ) {
			$refresh_notice = '<div class="notice notice-success is-dismissible"><p>' . esc_html( urldecode( $get_message_param ) ) . '</p></div>';
		} elseif ( $get_refresh_failed_param === '1' && $get_message_param ) {
			$refresh_notice = '<div class="notice notice-error is-dismissible"><p>' . esc_html( urldecode( $get_message_param ) ) . '</p></div>';
		}
	}
	$settings                      = drop_print_get_user_settings( $user_id );
	$defaults                      = drop_print_get_default_user_settings();
	$user_display_name             = $settings['user_display_name'] ?? null;
	$api_url_display               = defined( 'DROP_PRINT_API_URI' ) ? DROP_PRINT_API_URI : __( 'API URI Not Defined', 'drop-print' );
	$cost_currency                 = $settings['billing_currency'] ?? null;
	$server_status_details         = drop_print_check_server_status_on_settings_page();
	$server_available              = $server_status_details['status'];
	$server_offline_message        = $server_status_details['message'];
	$is_pro                        = (bool) ( $settings['pro_status'] ?? 0 );
	$current_packing_slip_attachment_id = $settings['packing_slip_attachment_id'] ?? 0;
	$current_packing_slip_url      = '';
	$current_packing_slip_filename = '';
	if ( $current_packing_slip_attachment_id > 0 && get_post( $current_packing_slip_attachment_id ) ) {
		$current_packing_slip_url      = wp_get_attachment_url( $current_packing_slip_attachment_id );
		$current_packing_slip_filename = basename( get_attached_file( $current_packing_slip_attachment_id ) );
	}
	$woocommerce_dimension_unit = get_option( 'woocommerce_dimension_unit', 'in' );
	$measurement_mapping         = array( 'cm' => 'cm', 'm' => 'cm', 'mm' => 'cm', 'in' => 'in', 'yd' => 'in', 'ft' => 'in' );
	$drop_print_measurement_pref = $measurement_mapping[ $woocommerce_dimension_unit ] ?? 'cm';
	$available_media             = $settings['available_media'] ?? array();
	$default_media_id_saved      = $settings['default_media_id'] ?? $defaults['default_media_id'];
	$final_default_media_id      = $default_media_id_saved;
	if ( 'ask' !== $default_media_id_saved ) {
		$is_saved_id_valid = false;
		foreach ( $available_media as $media_item ) {
			if ( isset( $media_item['id'] ) && $media_item['id'] === $default_media_id_saved ) {
				$is_saved_id_valid = true;
				break;
			}
		}
		if ( ! $is_saved_id_valid ) {
			$final_default_media_id = 'ask';
		}
	}
	$current_default_shipping     = $settings['default_shipping_method'] ?? $defaults['default_shipping_method'];
	$fetched_shipping_tiers = $settings['available_shipping_methods'] ?? array();
	if ( ! empty( $fetched_shipping_tiers ) && is_array( $fetched_shipping_tiers ) ) {
		$available_shipping_methods = array();
		foreach ( $fetched_shipping_tiers as $tier_item ) {
			if ( ! empty( $tier_item['slug'] ) && isset( $tier_item['label'] ) ) {
				$available_shipping_methods[ $tier_item['slug'] ] = $tier_item['label'];
			}
		}
	}
	if ( empty( $available_shipping_methods ) ) {
		$available_shipping_methods = array(
			'budget'    => __( 'Budget', 'drop-print' ),
			'standard'  => __( 'Standard', 'drop-print' ),
			'express'   => __( 'Express', 'drop-print' ),
			'overnight' => __( 'Overnight', 'drop-print' ),
		);
	}
	$current_default_image_resize = $settings['default_image_resize'] ?? $defaults['default_image_resize'];
	$available_image_resize_options = array(
		'ask'    => __( 'Ask every time', 'drop-print' ),
		'fit'    => __( 'Fit to page', 'drop-print' ),
		'fill'   => __( 'Fill the page', 'drop-print' ),
		'border' => __( 'Centre with border', 'drop-print' ),
	);
	$current_us_sales_tax_collected = $settings['us_sales_tax_collected'] ?? $defaults['us_sales_tax_collected'];
	?>
	<div class="wrap drop-print-settings-wrap">
		<h1>
			<?php esc_html_e( 'Drop Print Settings (Your Account)', 'drop-print' ); ?>
			<?php if ( function_exists( 'drop_print_onboarding_page_url' ) ) : ?>
				<a href="<?php echo esc_url( drop_print_onboarding_page_url() ); ?>" class="page-title-action"><?php esc_html_e( 'Re-run setup', 'drop-print' ); ?></a>
			<?php endif; ?>
		</h1>
		<?php
		if ( ! empty( $pro_activated_notice ) ) {
			echo wp_kses_post( $pro_activated_notice );
		}
		if ( ! empty( $refresh_notice ) ) {
			echo wp_kses_post( $refresh_notice );
		}
		settings_errors( 'drop_print_pro_status' );
		settings_errors( 'packing_slip_upload' );
		settings_errors( 'general' );
		$get_disconnected_param = isset( $_GET['disconnected'] ) ? sanitize_key( $_GET['disconnected'] ) : '';
		if ( $get_disconnected_param === '1' ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Successfully disconnected your user account from Drop Print.', 'drop-print' ) . '</p></div>';
		}
		if ( ! empty( $settings['client_user_connection_id'] ) && ! $server_available ) {
			echo '<div class="notice notice-error is-dismissible"><p>' . esc_html( $server_offline_message ) . '</p></div>';
		}
		?>
		<table class="form-table drop-print-status-table">
			<tbody>
			<?php if ( empty( $settings['client_user_connection_id'] ) ) : ?>
				<?php
				$connect_page_url = admin_url( 'admin.php?page=drop-print-settings' );
				if ( function_exists( 'drop_print_display_connect_notice' ) ) {
				} else {
					echo '<tr><td colspan="2"><p>';
					printf( wp_kses_post( __( 'You are not currently connected to Drop Print. Please <a href="%s">Connect your account</a> to manage settings.', 'drop-print' ) ), esc_url( $connect_page_url ) );
					echo '</p></td></tr>';
				}
				if ( function_exists( 'drop_print_use_headless_connect' ) && drop_print_use_headless_connect() ) :
					?>
					<tr>
						<td colspan="2"><?php drop_print_render_reconnect_widget(); ?></td>
					</tr>
				<?php endif; ?>
			<?php else : ?>
				<tr>
					<th scope="row"><?php esc_html_e( 'Your Username', 'drop-print' ); ?></th>
					<td><strong><?php echo esc_html( $user_display_name ?: __( 'N/A', 'drop-print' ) ); ?></strong></td>
				</tr>
				<?php if ( $cost_currency ) : ?>
					<tr>
						<th scope="row"><?php esc_html_e( 'Your Billing Currency', 'drop-print' ); ?></th>
						<td>
							<strong><?php echo esc_html( $cost_currency ); ?></strong>
							<p class="description"><?php esc_html_e( 'This is your fixed billing currency set during account connection.', 'drop-print' ); ?></p>
						</td>
					</tr>
				<?php endif; ?>
				<tr>
					<th scope="row"><?php esc_html_e( 'Your Account Status', 'drop-print' ); ?></th>
					<td>
						<strong id="drop-print-account-status-value" data-pro-label="<?php echo esc_attr__( 'Pro User', 'drop-print' ); ?>" data-standard-label="<?php echo esc_attr__( 'Standard User', 'drop-print' ); ?>"><?php echo $is_pro ? esc_html__( 'Pro User', 'drop-print' ) : esc_html__( 'Standard User', 'drop-print' ); ?></strong>
						<?php if ( ! $is_pro ) : ?>
							<button type="button" class="button button-primary drop-print-pro-upgrade-launcher" data-upgrade-origin="settings_page" data-upgrade-surface="settings"><?php esc_html_e( 'Upgrade to Pro', 'drop-print' ); ?></button>
						<?php endif; ?>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e( 'Your Connection', 'drop-print' ); ?></th>
					<td style="display: flex; gap: 10px; align-items: center;">
						<form method="POST" action="" style="margin:0;">
<?php wp_nonce_field( 'drop_print_disconnect_user_action' );
$current_user_id = get_current_user_id();
$user_settings = drop_print_get_user_settings( $current_user_id );
$encryption_enabled = ! empty( $user_settings['encryption'] );
if ( $encryption_enabled ) {
	$disconnect_confirm = __(
		"Warning – Read Before Disconnecting\n\n" .
		"Your uploaded artwork is encrypted against your current Drop Print account.\n\n" .
		"Before disconnecting, make a note of the account currently shown on this page.\n\n" .
		"If you later reconnect using a different Drop Print account, previously encrypted artwork will not be accessible and any orders containing those files will fail.\n\n" .
		"If you intend to reconnect, I strongly recommend using the same Drop Print account.\n\n" .
		"Are you sure you wish to disconnect your account?",
		'drop-print'
	);
} else {
	$disconnect_confirm = __(
		"Disconnect your Drop Print account?\n\n" .
		"You will no longer be able to synchronise products, orders or artwork until you reconnect.\n\n" .
		"Are you sure you wish to disconnect your account?",
		'drop-print'
	);
}
?>
<button
	type="submit"
	name="drop_print_disconnect_user"
	class="button button-secondary drop-print-disconnect-button"
	onclick="return confirm('<?php echo esc_js( $disconnect_confirm ); ?>');"
>
	<?php esc_html_e( 'Disconnect My Account', 'drop-print' ); ?>
</button>
						</form>
						<form method="POST" action="" style="margin:0;">
							<?php wp_nonce_field( 'drop_print_refresh_user_data_action' ); ?>
							<button type="submit" name="drop_print_refresh_user_data" class="button button-secondary" <?php disabled( ! $server_available ); ?>><?php esc_html_e( 'Reload Account Info', 'drop-print' ); ?></button>
						</form>
					</td>
				</tr>
				<?php if ( function_exists( 'drop_print_use_headless_connect' ) && drop_print_use_headless_connect() ) : ?>
					<tr>
						<td colspan="2"><?php drop_print_render_reconnect_widget(); ?></td>
					</tr>
				<?php endif; ?>
			<?php endif; ?>
			</tbody>
		</table>
		<?php if ( ! empty( $settings['client_user_connection_id'] ) ) : ?>
			<h3><?php esc_html_e( 'Your Settings', 'drop-print' ); ?></h3>
			<form method="POST" action="" enctype="multipart/form-data">
				<?php wp_nonce_field( 'drop_print_save_user_settings_nonce' ); ?>
				<input type="hidden" name="action" value="drop_print_save_user_settings_on_settings_page_action" />
				<table class="form-table">
					<tbody>
					<tr>
						<th scope="row"><label for="packing_slip_upload_trigger"><?php esc_html_e( 'Your Packing Slip', 'drop-print' ); ?></label></th>
						<td>
							<div id="drop-print-current-packing-slip-container" style="<?php echo $current_packing_slip_filename ? '' : 'display:none;'; ?>">
								<?php if ( $current_packing_slip_filename && $current_packing_slip_url ) : ?>
									<p class="description">
										<a href="<?php echo esc_url( $current_packing_slip_url ); ?>" target="_blank" rel="noopener"><?php echo esc_html( $current_packing_slip_filename ); ?></a>
										<span class="drop-print-replace-packing-slip" style="cursor:pointer; margin-left: 10px;" title="<?php esc_attr_e( 'Replace Packing Slip', 'drop-print' ); ?>"><?php echo esc_html( '?' ); ?></span>
									</p>
								<?php else : ?>
									<p class="description"><?php esc_html_e( 'No packing slip uploaded, or unable to retrieve details.', 'drop-print' ); ?></p>
								<?php endif; ?>
							</div>
							<div id="drop-print-upload-packing-slip-container" style="<?php echo $current_packing_slip_filename ? 'display:none;' : ''; ?>">
								<input type="file" id="packing_slip_upload_trigger" name="packing_slip" accept="image/png">
								<p class="description"><?php esc_html_e( 'Upload an A4 PNG file (72 DPI recommended).', 'drop-print' ); ?></p>
							</div>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="us_sales_tax_collected"><?php esc_html_e( 'US Sales Tax Collected?', 'drop-print' ); ?></label></th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><?php esc_html_e( 'US Sales Tax Collected', 'drop-print' ); ?></legend>
								<label><input type="radio" name="us_sales_tax_collected" value="true" <?php checked( $current_us_sales_tax_collected, 'true' ); ?>> <?php esc_html_e( 'Yes', 'drop-print' ); ?></label><br />
								<label><input type="radio" name="us_sales_tax_collected" value="false" <?php checked( $current_us_sales_tax_collected, 'false' ); ?>> <?php esc_html_e( 'No', 'drop-print' ); ?></label>
							</fieldset>
							<p class="description"><?php esc_html_e( 'Indicate if US sales tax is collected and remitted for orders. This information may be passed to the print server.', 'drop-print' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="drop-print-measurement-unit-preference"><?php esc_html_e( 'Measurements', 'drop-print' ); ?></label></th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><?php esc_html_e( 'Measurement Unit Preference', 'drop-print' ); ?></legend>
								<label><input type="radio" name="drop_print_measurement_pref_display" value="cm" <?php checked( $drop_print_measurement_pref, 'cm' ); ?> disabled> <?php esc_html_e( 'Centimetres (cm)', 'drop-print' ); ?></label><br />
								<label><input type="radio" name="drop_print_measurement_pref_display" value="in" <?php checked( $drop_print_measurement_pref, 'in' ); ?> disabled> <?php esc_html_e( 'Inches (in)', 'drop-print' ); ?></label>
							</fieldset>
							<?php
							$wc_settings_product_url   = esc_url( admin_url( 'admin.php?page=wc-settings&tab=products&section' ) );
							$wc_settings_link_text     = esc_html__( 'WooCommerce Settings', 'drop-print' );
							$wc_settings_link          = sprintf( '<a href="%s" target="_blank" rel="noopener">%s</a>', $wc_settings_product_url, $wc_settings_link_text );
							$description_text_format = __( 'Unit preference derived from the <i>Dimensions unit</i> setting in %s (this is a site-wide WooCommerce setting).', 'drop-print' );
							$description_with_link   = sprintf( $description_text_format, $wc_settings_link );
							echo '<p class="description">' . wp_kses_post( $description_with_link ) . '</p>';
							?>
						</td>
					</tr>
<tr>
	<th scope="row">
		<label for="drop-print-encryption">
			<?php esc_html_e( 'File Encryption', 'drop-print' ); ?>
		</label>
	</th>
	<td>
		<label>
			<input
				type="checkbox"
				id="drop-print-encryption"
				name="encryption"
				value="1"
				<?php checked( ! empty( $settings['encryption'] ) ); ?>
			/>
			<?php esc_html_e( 'Encrypt uploaded artwork', 'drop-print' ); ?>
		</label>
		<p class="description">
			<?php esc_html_e( 'Recommended only if your organisation requires encrypted .drop files. If disabled, uploads will be packaged as standard .drop files without encryption.', 'drop-print' ); ?>
		</p>
	</td>
</tr>
					<tr>
						<th scope="row"><label for="drop-print-default-image-resize"><?php esc_html_e( 'Your Default Image Resize', 'drop-print' ); ?></label></th>
						<td>
							<select name="default_image_resize" id="drop-print-default-image-resize">
								<?php foreach ( $available_image_resize_options as $option_key => $option_name ) : ?>
									<option value="<?php echo esc_attr( $option_key ); ?>" <?php selected( $current_default_image_resize, $option_key ); ?>>
										<?php echo esc_html( $option_name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description"><?php esc_html_e( 'When your uploaded image is within 4mm of the selected print size, Drop Print can automatically resize it to fit. Choose how it should resize by default, or select "Ask every time" to be prompted per order.', 'drop-print' ); ?></p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="drop-print-default-media-id"><?php esc_html_e( 'Your Default Media Selection', 'drop-print' ); ?></label></th>
						<td>
							<?php
							$available_media_groups = array();
							foreach ( $available_media as $media_item ) {
								if ( ! isset( $media_item['id'], $media_item['name'] ) ) {
									continue;
								}
								$group_label = ! empty( $media_item['media_category_label'] )
									? $media_item['media_category_label']
									: __( 'Other', 'drop-print' );
								$available_media_groups[ $group_label ][] = $media_item;
							}
							?>
							<select name="default_media_id" id="drop-print-default-media-id">
								<option value="ask" <?php selected( $final_default_media_id, 'ask' ); ?>><?php esc_html_e( 'Ask every time', 'drop-print' ); ?></option>
								<?php foreach ( $available_media_groups as $group_label => $group_items ) : ?>
									<optgroup label="<?php echo esc_attr( $group_label ); ?>">
										<?php foreach ( $group_items as $media_item ) : ?>
											<option value="<?php echo esc_attr( $media_item['id'] ); ?>" <?php selected( $final_default_media_id, $media_item['id'] ); ?>>
												<?php echo esc_html( $media_item['name'] ); ?>
											</option>
										<?php endforeach; ?>
									</optgroup>
								<?php endforeach; ?>
							</select>
							<p class="description">
								<?php
								if ( empty( $available_media ) ) {
									esc_html_e( 'Refresh your data ("Reload Account Info") to populate the live list of papers.', 'drop-print' );
								} else {
									esc_html_e( 'Select your preferred default paper for new products, or "Ask every time" to be prompted per product.', 'drop-print' );
								}
								?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="drop-print-default-shipping-method"><?php esc_html_e( 'Your Default Shipping Method', 'drop-print' ); ?></label></th>
						<td>
							<select name="default_shipping_method" id="drop-print-default-shipping-method" class="drop-print-default-shipping-method-select">
								<?php foreach ( $available_shipping_methods as $method_key => $method_name ) : ?>
									<option value="<?php echo esc_attr( $method_key ); ?>" <?php selected( $current_default_shipping, $method_key ); ?>>
										<?php echo esc_html( $method_name ); ?>
									</option>
								<?php endforeach; ?>
							</select>
							<p class="description" id="drop-print-default-shipping-method-description">
								<?php esc_html_e( 'Select your preferred default shipping method for new products. This is also the tier pre-selected at checkout; customers can still pick another tier when it is available. You can change this per order during "Quote & Pay".', 'drop-print' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="drop-print-place-order-blocked-text"><?php esc_html_e( '"Place Order" Blocked Text', 'drop-print' ); ?></label></th>
						<td>
							<input type="text" name="place_order_blocked_text" id="drop-print-place-order-blocked-text" class="regular-text" value="<?php echo esc_attr( $settings['place_order_blocked_text'] ?? $defaults['place_order_blocked_text'] ); ?>" placeholder="<?php esc_attr_e( 'Updating shipping rate…', 'drop-print' ); ?>">
							<p class="description">
								<?php esc_html_e( 'Shown on the "Place Order" button at checkout while your live shipping price is still being confirmed. Leave blank to use the default shown above.', 'drop-print' ); ?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><?php esc_html_e( 'Payment Card', 'drop-print' ); ?></th>
						<td>
							<?php
							$payment_method_snapshot = $settings['payment_method_snapshot'] ?? $defaults['payment_method_snapshot'];
							$has_card_on_file         = ! empty( $payment_method_snapshot['has_card'] );
							if ( $has_card_on_file ) {
								$card_brand = $payment_method_snapshot['brand'] ? ucfirst( $payment_method_snapshot['brand'] ) : __( 'Card', 'drop-print' );
								printf(
									esc_html__( '%1$s •••• %2$s (expires %3$s/%4$s)', 'drop-print' ),
									esc_html( $card_brand ),
									esc_html( (string) $payment_method_snapshot['last4'] ),
									esc_html( str_pad( (string) $payment_method_snapshot['exp_month'], 2, '0', STR_PAD_LEFT ) ),
									esc_html( substr( (string) $payment_method_snapshot['exp_year'], -2 ) )
								);
							} else {
								esc_html_e( 'No card on file.', 'drop-print' );
							}
							?>
							<p class="description">
								<?php
								printf( wp_kses_post( __( 'Manage your saved card at <a href="%s" target="_blank" rel="noopener">Drop Print</a>. Updates here after your next settings refresh.', 'drop-print' ) ), drop_print_network_base_url( 'account' ) . '/my-account/payment-methods/' );
								?>
							</p>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="drop_print_auto_production"><?php esc_html_e( 'Auto Production', 'drop-print' ); ?></label></th>
						<td>
							<select name="auto_production" id="drop_print_auto_production">
								<option value="off" <?php selected( $settings['auto_production'] ?? $defaults['auto_production'], 'off' ); ?>><?php esc_html_e( 'Off', 'drop-print' ); ?></option>
								<option value="on" <?php selected( $settings['auto_production'] ?? $defaults['auto_production'], 'on' ); ?>><?php esc_html_e( 'On', 'drop-print' ); ?></option>
							</select>
							<p class="description" id="drop_print_auto_production_description">
								<?php
								printf( wp_kses_post( __( 'Automatically send orders to print upon customer payment. Requires a valid payment card on file at <a href="%s" target="_blank" rel="noopener">Drop Print</a>.', 'drop-print' ) ), drop_print_network_base_url( 'account' ) . '/my-account/payment-methods/' );
								?>
							</p>
							<?php if ( ( $settings['auto_production'] ?? $defaults['auto_production'] ) === 'on' && ! $has_card_on_file ) : ?>
								<p class="description" id="drop_print_auto_production_no_card_warning" style="color:#b32d2e;">
									<?php esc_html_e( 'No card on file — auto-production will fail at the payment step.', 'drop-print' ); ?>
								</p>
							<?php endif; ?>
						</td>
					</tr>
					</tbody>
				</table>
				<?php submit_button( __( 'Save My Settings', 'drop-print' ), 'primary', 'save_user_settings_drop_print' ); ?>
			</form>
		<?php endif; ?>
		<div class="drop-print-settings-footer">
			<p class="drop-print-settings-links">
				<a href="<?php echo esc_url( drop_print_network_base_url( 'main' ) . '/support' ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Support', 'drop-print' ); ?></a>
				<a href="<?php echo esc_url( drop_print_network_base_url( 'main' ) . '/docs' ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Documentation', 'drop-print' ); ?></a>
				<a href="<?php echo esc_url( drop_print_network_base_url( 'main' ) ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Drop Print', 'drop-print' ); ?></a>
				<a href="<?php echo esc_url( drop_print_network_base_url( 'account' ) . '/my-account/' ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Your account', 'drop-print' ); ?></a>
			</p>
			<p class="drop-print-settings-version">
				<?php
				printf(
					esc_html__( 'Drop Print %s', 'drop-print' ),
					esc_html( defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '' )
				);
				?>
			</p>
			<p class="description drop-print-technical-info">
				<?php
				printf(
					wp_kses_post( __( 'Technical note: Drop Print uses a global "%s" product attribute to build variations. Deactivating the plugin does not remove it; delete it manually if you fully retire Drop Print.', 'drop-print' ) ),
					esc_html__( 'Print Dimensions', 'drop-print' )
				);
				?>
			</p>
		</div>
	</div>
	<?php
}
