<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! function_exists( 'drop_print_user_can_use_pro_upgrade_workflow' ) ) {
	function drop_print_user_can_use_pro_upgrade_workflow(): bool {
		return current_user_can( 'manage_options' ) || current_user_can( 'edit_shop_orders' );
	}
}
if ( ! function_exists( 'drop_print_get_pro_upgrade_client_config' ) ) {
	function drop_print_get_pro_upgrade_client_config( string $surface_label = 'Quote & Pay', string $origin_surface = 'quote_modal' ): array {
		return 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',
			'refresh_data_action' => 'drop_print_refresh_client_account_data',
			'intent_action' => 'drop_print_request_pro_subscription_intent',
			'confirm_action' => 'drop_print_confirm_pro_subscription',
			'surface_label' => $surface_label,
			'origin_surface' => $origin_surface,
			'site_label' => get_bloginfo( 'name' ),
			'poll_interval_ms' => 5000,
			'poll_schedule_ms' => array( 3000, 3000, 5000, 5000, 10000 ),
			'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' ),
				'redirecting' => __( 'Taking you to secure checkout…', 'drop-print' ),
				'confirming' => __( 'Confirming your Pro upgrade…', 'drop-print' ),
				'polling' => __( 'Checking your account state…', 'drop-print' ),
				'success' => __( 'Pro upgrade complete.', 'drop-print' ),
				'welcome' => __( 'Welcome to Drop Print Pro!', 'drop-print' ),
				'welcome_body' => __( 'Your account has been upgraded. Pro pricing and premium shipping are now active. Auto send-to-production is now available - turn it on any time in Drop Print → Settings.', 'drop-print' ),
				'continue' => __( 'Continue', 'drop-print' ),
				'continue_order_sprintf' => __( 'Continue with order #%order_id%', 'drop-print' ),
				'close' => __( 'Close', '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' ),
				'confirm_pending' => __( 'Payment is still being confirmed. Your account will unlock automatically once it settles.', 'drop-print' ),
				'returning_sprintf' => __( 'Returning to %site_label%…', 'drop-print' ),
				'checking_subscription' => __( 'Checking subscription…', 'drop-print' ),
				'unlock_pricing' => __( 'Discount Pricing on Every Order', 'drop-print' ),
				'unlock_shipping' => __( 'Access to Shipping Upgrade Option', 'drop-print' ),
				'unlock_auto_production' => __( 'Auto Send-to-Production Option', 'drop-print' ),
				'unlock_paper_stocks' => __( 'Access to more Paper Stocks', 'drop-print' ),
				'unlock_priority_support' => __( 'Expedited Support Tickets', 'drop-print' ),
				'refreshing_sprintf' => __( 'Refreshing %surface_label%…', 'drop-print' ),
				'settings_pro_activated' => __( 'Congratulations! Your Drop Print Pro account has been activated.', 'drop-print' ),
				'settings_shipping_description_pro' => __( 'Select your preferred default shipping method for new products. You can also change this per order during "Quote & Pay".', 'drop-print' ),
				'settings_auto_production_description_pro' => __( 'Automatically send orders to print upon customer payment. Requires a valid payment card on file at Drop Print.', 'drop-print' ),
				'pay_button' => __( 'Start Drop Print Pro', 'drop-print' ),
				'pay_button_trial' => __( 'Start Free Trial', 'drop-print' ),
				'card_details_label' => __( 'Card details', 'drop-print' ),
				'preparing_payment' => __( 'Preparing payment…', 'drop-print' ),
				'confirming_payment' => __( 'Confirming payment…', 'drop-print' ),
				'activating_subscription' => __( 'Activating your Pro subscription…', 'drop-print' ),
				'payment_error_generic' => __( 'Payment could not be completed. Please try again.', 'drop-print' ),
			),
		);
	}
}
if ( ! function_exists( 'drop_print_normalize_pro_upgrade_api_response' ) ) {
	function drop_print_normalize_pro_upgrade_api_response( $response ) {
		if ( is_array( $response ) && isset( $response['success'] ) && array_key_exists( 'data', $response ) ) {
			return $response['data'];
		}
		return is_array( $response ) ? $response : array();
	}
}
if ( ! function_exists( 'drop_print_extract_pro_upgrade_account_state' ) ) {
	function drop_print_extract_pro_upgrade_account_state( array $response ): array {
		$state = array();
		if ( isset( $response['account_state'] ) && is_array( $response['account_state'] ) ) {
			$state = $response['account_state'];
		} elseif ( isset( $response['data'] ) && is_array( $response['data'] ) && isset( $response['data']['account_state'] ) && is_array( $response['data']['account_state'] ) ) {
			$state = $response['data']['account_state'];
		} elseif ( isset( $response['data'] ) && is_array( $response['data'] ) ) {
			$state = $response['data'];
		} else {
			$state = $response;
		}
		return $state;
	}
}
if ( ! function_exists( 'drop_print_store_pro_upgrade_account_state_snapshot' ) ) {
	function drop_print_store_pro_upgrade_account_state_snapshot( int $user_id, array $account_state ): void {
		$settings = drop_print_get_user_settings( $user_id );
		if ( isset( $account_state['is_pro'] ) ) {
			$settings['pro_status'] = absint( (bool) $account_state['is_pro'] );
		}
		$settings['pro_account_state_snapshot'] = $account_state;
		update_user_meta( $user_id, 'drop_print_user_settings', $settings );
	}
}
if ( ! function_exists( 'drop_print_get_client_pro_upgrade_auth_context' ) ) {
	function drop_print_get_client_pro_upgrade_auth_context( int $user_id = 0 ) {
		if ( $user_id <= 0 ) {
			$user_id = get_current_user_id();
		}
		if ( $user_id <= 0 ) {
			return new WP_Error( 'user_not_logged_in', __( 'User not logged in or not identifiable for Pro upgrade workflow.', 'drop-print' ) );
		}
		if ( ! function_exists( 'drop_print_get_client_server_auth_details_for_ajax' ) || ! function_exists( 'drop_print_make_server_request_for_ajax' ) ) {
			return new WP_Error( 'upgrade_helpers_missing', __( 'Required API proxy helpers are not available.', 'drop-print' ) );
		}
		$auth_details = drop_print_get_client_server_auth_details_for_ajax();
		if ( is_wp_error( $auth_details ) ) {
			return $auth_details;
		}
		$settings = drop_print_get_user_settings( $user_id );
		return array(
			'user_id' => $user_id,
			'settings' => $settings,
			'auth' => $auth_details,
			'site_label' => get_bloginfo( 'name' ),
			'site_url' => home_url(),
		);
	}
}
if ( ! function_exists( 'drop_print_request_pro_upgrade_session_ajax_handler' ) ) {
	function drop_print_request_pro_upgrade_session_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_pro_upgrade_workflow_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ), 'code' => 'nonce_failure' ), 403 );
			return;
		}
		if ( ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'drop-print' ), 'code' => 'permission_denied' ), 403 );
			return;
		}
		$context = drop_print_get_client_pro_upgrade_auth_context();
		if ( is_wp_error( $context ) ) {
			wp_send_json_error( array( 'message' => $context->get_error_message(), 'code' => $context->get_error_code() ), 400 );
			return;
		}
		$origin_surface = isset( $_POST['origin_surface'] ) ? sanitize_key( wp_unslash( $_POST['origin_surface'] ) ) : 'quote_modal';
		$client_order_id = isset( $_POST['client_order_id'] ) ? absint( wp_unslash( $_POST['client_order_id'] ) ) : 0;
		$quote_id = isset( $_POST['quote_id'] ) ? sanitize_text_field( wp_unslash( $_POST['quote_id'] ) ) : '';
		$return_url = isset( $_POST['return_url'] ) ? esc_url_raw( wp_unslash( $_POST['return_url'] ) ) : '';
		if ( $return_url !== '' && strpos( $return_url, home_url() ) !== 0 ) {
			$return_url = '';
		}
		$return_state = wp_json_encode(
			array(
				'return_url'      => $return_url,
				'client_order_id' => $client_order_id ?: null,
				'quote_id'        => $quote_id ?: null,
				'origin_surface'  => $origin_surface,
			)
		);
		$payload = array(
			'origin_surface' => $origin_surface,
			'site_label' => $context['site_label'],
			'site_url' => $context['site_url'],
			'client_plugin_version' => defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
			'client_wp_user_id' => $context['user_id'],
			'client_order_id' => $client_order_id ?: null,
			'return_state' => $return_state,
		);
		$api_response = drop_print_make_server_request_for_ajax( 'pro-upgrade-session', $payload, 'POST', 45 );
		if ( is_wp_error( $api_response ) ) {
			$error_data = $api_response->get_error_data();
			$response_status = isset( $error_data['status'] ) ? (int) $error_data['status'] : 400;
			wp_send_json_error(
				array(
					'message' => $api_response->get_error_message(),
					'code'    => $api_response->get_error_code(),
					'details' => $error_data,
				),
				$response_status
			);
			return;
		}
		$normalized = drop_print_normalize_pro_upgrade_api_response( $api_response );
		if ( empty( $normalized ) ) {
			wp_send_json_error( array( 'message' => __( 'The upgrade session could not be created.', 'drop-print' ), 'code' => 'upgrade_session_empty' ), 500 );
			return;
		}
		wp_send_json_success( $normalized );
	}
}
add_action( 'wp_ajax_drop_print_request_pro_upgrade_session', 'drop_print_request_pro_upgrade_session_ajax_handler' );
if ( ! function_exists( 'drop_print_poll_pro_upgrade_account_state_ajax_handler' ) ) {
	function drop_print_poll_pro_upgrade_account_state_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_pro_upgrade_workflow_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ), 'code' => 'nonce_failure' ), 403 );
			return;
		}
		if ( ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'drop-print' ), 'code' => 'permission_denied' ), 403 );
			return;
		}
		$context = drop_print_get_client_pro_upgrade_auth_context();
		if ( is_wp_error( $context ) ) {
			wp_send_json_error( array( 'message' => $context->get_error_message(), 'code' => $context->get_error_code() ), 400 );
			return;
		}
		$upgrade_session_id = isset( $_POST['upgrade_session_id'] ) ? sanitize_text_field( wp_unslash( $_POST['upgrade_session_id'] ) ) : '';
		$payload = array(
			'upgrade_session_id' => $upgrade_session_id,
			'client_wp_user_id'   => $context['user_id'],
			'site_label'          => $context['site_label'],
			'client_plugin_version' => defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '1.1.3',
		);
		$api_response = drop_print_make_server_request_for_ajax( 'account-state', $payload, 'POST', 45 );
		if ( is_wp_error( $api_response ) ) {
			$error_data = $api_response->get_error_data();
			$response_status = isset( $error_data['status'] ) ? (int) $error_data['status'] : 400;
			wp_send_json_error(
				array(
					'message' => $api_response->get_error_message(),
					'code'    => $api_response->get_error_code(),
					'details' => $error_data,
				),
				$response_status
			);
			return;
		}
		$account_state = drop_print_extract_pro_upgrade_account_state( is_array( $api_response ) ? $api_response : array() );
		if ( empty( $account_state ) ) {
			wp_send_json_error( array( 'message' => __( 'Account state could not be retrieved.', 'drop-print' ), 'code' => 'account_state_empty' ), 500 );
			return;
		}
		if ( isset( $account_state['is_pro'] ) ) {
			drop_print_store_pro_upgrade_account_state_snapshot( $context['user_id'], $account_state );
		}
		wp_send_json_success(
			array(
				'account_state' => $account_state,
				'is_pro'        => ! empty( $account_state['is_pro'] ),
				'session_id'    => $upgrade_session_id,
			)
		);
	}
}
add_action( 'wp_ajax_drop_print_poll_pro_upgrade_account_state', 'drop_print_poll_pro_upgrade_account_state_ajax_handler' );
if ( ! function_exists( 'drop_print_refresh_client_account_data_ajax_handler' ) ) {
	function drop_print_refresh_client_account_data_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_pro_upgrade_workflow_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ), 'code' => 'nonce_failure' ), 403 );
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'drop-print' ), 'code' => 'permission_denied' ), 403 );
			return;
		}
		$user_id = get_current_user_id();
		if ( $user_id <= 0 || ! function_exists( 'drop_print_client_refresh_data_and_status' ) ) {
			wp_send_json_error( array( 'message' => __( 'Unable to refresh account data.', 'drop-print' ), 'code' => 'refresh_unavailable' ), 500 );
			return;
		}
		$result   = drop_print_client_refresh_data_and_status( $user_id );
		$settings = drop_print_get_user_settings( $user_id );
		wp_send_json_success(
			array(
				'status'                  => (bool) $result['status'],
				'message'                 => $result['message'] ?? '',
				'is_pro'                  => (bool) ( $settings['pro_status'] ?? 0 ),
				'available_media'         => $settings['available_media'] ?? array(),
				'default_media_id'        => $settings['default_media_id'] ?? '',
				'auto_production'         => $settings['auto_production'] ?? 'off',
				'default_shipping_method' => $settings['default_shipping_method'] ?? 'standard',
				'available_shipping_methods' => $settings['available_shipping_methods'] ?? array(),
			)
		);
	}
}
add_action( 'wp_ajax_drop_print_refresh_client_account_data', 'drop_print_refresh_client_account_data_ajax_handler' );
if ( ! function_exists( 'drop_print_request_pro_subscription_intent_ajax_handler' ) ) {
	function drop_print_request_pro_subscription_intent_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_pro_upgrade_workflow_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ), 'code' => 'nonce_failure' ), 403 );
			return;
		}
		if ( ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'drop-print' ), 'code' => 'permission_denied' ), 403 );
			return;
		}
		if ( ! function_exists( 'drop_print_make_server_request_for_ajax' ) ) {
			wp_send_json_error( array( 'message' => __( 'Required API proxy helpers are not available.', 'drop-print' ), 'code' => 'upgrade_helpers_missing' ), 500 );
			return;
		}
		$api_response = drop_print_make_server_request_for_ajax( 'pro-subscription/intent', array(), 'POST', 45 );
		if ( is_wp_error( $api_response ) ) {
			$error_data      = $api_response->get_error_data();
			$response_status = isset( $error_data['status'] ) ? (int) $error_data['status'] : 400;
			wp_send_json_error( array( 'message' => $api_response->get_error_message(), 'code' => $api_response->get_error_code(), 'details' => $error_data ), $response_status );
			return;
		}
		$normalized = drop_print_normalize_pro_upgrade_api_response( $api_response );
		if ( empty( $normalized ) ) {
			wp_send_json_error( array( 'message' => __( 'Could not start the Pro upgrade payment.', 'drop-print' ), 'code' => 'pro_subscription_intent_empty' ), 500 );
			return;
		}
		wp_send_json_success( $normalized );
	}
}
add_action( 'wp_ajax_drop_print_request_pro_subscription_intent', 'drop_print_request_pro_subscription_intent_ajax_handler' );
if ( ! function_exists( 'drop_print_confirm_pro_subscription_ajax_handler' ) ) {
	function drop_print_confirm_pro_subscription_ajax_handler() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['nonce'] ) ), 'drop_print_pro_upgrade_workflow_action' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed.', 'drop-print' ), 'code' => 'nonce_failure' ), 403 );
			return;
		}
		if ( ! drop_print_user_can_use_pro_upgrade_workflow() ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission.', 'drop-print' ), 'code' => 'permission_denied' ), 403 );
			return;
		}
		if ( ! function_exists( 'drop_print_make_server_request_for_ajax' ) ) {
			wp_send_json_error( array( 'message' => __( 'Required API proxy helpers are not available.', 'drop-print' ), 'code' => 'upgrade_helpers_missing' ), 500 );
			return;
		}
		$intent_id   = isset( $_POST['intent_id'] ) ? sanitize_text_field( wp_unslash( $_POST['intent_id'] ) ) : '';
		$intent_type = isset( $_POST['intent_type'] ) ? sanitize_key( wp_unslash( $_POST['intent_type'] ) ) : 'payment';
		if ( '' === $intent_id ) {
			wp_send_json_error( array( 'message' => __( 'Missing payment confirmation.', 'drop-print' ), 'code' => 'pro_subscription_no_intent' ), 400 );
			return;
		}
		$api_response = drop_print_make_server_request_for_ajax(
			'pro-subscription/confirm',
			array(
				'intent_id'   => $intent_id,
				'intent_type' => $intent_type,
			),
			'POST',
			45
		);
		if ( is_wp_error( $api_response ) ) {
			$error_data      = $api_response->get_error_data();
			$response_status = isset( $error_data['status'] ) ? (int) $error_data['status'] : 400;
			wp_send_json_error( array( 'message' => $api_response->get_error_message(), 'code' => $api_response->get_error_code(), 'details' => $error_data ), $response_status );
			return;
		}
		$normalized    = drop_print_normalize_pro_upgrade_api_response( $api_response );
		$account_state = drop_print_extract_pro_upgrade_account_state( is_array( $normalized ) ? $normalized : array() );
		if ( ! empty( $account_state ) ) {
			drop_print_store_pro_upgrade_account_state_snapshot( get_current_user_id(), $account_state );
		}
		wp_send_json_success( $normalized );
	}
}
add_action( 'wp_ajax_drop_print_confirm_pro_subscription', 'drop_print_confirm_pro_subscription_ajax_handler' );
