<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly
}

if ( ! class_exists( 'SftcyWordformConnectHubspot' ) ) {
	class SftcyWordformConnectHubspot {
		private static $initiated = false;
		public static $output     = [];

		public function __construct() {
			if ( ! self::$initiated ) {
				self::initiate_hooks();
			}
		}

		/**
		 * Init hooks.
		 *
		 * @return void
		 */
		private static function initiate_hooks() {
			add_action( 'wp_ajax_wordform_connect_save_hubspot_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_hubspot_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_hubspot_with_form_fields', [ __CLASS__, 'wordform_connect_create_hubspot_with_form_fields' ] );
			add_action( 'wp_ajax_wordform_connect_verify_hubspot_token', [ __CLASS__, 'wordform_connect_verify_hubspot_token' ] );

			self::$initiated = true;
		}

		/**
		 * Get HubSpot configured information from option table.
		 *
		 * @return array
		 */
		public static function get_hubspot_configured_info() {
			$hubspot_info = get_option( 'wordform_connect_hubspot_info', [] );
			if ( isset( $hubspot_info['privateAppToken'] ) && ! empty( $hubspot_info['privateAppToken'] ) ) {
				return [
					'privateAppToken' => $hubspot_info['privateAppToken'],
				];
			}

			return [];
		}

		/**
		 * Ajax request.
		 * Store HubSpot private app token as option data.
		 *
		 * @return void
		 */
		public static function wordform_connect_save_hubspot_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$private_app_token = isset( $_POST['params']['hubspotPrivateAppToken'] ) ? sanitize_text_field( trim( $_POST['params']['hubspotPrivateAppToken'] ) ) : '';
			self::$output      = [];

			if ( empty( $private_app_token ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'HubSpot private app token missing.';
				self::$output['comment'] = 'HubSpot Private App Token is required.';
			} else {
				$verification_result = self::verify_hubspot_private_app_token( $private_app_token );
				if ( 'success' !== $verification_result['status'] ) {
					echo wp_json_encode( $verification_result, JSON_HEX_APOS );
					wp_die();
				}

				$hubspot_info = [
					'privateAppToken' => $private_app_token,
				];

				if ( update_option( 'wordform_connect_hubspot_info', $hubspot_info ) ) {
					self::$output['status']  = 'success';
					self::$output['reason']  = 'HubSpot token saved as option value.';
					self::$output['comment'] = 'HubSpot configuration saved successfully.';
				} else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'HubSpot configuration did not change.';
					self::$output['comment'] = 'HubSpot configuration saved successfully.';
				}

				self::$output['hubspotConfiguredInfoStatus'] = self::save_configured_hubspot_application( $hubspot_info );
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( 'hubspot' );
			}

			echo wp_json_encode( self::$output, JSON_HEX_APOS );
			wp_die();
		}

		/**
		 * Ajax request.
		 * Verify HubSpot private app token before save.
		 *
		 * @return void
		 */
		public static function wordform_connect_verify_hubspot_token() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$private_app_token = isset( $_POST['params']['hubspotPrivateAppToken'] ) ? sanitize_text_field( trim( $_POST['params']['hubspotPrivateAppToken'] ) ) : '';
			$response          = self::verify_hubspot_private_app_token( $private_app_token );

			echo wp_json_encode( $response, JSON_HEX_APOS );
			wp_die();
		}

		/**
		 * Verify HubSpot private app token.
		 *
		 * @param string $private_app_token
		 * @return array
		 */
		private static function verify_hubspot_private_app_token( $private_app_token = '' ) {
			$private_app_token = sanitize_text_field( trim( (string) $private_app_token ) );

			if ( empty( $private_app_token ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Please enter HubSpot Private App Token first.',
					'hubspot',
					[
					'fixTip' => 'Create a private app token with contact read and write scopes, then paste it here exactly as copied.',
						'logStage' => 'verify_token',
					]
				);
			}

			$response = wp_remote_get(
				'https://api.hubapi.com/crm/v3/properties/contacts/email',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $private_app_token,
						'Accept'        => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'HubSpot token could not be verified right now: ' . $response->get_error_message(),
					'hubspot',
					[
					'fixTip' => 'Check outbound HTTPS access from this site, then verify the token and try again.',
						'logStage' => 'verify_token',
					]
				);
			}

			$status_code = (int) wp_remote_retrieve_response_code( $response );
			$body        = wp_remote_retrieve_body( $response );
			if ( $status_code >= 200 && $status_code < 300 ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'success',
					'HubSpot token verified successfully.',
					'hubspot'
				);
			}

			$remote_error = SftcyWordformConnectBase::extract_connect_remote_error_message( $body );
			$comment      = 'HubSpot token is invalid or does not have the required contact access.';
			if ( ! empty( $remote_error ) ) {
				$comment .= ' ' . $remote_error;
			}

			return SftcyWordformConnectBase::build_connect_feedback_payload(
				'fail',
				$comment,
				'hubspot',
				[
					'fixTip'            => 'Enable contact read and write scopes on the HubSpot private app, then verify the token again.',
					'responseStatusCode'=> $status_code,
					'logStage'          => 'verify_token',
				]
			);
		}

		/**
		 * Save configured HubSpot application into configured applications table.
		 *
		 * @param array $hubspot_info HubSpot configuration.
		 * @return bool
		 */
		public static function save_configured_hubspot_application( $hubspot_info = [] ) {
			if ( ! is_array( $hubspot_info ) || ! isset( $hubspot_info['privateAppToken'] ) ) {
				return false;
			}

			$application_slug = 'hubspot';
			$application_name = 'HubSpot';
			$data             = [
				'application_slug' => $application_slug,
				'application_name' => $application_name,
			];

			global $wpdb;
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
			$query_results = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE application_slug = %s LIMIT 1', array( $table, $application_slug ) ), ARRAY_A );

			$data['configured_info'] = wp_json_encode(
				[
					'reconfigured'    => $query_results ? 'yes' : 'no',
					'payloadFormat'   => 'hubspot-contact',
					'privateAppToken' => $hubspot_info['privateAppToken'],
				]
			);

			if ( $query_results ) {
				$where                     = [ 'id' => $query_results[0]['id'] ];
				$data['configured_status'] = 'active';
				$update_result             = $wpdb->update( $table, $data, $where );
				return false !== $update_result;
			}

			$insert_result = $wpdb->insert( $table, $data );
			return false !== $insert_result;
		}

		/**
		 * Ajax call.
		 * Store HubSpot connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_hubspot_with_form_fields() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			self::$output = [];
			if ( isset( $_POST['params'] ) && array_filter( $_POST['params'] ) ) {
				$wordform_id                 = isset( $_POST['params']['wordFormID'] ) ? sanitize_text_field( $_POST['params']['wordFormID'] ) : '';
				$wordform_name               = isset( $_POST['params']['wordFormName'] ) ? sanitize_text_field( $_POST['params']['wordFormName'] ) : '';
				$configured_application_id   = isset( $_POST['params']['applicationID'] ) ? absint( $_POST['params']['applicationID'] ) : 0;
				$configured_application_name = isset( $_POST['params']['applicationName'] ) ? sanitize_text_field( $_POST['params']['applicationName'] ) : '';

				if ( ! empty( $wordform_id ) && ! empty( $configured_application_id ) ) {
					$form_fields = SftcyWordformBuildForm::wordform_get_field_names( $wordform_id );
					if ( $form_fields && array_filter( $form_fields ) ) {
						$hubspot_info = self::get_hubspot_configured_info();
						if ( isset( $hubspot_info['privateAppToken'] ) && ! empty( $hubspot_info['privateAppToken'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'hubspot-contact',
								'privateAppToken'     => $hubspot_info['privateAppToken'],
								'connectionUpdatedAt' => current_time( 'mysql' ),
							];

							$insertdata = [
								'configured_application_tbl_id' => $configured_application_id,
								'wordform_id'                   => $wordform_id,
								'connection_info'               => wp_json_encode( $connection_info ),
							];

							$db_result = SftcyWordformConnectBase::wordform_save_connected_application_info( $insertdata );
							if ( false !== $db_result ) {
								self::$output['status']              = 'success';
								self::$output['formFields']          = $form_fields;
								self::$output['formName']            = $wordform_name;
								self::$output['reason']              = 'HubSpot connected successfully.';
								self::$output['comment']             = 'HubSpot connected successfully.';
								self::$output['connectedInfoStored'] = $db_result;
							} else {
								self::$output['status']  = 'fail';
								self::$output['reason']  = 'Connection info storing failed.';
								self::$output['comment'] = 'Could not create HubSpot connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'HubSpot configuration missing.';
							self::$output['comment'] = 'HubSpot Private App Token not found. Please save HubSpot configuration first.';
						}
					} else {
						self::$output['status']  = 'fail';
						self::$output['reason']  = 'WordForm form fields are not available.';
						self::$output['comment'] = 'WordForm fields not found for selected form.';
					}
				} else {
					self::$output['status']  = 'fail';
					self::$output['reason']  = 'WordForm ID or configured application ID missing.';
					self::$output['comment'] = 'Required connection fields are missing.';
				}
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Post parameters are missing.';
				self::$output['comment'] = 'Required post parameters are missing.';
			}

			echo wp_json_encode( self::$output, JSON_HEX_AMP );
			wp_die();
		}

		/**
		 * Send form submission data into HubSpot contact object.
		 * Finds contact by email, updates if found, otherwise creates a new contact.
		 *
		 * @param array $forms_data Processed form fields.
		 * @param array $hubspot_info HubSpot configuration.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_hubspot( $forms_data = [], $hubspot_info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'hubspot';

			if ( ! is_array( $forms_data ) || ! array_filter( $forms_data ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Processed submission fields are empty.';
				$send_info['comment'] = 'No WordForm submission fields found for HubSpot.';
				return $send_info;
			}

			$private_app_token = isset( $hubspot_info['privateAppToken'] ) ? sanitize_text_field( (string) $hubspot_info['privateAppToken'] ) : '';
			if ( empty( $private_app_token ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'HubSpot configuration incomplete.';
				$send_info['comment'] = 'HubSpot Private App Token missing.';
				return $send_info;
			}

			$contact_properties = SftcyWordformConnectBase::extract_common_contact_properties_from_submission_fields( $forms_data );
			if ( empty( $contact_properties['email'] ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Email field value not found in this form submission.';
				$send_info['comment'] = 'HubSpot requires at least one valid email field in the connected form.';
				return $send_info;
			}

			$hubspot_properties = [
				'email' => $contact_properties['email'],
			];
			if ( ! empty( $contact_properties['firstName'] ) ) {
				$hubspot_properties['firstname'] = $contact_properties['firstName'];
			}
			if ( ! empty( $contact_properties['lastName'] ) ) {
				$hubspot_properties['lastname'] = $contact_properties['lastName'];
			}
			if ( ! empty( $contact_properties['phone'] ) ) {
				$hubspot_properties['phone'] = $contact_properties['phone'];
			}
			if ( ! empty( $contact_properties['company'] ) ) {
				$hubspot_properties['company'] = $contact_properties['company'];
			}

			$headers = [
				'Content-Type'  => 'application/json; charset=utf-8',
				'Authorization' => 'Bearer ' . $private_app_token,
			];

			$email_lookup_url = 'https://api.hubapi.com/crm/v3/objects/contacts/' . rawurlencode( $contact_properties['email'] ) . '?idProperty=email';
			$lookup_response  = wp_remote_get(
				$email_lookup_url,
				[
					'timeout' => 20,
					'headers' => $headers,
				]
			);

			if ( is_wp_error( $lookup_response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'HubSpot contact lookup failed.';
				$send_info['requestError'] = $lookup_response->get_error_message();
				$send_info['comment']      = 'HubSpot API lookup request could not be completed.';
				return $send_info;
			}

			$lookup_status_code = (int) wp_remote_retrieve_response_code( $lookup_response );
			$lookup_body        = wp_remote_retrieve_body( $lookup_response );
			$lookup_json        = json_decode( $lookup_body, true );
			$request_method     = 'POST';
			$request_url        = 'https://api.hubapi.com/crm/v3/objects/contacts';
			$send_info['operation'] = 'create';

			if ( 200 === $lookup_status_code && is_array( $lookup_json ) && isset( $lookup_json['id'] ) ) {
				$request_method          = 'PATCH';
				$request_url             = 'https://api.hubapi.com/crm/v3/objects/contacts/' . rawurlencode( $lookup_json['id'] );
				$send_info['operation']  = 'update';
				$send_info['contactId']  = sanitize_text_field( (string) $lookup_json['id'] );
			} elseif ( 404 !== $lookup_status_code ) {
				$send_info['status']             = 'fail';
				$send_info['reason']             = 'HubSpot lookup returned unexpected response.';
				$send_info['comment']            = 'HubSpot contact lookup did not return a valid create-or-update state.';
				$send_info['lookupStatusCode']   = $lookup_status_code;
				if ( is_array( $lookup_json ) && isset( $lookup_json['message'] ) ) {
					$send_info['lookupMessage'] = substr( sanitize_textarea_field( (string) $lookup_json['message'] ), 0, 500 );
				}
				return $send_info;
			}

			$response = wp_remote_request(
				$request_url,
				[
					'method'  => $request_method,
					'timeout' => 20,
					'headers' => $headers,
					'body'    => wp_json_encode( [ 'properties' => $hubspot_properties ] ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'HubSpot contact sync failed.';
				$send_info['requestError'] = $response->get_error_message();
				$send_info['comment']      = 'HubSpot API contact request could not be completed.';
				return $send_info;
			}

			$status_code                  = (int) wp_remote_retrieve_response_code( $response );
			$response_body                = wp_remote_retrieve_body( $response );
			$response_json                = json_decode( $response_body, true );
			$send_info['responseStatusCode'] = $status_code;

			if ( $status_code >= 200 && $status_code < 300 ) {
				$send_info['status']  = 'success';
				$send_info['reason']  = 'Form submission data sent to HubSpot.';
				$send_info['comment'] = 'HubSpot contact synced successfully.';
				if ( is_array( $response_json ) && isset( $response_json['id'] ) ) {
					$send_info['contactId'] = sanitize_text_field( (string) $response_json['id'] );
				}
			} else {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'HubSpot response status indicates failure.';
				$send_info['comment'] = 'HubSpot API returned non-success HTTP status.';
				if ( is_array( $response_json ) && isset( $response_json['message'] ) ) {
					$send_info['responseMessage'] = substr( sanitize_textarea_field( (string) $response_json['message'] ), 0, 500 );
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $response_body ), 0, 500 );
				}
			}

			return $send_info;
		}

		/**
		 * Check whether HubSpot configured app status is active.
		 *
		 * @return bool
		 */
		public static function is_hubspot_configured_status_active() {
			global $wpdb;
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_configured_application_tbl;
			$query_results = $wpdb->get_results(
				$wpdb->prepare(
					'SELECT * FROM %i WHERE application_slug = %s AND configured_status = %s LIMIT 1',
					[
						$table,
						'hubspot',
						'active',
					]
				),
				ARRAY_A
			);

			return ! empty( $query_results );
		}
	} // End class
}
