<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
if ( ! function_exists( 'drop_print_use_headless_connect' ) ) {
	function drop_print_use_headless_connect(): bool {
		return (bool) apply_filters( 'drop_print_use_headless_connect', false );
	}
}
if ( ! function_exists( 'drop_print_headless_api_base' ) ) {
	function drop_print_headless_api_base(): string {
		return defined( 'DROP_PRINT_API_URI' ) ? untrailingslashit( DROP_PRINT_API_URI ) : '';
	}
}
if ( ! function_exists( 'drop_print_headless_request' ) ) {
	function drop_print_headless_request( string $path, string $method = 'GET', array $body = array() ) {
		$base = drop_print_headless_api_base();
		if ( '' === $base ) {
			return new WP_Error( 'drop_print_headless_no_api', __( 'Drop Print API is not configured on this site.', 'drop-print' ) );
		}
		$args = array(
			'method'  => $method,
			'timeout' => 20,
			'headers' => array( 'Accept' => 'application/json' ),
		);
		if ( 'GET' !== $method ) {
			$args['headers']['Content-Type'] = 'application/json; charset=utf-8';
			$args['body']                     = wp_json_encode( $body );
		}
		$response = 'GET' === $method
			? wp_remote_get( $base . $path, $args )
			: wp_remote_post( $base . $path, $args );
		if ( is_wp_error( $response ) ) {
			return $response;
		}
		$status = wp_remote_retrieve_response_code( $response );
		$raw    = wp_remote_retrieve_body( $response );
		$decoded = json_decode( $raw, true );
		return array(
			'status'  => $status,
			'body'    => is_array( $decoded ) ? $decoded : null,
			'code'    => ( $status >= 200 && $status < 300 ) ? '' : ( is_array( $decoded ) && isset( $decoded['code'] ) ? (string) $decoded['code'] : 'drop_print_headless_http_' . $status ),
			'message' => is_array( $decoded ) && isset( $decoded['message'] ) ? (string) $decoded['message'] : '',
		);
	}
}
if ( ! function_exists( 'drop_print_headless_fetch_terms' ) ) {
	function drop_print_headless_fetch_terms() {
		$result = drop_print_headless_request( '/client/terms', 'GET' );
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		if ( '' !== $result['code'] || empty( $result['body']['html'] ) ) {
			return new WP_Error( 'drop_print_headless_no_terms', __( 'Could not load the terms and conditions. Please try again shortly.', 'drop-print' ) );
		}
		return array(
			'version' => (string) ( $result['body']['version'] ?? '' ),
			'html'    => (string) $result['body']['html'],
		);
	}
}
if ( ! function_exists( 'drop_print_headless_register' ) ) {
	function drop_print_headless_register( string $email, string $billing_currency, string $terms_version, int $client_uid ) {
		$result = drop_print_headless_request(
			'/client/register',
			'POST',
			array(
				'email'            => $email,
				'billing_currency' => $billing_currency,
				'shop_url'         => admin_url(),
				'terms_version'    => $terms_version,
				'terms_accepted'   => true,
				'client_uid'       => $client_uid,
				'plugin_version'   => defined( 'DROP_PRINT_VERSION' ) ? DROP_PRINT_VERSION : '',
			)
		);
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		if ( '' !== $result['code'] ) {
			return new WP_Error(
				$result['code'],
				'' !== $result['message'] ? $result['message'] : __( 'Registration failed. Please try again.', 'drop-print' )
			);
		}
		return $result['body'];
	}
}
if ( ! function_exists( 'drop_print_headless_pair_request' ) ) {
	function drop_print_headless_pair_request( string $email ): bool {
		$result = drop_print_headless_request(
			'/client/pair-request',
			'POST',
			array( 'email' => $email, 'shop_url' => admin_url() )
		);
		return ! is_wp_error( $result );
	}
}
if ( ! function_exists( 'drop_print_headless_pair_confirm' ) ) {
	function drop_print_headless_pair_confirm( string $email, string $code, int $client_uid ) {
		$result = drop_print_headless_request(
			'/client/pair-confirm',
			'POST',
			array( 'email' => $email, 'code' => $code, 'shop_url' => admin_url(), 'client_uid' => $client_uid )
		);
		if ( is_wp_error( $result ) ) {
			return $result;
		}
		if ( '' !== $result['code'] ) {
			return new WP_Error(
				$result['code'],
				'' !== $result['message'] ? $result['message'] : __( 'That code is incorrect or has expired. Request a new one.', 'drop-print' )
			);
		}
		return $result['body'];
	}
}
if ( ! function_exists( 'drop_print_store_connection_payload' ) ) {
	function drop_print_store_connection_payload( int $client_uid, array $api_payload ) {
		if ( $client_uid <= 0 ) {
			return new WP_Error( 'drop_print_headless_bad_uid', __( 'Missing local user context.', 'drop-print' ) );
		}
		$current_user_settings = drop_print_get_user_settings( $client_uid );
		$new_connection_data = array();
		$new_connection_data['client_user_connection_id'] = sanitize_text_field( (string) ( $api_payload['client_id'] ?? '' ) );
		$new_connection_data['public_key_pem_b64']         = sanitize_textarea_field( (string) ( $api_payload['public_pem_b64'] ?? '' ) );
		$new_connection_data['billing_currency']           = sanitize_text_field( strtoupper( (string) ( $api_payload['billing_currency'] ?? '' ) ) );
		$new_connection_data['pro_status']                 = absint( $api_payload['pro_status'] ?? 0 );
		$raw_media = $api_payload['available_media'] ?? array();
		$sanitized_media = array();
		if ( is_array( $raw_media ) ) {
			foreach ( $raw_media as $item ) {
				if ( is_array( $item ) && isset( $item['id'], $item['name'] ) && is_string( $item['id'] ) && is_string( $item['name'] ) ) {
					$sanitized_media[] = array( 'id' => sanitize_key( $item['id'] ), 'name' => sanitize_text_field( $item['name'] ) );
				}
			}
		}
		$new_connection_data['available_media']   = $sanitized_media;
		$new_connection_data['media_last_updated'] = time();
		$new_connection_data['user_display_name']  = sanitize_email( (string) ( $api_payload['username_display'] ?? '' ) );
		if ( ! empty( $api_payload['auth_username_b64'] ) && ! empty( $api_payload['auth_password_b64'] ) ) {
			$new_connection_data['auth_username_b64'] = sanitize_text_field( (string) $api_payload['auth_username_b64'] );
			$new_connection_data['auth_password_b64'] = sanitize_text_field( (string) $api_payload['auth_password_b64'] );
		}
		if ( empty( $new_connection_data['client_user_connection_id'] ) || empty( $new_connection_data['public_key_pem_b64'] ) || empty( $new_connection_data['billing_currency'] ) ) {
			return new WP_Error( 'drop_print_headless_incomplete_payload', __( 'Connection failed: incomplete data received from the server.', 'drop-print' ) );
		}
		if ( empty( $current_user_settings['auth_username_b64'] ) && empty( $new_connection_data['auth_username_b64'] ) ) {
			return new WP_Error( 'drop_print_headless_incomplete_payload', __( 'Connection failed: incomplete data received from the server.', 'drop-print' ) );
		}
		$updated_user_settings = array_merge( $current_user_settings, $new_connection_data );
		update_user_meta( $client_uid, 'drop_print_user_settings', $updated_user_settings );
		$stored = get_user_meta( $client_uid, 'drop_print_user_settings', true );
		if ( ! is_array( $stored ) || empty( $stored['client_user_connection_id'] ) ) {
			return new WP_Error( 'drop_print_headless_store_failed', __( 'Connection failed: could not save connection details.', 'drop-print' ) );
		}
		delete_transient( 'drop_print_connect_token_' . $client_uid );
		set_transient( 'drop_print_just_connected_' . $client_uid, 1, 5 * MINUTE_IN_SECONDS );
		delete_option( 'drop_print_outbound_401_seen' );
		do_action( 'drop_print_connected', $client_uid );
		if ( function_exists( 'drop_print_client_refresh_data_and_status' ) && ! wp_next_scheduled( 'drop_print_initial_user_data_sync_hook', array( 'user_id' => $client_uid ) ) ) {
			wp_schedule_single_event( time() + 20, 'drop_print_initial_user_data_sync_hook', array( 'user_id' => $client_uid ) );
		}
		return true;
	}
}
if ( ! function_exists( 'drop_print_handle_reconnect_on_settings_page' ) ) {
	function drop_print_handle_reconnect_on_settings_page() {
		if ( ! drop_print_use_headless_connect() ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$user_id = get_current_user_id();
		if ( isset( $_POST['drop_print_reconnect_request'] ) && check_admin_referer( 'drop_print_reconnect_action' ) ) {
			$email = isset( $_POST['dp_reconnect_email'] ) ? sanitize_email( wp_unslash( $_POST['dp_reconnect_email'] ) ) : '';
			if ( '' !== $email && is_email( $email ) ) {
				drop_print_headless_pair_request( $email ); 
			}
			wp_safe_redirect( add_query_arg( array( 'page' => 'drop-print-settings', 'drop_print_reconnect' => 'code_sent', 'dp_email' => rawurlencode( $email ) ), admin_url( 'admin.php' ) ) );
			exit;
		}
		if ( isset( $_POST['drop_print_reconnect_confirm'] ) && check_admin_referer( 'drop_print_reconnect_action' ) ) {
			$email = isset( $_POST['dp_reconnect_email'] ) ? sanitize_email( wp_unslash( $_POST['dp_reconnect_email'] ) ) : '';
			$code  = isset( $_POST['dp_reconnect_code'] ) ? sanitize_text_field( wp_unslash( $_POST['dp_reconnect_code'] ) ) : '';
			$result = drop_print_headless_pair_confirm( $email, $code, $user_id );
			if ( is_wp_error( $result ) ) {
				wp_safe_redirect( add_query_arg( array( 'page' => 'drop-print-settings', 'drop_print_reconnect' => 'error', 'dp_email' => rawurlencode( $email ), 'dp_reconnect_error' => rawurlencode( $result->get_error_message() ) ), admin_url( 'admin.php' ) ) );
				exit;
			}
			$stored = drop_print_store_connection_payload( $user_id, $result );
			if ( is_wp_error( $stored ) ) {
				wp_safe_redirect( add_query_arg( array( 'page' => 'drop-print-settings', 'drop_print_reconnect' => 'error', 'dp_reconnect_error' => rawurlencode( $stored->get_error_message() ) ), admin_url( 'admin.php' ) ) );
				exit;
			}
			wp_safe_redirect( add_query_arg( array( 'page' => 'drop-print-settings', 'drop_print_reconnect' => 'success' ), admin_url( 'admin.php' ) ) );
			exit;
		}
	}
}
add_action( 'admin_init', 'drop_print_handle_reconnect_on_settings_page' );
if ( ! function_exists( 'drop_print_render_reconnect_widget' ) ) {
	function drop_print_render_reconnect_widget() {
		$state         = isset( $_GET['drop_print_reconnect'] ) ? sanitize_key( wp_unslash( $_GET['drop_print_reconnect'] ) ) : '';
		$prefill_email = isset( $_GET['dp_email'] ) ? sanitize_email( rawurldecode( wp_unslash( $_GET['dp_email'] ) ) ) : '';
		$error         = isset( $_GET['dp_reconnect_error'] ) ? sanitize_text_field( rawurldecode( wp_unslash( $_GET['dp_reconnect_error'] ) ) ) : '';
		?>
		<div class="drop-print-reconnect-widget">
			<?php if ( 'success' === $state ) : ?>
				<p><strong><?php esc_html_e( 'Reconnected.', 'drop-print' ); ?></strong></p>
			<?php else : ?>
				<?php if ( '' !== $error ) : ?>
					<p style="color:#c0392b;"><?php echo esc_html( $error ); ?></p>
				<?php endif; ?>
				<?php if ( 'code_sent' === $state ) : ?>
					<p class="description"><?php esc_html_e( 'If an account exists for that email, a code has been sent. Enter it below - your Drop Print password is never needed here.', 'drop-print' ); ?></p>
					<form method="POST" action="" style="margin:0;display:flex;gap:8px;align-items:center;">
						<?php wp_nonce_field( 'drop_print_reconnect_action' ); ?>
						<input type="hidden" name="dp_reconnect_email" value="<?php echo esc_attr( $prefill_email ); ?>" />
						<input type="text" name="dp_reconnect_code" placeholder="<?php esc_attr_e( 'Code from your email', 'drop-print' ); ?>" maxlength="8" style="text-transform:uppercase;letter-spacing:2px;" required />
						<button type="submit" name="drop_print_reconnect_confirm" class="button button-secondary"><?php esc_html_e( 'Confirm', 'drop-print' ); ?></button>
					</form>
				<?php else : ?>
					<form method="POST" action="" style="margin:0;display:flex;gap:8px;align-items:center;">
						<?php wp_nonce_field( 'drop_print_reconnect_action' ); ?>
						<input type="email" name="dp_reconnect_email" placeholder="<?php esc_attr_e( 'Your Drop Print account email', 'drop-print' ); ?>" value="<?php echo esc_attr( $prefill_email ); ?>" required />
						<button type="submit" name="drop_print_reconnect_request" class="button button-secondary"><?php esc_html_e( 'Email me a reconnect code', 'drop-print' ); ?></button>
					</form>
				<?php endif; ?>
			<?php endif; ?>
		</div>
		<?php
	}
}
if ( ! function_exists( 'drop_print_render_outbound_401_notice' ) ) {
	function drop_print_render_outbound_401_notice() {
		if ( ! drop_print_use_headless_connect() ) {
			return;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		if ( ! get_option( 'drop_print_outbound_401_seen', false ) ) {
			return;
		}
		$settings = drop_print_get_user_settings( get_current_user_id() );
		if ( empty( $settings['client_user_connection_id'] ) ) {
			return; 
		}
		$settings_url = admin_url( 'admin.php?page=drop-print-settings' );
		?>
		<div class="notice notice-error is-dismissible">
			<p>
				<?php
				printf(
					wp_kses_post(
						__( 'Drop Print could not authenticate with the server. Your connection may have expired — <a href="%s">reconnect your account</a>.', 'drop-print' )
					),
					esc_url( $settings_url )
				);
				?>
			</p>
		</div>
		<?php
	}
}
add_action( 'admin_notices', 'drop_print_render_outbound_401_notice' );
