<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! function_exists( 'drop_print_get_deactivation_dependency_snapshot' ) ) {
	function drop_print_get_deactivation_dependency_snapshot() {
		$product_ids   = array();
		$product_names = array();
		if ( class_exists( 'WooCommerce' ) || post_type_exists( 'product' ) ) {
			$product_posts = get_posts(
				array(
					'post_type'              => 'product',
					'post_status'            => array( 'publish', 'draft', 'pending', 'private', 'future' ),
					'posts_per_page'         => -1,
					'fields'                 => 'ids',
					'no_found_rows'          => true,
					'update_post_meta_cache' => false,
					'update_post_term_cache' => false,
					'meta_key'               => '_drop_print_meta',
				)
			);
			if ( ! empty( $product_posts ) ) {
				foreach ( $product_posts as $product_id ) {
					$product_id = absint( $product_id );
					if ( ! $product_id ) {
						continue;
					}
					$meta = get_post_meta( $product_id, '_drop_print_meta', true );
					if ( ! is_array( $meta ) || ! isset( $meta['active'] ) || 'yes' !== $meta['active'] ) {
						continue;
					}
					$product_ids[] = $product_id;
					$title = get_the_title( $product_id );
					if ( '' === trim( (string) $title ) ) {
						$title = sprintf( __( 'Product #%d', 'drop-print' ), $product_id );
					}
					$product_names[] = wp_strip_all_tags( $title );
				}
			}
		}
		$tracked_files = function_exists( 'drop_print_files_get_index' )
			? drop_print_files_get_index()['files']
			: (array) get_option( 'drop_print_files', array() );
		$file_names = array_keys( $tracked_files );
		natcasesort( $file_names );
		$file_names = array_values( $file_names );
		$sanitised_file_names = array();
		foreach ( $file_names as $file_name ) {
			$file_name = sanitize_file_name( (string) $file_name );
			if ( '' !== $file_name ) {
				$sanitised_file_names[] = $file_name;
			}
		}
		$settings = drop_print_get_user_settings( get_current_user_id() );
		return array(
			'product_ids'   => $product_ids,
			'product_names' => $product_names,
			'file_names'    => $sanitised_file_names,
			'settings'      => array(
				'client_user_connection_id' => $settings['client_user_connection_id'] ?? null,
				'user_display_name'         => $settings['user_display_name'] ?? null,
				'billing_currency'          => $settings['billing_currency'] ?? null,
				'pro_status'                => isset( $settings['pro_status'] ) ? (int) $settings['pro_status'] : 0,
				'encryption'                => ! empty( $settings['encryption'] ),
				'auto_production'           => $settings['auto_production'] ?? null,
				'payment_frequency'         => $settings['payment_frequency'] ?? null,
				'default_shipping_method'   => $settings['default_shipping_method'] ?? null,
				'price_margin'              => $settings['price_margin'] ?? null,
			),
		);
	}
}
if ( ! function_exists( 'drop_print_get_deactivation_summary_data' ) ) {
	function drop_print_get_deactivation_summary_data() {
		$snapshot = drop_print_get_deactivation_dependency_snapshot();
		return array(
			'product_count' => count( $snapshot['product_ids'] ),
			'product_names' => array_slice( $snapshot['product_names'], 0, 3 ),
			'file_count'    => count( $snapshot['file_names'] ),
			'file_names'    => array_slice( $snapshot['file_names'], 0, 3 ),
		);
	}
}
if ( ! function_exists( 'drop_print_client_enqueue_plugin_deactivation_guard' ) ) {
	function drop_print_client_enqueue_plugin_deactivation_guard( $hook_suffix ) {
		if ( 'plugins.php' !== $hook_suffix && 'plugins-network.php' !== $hook_suffix ) {
			return;
		}
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}
		$asset_path    = DROP_PRINT_PLUGIN_PATH . 'assets/js/admin/drop-print-plugin-deactivation.js';
		$asset_version = file_exists( $asset_path ) ? (string) filemtime( $asset_path ) : ( defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3' );
		$version       = defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3';
		$support_subject = sprintf(
			__( 'Considering deactivating Drop Print V%s', 'drop-print' ),
			$version
		);
		wp_enqueue_script(
			'drop-print-plugin-deactivation',
			DROP_PRINT_PLUGIN_URL . 'assets/js/admin/drop-print-plugin-deactivation.js',
			array( 'jquery' ),
			$asset_version,
			true
		);
		wp_localize_script(
			'drop-print-plugin-deactivation',
			'dropPrintDeactivationGuard',
			array(
				'ajaxUrl'      => admin_url( 'admin-ajax.php' ),
				'nonce'        => wp_create_nonce( 'drop_print_deactivation_summary' ),
				'pluginFile'   => plugin_basename( DROP_PRINT_PLUGIN_FILE ),
				'pluginName'   => __( 'Drop Print', 'drop-print' ),
				'version'      => $version,
				'supportEmail' => 'callum@aldenfineprint.com',
				'supportLink'  => 'mailto:callum@aldenfineprint.com?subject=' . rawurlencode( $support_subject ),
				'reasons'      => array(
					array(
						'value' => 'bug',
						'label' => __( 'I found a bug', 'drop-print' ),
					),
					array(
						'value' => 'troubleshooting',
						'label' => __( 'I am troubleshooting', 'drop-print' ),
					),
					array(
						'value' => 'no_longer_needed',
						'label' => __( 'I no longer need Drop Print', 'drop-print' ),
					),
					array(
						'value' => 'switching_solution',
						'label' => __( 'I am switching to another solution', 'drop-print' ),
					),
					array(
						'value' => 'performance',
						'label' => __( 'Performance concerns', 'drop-print' ),
					),
					array(
						'value' => 'other',
						'label' => __( 'Other', 'drop-print' ),
					),
				),
				'labels'       => array(
					'title'                 => __( 'Deactivate Drop Print?', 'drop-print' ),
					'continue'              => __( 'Deactivate Anyway', 'drop-print' ),
					'cancel'                => __( 'Cancel', 'drop-print' ),
					'back'                  => __( 'Back', 'drop-print' ),
					'deactivatePlugin'      => __( 'Deactivate Plugin', 'drop-print' ),
					'warningIntro'          => __( 'This site still contains Drop Print products and/or .drop container files that rely on this plugin.', 'drop-print' ),
					'noDependenciesTitle'   => __( 'No active Drop Print dependencies were found.', 'drop-print' ),
					'noDependenciesMessage' => __( 'This installation does not currently appear to have active Drop Print products or tracked .drop container files. Deactivation should be safe, but you may still wish to keep a copy of your uploads directory before proceeding.', 'drop-print' ),
					'productsCounted'       => __( 'product', 'drop-print' ),
					'productsCountedPlural'  => __( 'products', 'drop-print' ),
					'filesCounted'          => __( 'print file', 'drop-print' ),
					'filesCountedPlural'    => __( 'print files', 'drop-print' ),
					'affectedSuffix'        => __( 'will be affected:', 'drop-print' ),
					'orphanedSuffix'        => __( 'will be orphaned:', 'drop-print' ),
					'supportLead'           => __( 'Experiencing a problem?', 'drop-print' ),
					'supportAdvice'         => __( 'Before deactivating Drop Print, our support team may be able to help.', 'drop-print' ),
					'cleanupAdvice'         => __( 'If you are permanently retiring Drop Print, you may wish to remove the uploads/drop-print directory from your server after confirming that anything you wish to keep has been backed up.', 'drop-print' ),
					'andMore'               => __( 'and %d more', 'drop-print' ),
					'surveyLead'            => __( 'Why are you deactivating?', 'drop-print' ),
					'surveyPrompt'          => __( 'Please choose the main reason. This helps us improve Drop Print.', 'drop-print' ),
					'surveyNote'            => __( 'You can cancel at any time and keep the plugin active.', 'drop-print' ),
					'deactivationSent'      => __( 'Thanks. Your feedback has been recorded.', 'drop-print' ),
					'cancelledSent'         => __( 'Cancellation noted.', 'drop-print' ),
					'productFallback'       => __( 'Product #%d', 'drop-print' ),
				),
			)
		);
	}
}
add_action( 'admin_enqueue_scripts', 'drop_print_client_enqueue_plugin_deactivation_guard' );
if ( ! function_exists( 'drop_print_get_deactivation_event_payload' ) ) {
	function drop_print_get_deactivation_event_payload( array $request_payload = array() ) {
		$snapshot = drop_print_get_deactivation_dependency_snapshot();
		$settings = $snapshot['settings'];
		global $wp_version;
		$woocommerce_version = '';
		if ( function_exists( 'WC' ) && WC() && isset( WC()->version ) ) {
			$woocommerce_version = (string) WC()->version;
		} elseif ( defined( 'WC_VERSION' ) ) {
			$woocommerce_version = (string) WC_VERSION;
		}
		$plugin_version = defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3';
		$result         = isset( $request_payload['result'] ) ? sanitize_key( (string) $request_payload['result'] ) : '';
		if ( ! in_array( $result, array( 'deactivated', 'cancelled' ), true ) ) {
			$result = 'deactivated';
		}
		$stage = isset( $request_payload['stage'] ) ? sanitize_key( (string) $request_payload['stage'] ) : 'warning';
		if ( ! in_array( $stage, array( 'warning', 'survey' ), true ) ) {
			$stage = 'warning';
		}
		return array(
			'event'                    => 'plugin_deactivation',
			'result'                   => $result,
			'stage'                    => $stage,
			'reason'                   => isset( $request_payload['reason'] ) ? sanitize_key( (string) $request_payload['reason'] ) : '',
			'reason_label'             => isset( $request_payload['reason_label'] ) ? sanitize_text_field( (string) $request_payload['reason_label'] ) : '',
			'cancel_source'            => isset( $request_payload['cancel_source'] ) ? sanitize_key( (string) $request_payload['cancel_source'] ) : '',
			'plugin_version'           => $plugin_version,
			'wordpress_version'        => (string) $wp_version,
			'woocommerce_version'      => $woocommerce_version,
			'php_version'              => phpversion(),
			'client_user_connection_id' => $settings['client_user_connection_id'] ?? null,
			'user_display_name'        => $settings['user_display_name'] ?? null,
			'billing_currency'         => $settings['billing_currency'] ?? null,
			'pro_status'               => isset( $settings['pro_status'] ) ? (int) $settings['pro_status'] : 0,
			'encryption'               => ! empty( $settings['encryption'] ),
			'auto_production'          => $settings['auto_production'] ?? null,
			'payment_frequency'        => $settings['payment_frequency'] ?? null,
			'default_shipping_method'  => $settings['default_shipping_method'] ?? null,
			'price_margin'             => $settings['price_margin'] ?? null,
			'product_count'            => count( $snapshot['product_ids'] ),
			'file_count'               => count( $snapshot['file_names'] ),
			'timestamp_client'         => gmdate( 'c' ),
			'payload_source'           => 'wordpress',
			'user_agent'               => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
		);
	}
}
if ( ! function_exists( 'drop_print_send_deactivation_event_to_api' ) ) {
	function drop_print_send_deactivation_event_to_api( array $payload ) {
		if ( ! function_exists( 'drop_print_get_client_server_auth_details_for_ajax' ) ) {
			return array(
				'sent'  => false,
				'error' => 'Authentication helper unavailable.',
			);
		}
		$auth_details = drop_print_get_client_server_auth_details_for_ajax();
		if ( is_wp_error( $auth_details ) ) {
			error_log( '[DropPrint Client] Deactivation telemetry not sent: ' . $auth_details->get_error_message() );
			return array(
				'sent'   => false,
				'queued' => false,
				'error'  => $auth_details->get_error_message(),
			);
		}
		$api_url      = trailingslashit( $auth_details['base_url'] ) . 'client-event';
		$api_username = $auth_details['username'];
		$api_password = $auth_details['password'];
		$version      = defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3';
		$response = wp_remote_post(
			$api_url,
			array(
				'method'      => 'POST',
				'timeout'     => 2,
				'blocking'    => false,
				'redirection' => 0,
				'headers'     => array(
					'Authorization' => 'Basic ' . base64_encode( $api_username . ':' . $api_password ),
					'Content-Type'   => 'application/json; charset=utf-8',
					'Accept'         => 'application/json',
					'User-Agent'     => 'DropPrintClientDeactivation/' . $version,
				),
				'body'        => wp_json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ),
			)
		);
		if ( is_wp_error( $response ) ) {
			error_log( '[DropPrint Client] Deactivation telemetry request error: ' . $response->get_error_message() );
			return array(
				'sent'   => false,
				'queued' => true,
				'error'  => $response->get_error_message(),
			);
		}
		return array(
			'sent'     => true,
			'queued'   => true,
			'endpoint' => $api_url,
		);
	}
}
if ( ! function_exists( 'drop_print_ajax_record_deactivation_event' ) ) {
	function drop_print_ajax_record_deactivation_event() {
		check_ajax_referer( 'drop_print_deactivation_summary', 'nonce' );
		if ( ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Permission denied.', 'drop-print' ),
				),
				403
			);
		}
		$request_payload = array(
			'result'        => isset( $_POST['result'] ) ? sanitize_key( wp_unslash( $_POST['result'] ) ) : '',
			'stage'         => isset( $_POST['stage'] ) ? sanitize_key( wp_unslash( $_POST['stage'] ) ) : 'warning',
			'reason'        => isset( $_POST['reason'] ) ? sanitize_key( wp_unslash( $_POST['reason'] ) ) : '',
			'reason_label'  => isset( $_POST['reason_label'] ) ? sanitize_text_field( wp_unslash( $_POST['reason_label'] ) ) : '',
			'cancel_source' => isset( $_POST['cancel_source'] ) ? sanitize_key( wp_unslash( $_POST['cancel_source'] ) ) : '',
		);
		$payload     = drop_print_get_deactivation_event_payload( $request_payload );
		$send_result = drop_print_send_deactivation_event_to_api( $payload );
		update_user_meta(
			get_current_user_id(),
			'_drop_print_client_event',
			wp_json_encode( $payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE )
		);
		wp_send_json_success(
			array(
				'queued'  => true,
				'sent'    => ! empty( $send_result['sent'] ),
				'result'  => $payload['result'],
				'stage'   => $payload['stage'],
				'message' => 'cancelled' === $payload['result'] ? __( 'Cancellation recorded.', 'drop-print' ) : __( 'Deactivation recorded.', 'drop-print' ),
			)
		);
	}
}
add_action( 'wp_ajax_drop_print_record_deactivation_event', 'drop_print_ajax_record_deactivation_event' );
if ( ! function_exists( 'drop_print_ajax_get_deactivation_summary' ) ) {
	function drop_print_ajax_get_deactivation_summary() {
		check_ajax_referer( 'drop_print_deactivation_summary', 'nonce' );
		if ( ! current_user_can( 'activate_plugins' ) ) {
			wp_send_json_error(
				array(
					'message' => __( 'Permission denied.', 'drop-print' ),
				),
				403
			);
		}
		wp_send_json_success( drop_print_get_deactivation_summary_data() );
	}
}
add_action( 'wp_ajax_drop_print_get_deactivation_summary', 'drop_print_ajax_get_deactivation_summary' );
