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

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

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

		private static function initiate_hooks() {
			add_action( 'wp_ajax_wordform_connect_save_activecampaign_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_activecampaign_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_activecampaign_with_form_fields', [ __CLASS__, 'wordform_connect_create_activecampaign_with_form_fields' ] );
			add_action( 'wp_ajax_wordform_connect_fetch_activecampaign_lists', [ __CLASS__, 'wordform_connect_fetch_activecampaign_lists' ] );
			self::$initiated = true;
		}

		public static function get_activecampaign_configured_info() {
			$info = get_option( 'wordform_connect_activecampaign_info', [] );
			if ( isset( $info['apiBaseUrl'], $info['apiKey'], $info['listId'] ) && ! empty( $info['apiBaseUrl'] ) && ! empty( $info['apiKey'] ) && ! empty( $info['listId'] ) ) {
				return [
					'apiBaseUrl' => untrailingslashit( $info['apiBaseUrl'] ),
					'apiKey'     => $info['apiKey'],
					'listId'     => absint( $info['listId'] ),
					'listLabel'  => isset( $info['listLabel'] ) ? $info['listLabel'] : '',
				];
			}

			return [];
		}

		public static function wordform_connect_save_activecampaign_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$api_base_url = isset( $_POST['params']['activecampaignApiBaseUrl'] ) ? esc_url_raw( trim( $_POST['params']['activecampaignApiBaseUrl'] ) ) : '';
			$api_key      = isset( $_POST['params']['activecampaignApiKey'] ) ? sanitize_text_field( trim( $_POST['params']['activecampaignApiKey'] ) ) : '';
			$list_id      = isset( $_POST['params']['activecampaignListId'] ) ? absint( $_POST['params']['activecampaignListId'] ) : 0;
			$list_label   = isset( $_POST['params']['activecampaignListLabel'] ) ? sanitize_text_field( trim( $_POST['params']['activecampaignListLabel'] ) ) : '';
			self::$output = [];

			if ( empty( $api_base_url ) || empty( $api_key ) || $list_id <= 0 ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'ActiveCampaign configuration values are missing.';
				self::$output['comment'] = 'ActiveCampaign API URL, API Key, and List ID are required.';
			} elseif ( ! filter_var( $api_base_url, FILTER_VALIDATE_URL ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'ActiveCampaign API URL is not valid.';
				self::$output['comment'] = 'Please enter valid ActiveCampaign API URL.';
			} else {
				$info = [
					'apiBaseUrl' => untrailingslashit( $api_base_url ),
					'apiKey'     => $api_key,
					'listId'     => $list_id,
					'listLabel'  => $list_label,
				];

				if ( update_option( 'wordform_connect_activecampaign_info', $info ) ) {
					self::$output['status']  = 'success';
					self::$output['reason']  = 'ActiveCampaign configuration saved.';
					self::$output['comment'] = 'ActiveCampaign configuration saved successfully.';
				} else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'ActiveCampaign configuration did not change.';
					self::$output['comment'] = 'ActiveCampaign configuration saved successfully.';
				}

				self::$output['activecampaignConfiguredInfoStatus'] = self::save_configured_activecampaign_application( $info );
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( 'activecampaign' );
			}

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

		public static function save_configured_activecampaign_application( $info = [] ) {
			if ( ! is_array( $info ) || ! isset( $info['apiBaseUrl'], $info['apiKey'], $info['listId'] ) ) {
				return false;
			}

			$application_slug = 'activecampaign';
			$application_name = 'ActiveCampaign';
			$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', [ $table, $application_slug ] ), ARRAY_A );

			$data['configured_info'] = wp_json_encode(
				[
					'reconfigured'  => $query_results ? 'yes' : 'no',
					'payloadFormat' => 'activecampaign-contact',
					'apiBaseUrl'    => untrailingslashit( $info['apiBaseUrl'] ),
					'apiKey'        => $info['apiKey'],
					'listId'        => absint( $info['listId'] ),
					'listLabel'     => isset( $info['listLabel'] ) ? $info['listLabel'] : '',
				]
			);

			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;
		}

		public static function wordform_connect_create_activecampaign_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 ) ) {
						$info = self::get_activecampaign_configured_info();
						if ( $info ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'activecampaign-contact',
								'apiBaseUrl'          => $info['apiBaseUrl'],
								'apiKey'              => $info['apiKey'],
								'listId'              => $info['listId'],
								'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']              = 'ActiveCampaign connected successfully.';
								self::$output['comment']             = 'ActiveCampaign 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 ActiveCampaign connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'ActiveCampaign configuration missing.';
							self::$output['comment'] = 'ActiveCampaign API URL, API Key, or List ID not found. Please save 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();
		}

		/**
		 * Ajax request.
		 * Fetch ActiveCampaign lists.
		 *
		 * @return void
		 */
		public static function wordform_connect_fetch_activecampaign_lists() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$api_base_url = isset( $_POST['params']['activecampaignApiBaseUrl'] ) ? esc_url_raw( trim( $_POST['params']['activecampaignApiBaseUrl'] ) ) : '';
			$api_key      = isset( $_POST['params']['activecampaignApiKey'] ) ? sanitize_text_field( trim( $_POST['params']['activecampaignApiKey'] ) ) : '';
			$response     = self::get_activecampaign_lists( $api_base_url, $api_key );

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

		/**
		 * Fetch ActiveCampaign lists.
		 *
		 * @param string $api_base_url
		 * @param string $api_key
		 * @return array
		 */
		private static function get_activecampaign_lists( $api_base_url = '', $api_key = '' ) {
			$api_base_url = untrailingslashit( esc_url_raw( trim( (string) $api_base_url ) ) );
			$api_key      = sanitize_text_field( trim( (string) $api_key ) );

			if ( empty( $api_base_url ) || empty( $api_key ) || ! filter_var( $api_base_url, FILTER_VALIDATE_URL ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Please enter a valid ActiveCampaign API URL and API key first.',
					'activecampaign',
					[
					'fixTip' => 'Use the exact API URL and API key from ActiveCampaign account settings.',
						'logStage' => 'verify_load',
					]
				);
			}

			$response = wp_remote_get(
				$api_base_url . '/api/3/lists',
				[
					'timeout' => 20,
					'headers' => [
						'Api-Token' => $api_key,
						'Accept'    => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'ActiveCampaign lists could not be loaded right now: ' . $response->get_error_message(),
					'activecampaign',
					[
					'fixTip' => 'Check outbound HTTPS access from this site, then verify the API URL and API key.',
						'logStage' => 'verify_load',
					]
				);
			}

			$status_code = (int) wp_remote_retrieve_response_code( $response );
			$body        = wp_remote_retrieve_body( $response );
			$json        = json_decode( $body, true );

			if ( $status_code < 200 || $status_code >= 300 || ! is_array( $json ) ) {
				$remote_error = SftcyWordformConnectBase::extract_connect_remote_error_message( $body );
				$comment      = 'ActiveCampaign credentials could not be verified.';
				if ( ! empty( $remote_error ) ) {
					$comment .= ' ' . $remote_error;
				}

				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					$comment,
					'activecampaign',
					[
						'fixTip'            => 'Confirm the API URL points to your ActiveCampaign account and the API key is still active.',
						'responseStatusCode'=> $status_code,
						'logStage'          => 'verify_load',
					]
				);
			}

			$resources = [];
			if ( ! empty( $json['lists'] ) && is_array( $json['lists'] ) ) {
				foreach ( $json['lists'] as $list ) {
					if ( empty( $list['id'] ) ) {
						continue;
					}
					$label = isset( $list['name'] ) && '' !== trim( (string) $list['name'] ) ? $list['name'] : (string) $list['id'];
					$resources[] = [
						'value' => (string) absint( $list['id'] ),
						'label' => sanitize_text_field( $label ),
					];
				}
			}

			if ( empty( $resources ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'No ActiveCampaign lists were found for this account.',
					'activecampaign',
					[
						'fixTip' => 'Create at least one list in ActiveCampaign, or confirm the connected account already has available lists.',
						'logStage' => 'verify_load',
					]
				);
			}

			return SftcyWordformConnectBase::build_connect_feedback_payload(
				'success',
				'ActiveCampaign lists loaded successfully.',
				'activecampaign',
				[
					'resources' => $resources,
				]
			);
		}

		public static function wordform_send_forms_data_into_activecampaign( $forms_data = [], $info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'activecampaign';

			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 ActiveCampaign.';
				return $send_info;
			}

			$api_base_url = isset( $info['apiBaseUrl'] ) ? untrailingslashit( $info['apiBaseUrl'] ) : '';
			$api_key      = isset( $info['apiKey'] ) ? sanitize_text_field( (string) $info['apiKey'] ) : '';
			$list_id      = isset( $info['listId'] ) ? absint( $info['listId'] ) : 0;
			if ( empty( $api_base_url ) || empty( $api_key ) || $list_id <= 0 ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'ActiveCampaign configuration incomplete.';
				$send_info['comment'] = 'ActiveCampaign API URL, API Key, or List ID 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'] = 'ActiveCampaign requires at least one valid email field in the connected form.';
				return $send_info;
			}

			$contact_payload = [
				'contact' => [
					'email' => $contact_properties['email'],
				],
			];
			if ( ! empty( $contact_properties['firstName'] ) ) {
				$contact_payload['contact']['firstName'] = $contact_properties['firstName'];
			}
			if ( ! empty( $contact_properties['lastName'] ) ) {
				$contact_payload['contact']['lastName'] = $contact_properties['lastName'];
			}
			if ( ! empty( $contact_properties['phone'] ) ) {
				$contact_payload['contact']['phone'] = $contact_properties['phone'];
			}

			$headers = [
				'Content-Type' => 'application/json; charset=utf-8',
				'Api-Token'    => $api_key,
			];

			$sync_response = wp_remote_post(
				$api_base_url . '/api/3/contact/sync',
				[
					'timeout' => 20,
					'headers' => $headers,
					'body'    => wp_json_encode( $contact_payload ),
				]
			);

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

			$sync_status_code = (int) wp_remote_retrieve_response_code( $sync_response );
			$sync_body        = wp_remote_retrieve_body( $sync_response );
			$sync_json        = json_decode( $sync_body, true );
			if ( $sync_status_code < 200 || $sync_status_code >= 300 || ! is_array( $sync_json ) || empty( $sync_json['contact']['id'] ) ) {
				$send_info['status']           = 'fail';
				$send_info['reason']           = 'ActiveCampaign contact sync failed.';
				$send_info['comment']          = 'ActiveCampaign could not create or update the contact.';
				$send_info['responseStatusCode'] = $sync_status_code;
				if ( is_array( $sync_json ) && isset( $sync_json['message'] ) ) {
					$send_info['responseMessage'] = substr( sanitize_textarea_field( (string) $sync_json['message'] ), 0, 500 );
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $sync_body ), 0, 500 );
				}
				return $send_info;
			}

			$contact_id = absint( $sync_json['contact']['id'] );
			$list_response = wp_remote_post(
				$api_base_url . '/api/3/contactLists',
				[
					'timeout' => 20,
					'headers' => $headers,
					'body'    => wp_json_encode(
						[
							'contactList' => [
								'list'    => $list_id,
								'contact' => $contact_id,
								'status'  => 1,
							],
						]
					),
				]
			);

			if ( is_wp_error( $list_response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'ActiveCampaign list subscribe request failed.';
				$send_info['requestError'] = $list_response->get_error_message();
				$send_info['comment']      = 'ActiveCampaign contact synced but list subscription request failed.';
				$send_info['contactId']    = $contact_id;
				return $send_info;
			}

			$list_status_code = (int) wp_remote_retrieve_response_code( $list_response );
			$list_body        = wp_remote_retrieve_body( $list_response );
			$list_json        = json_decode( $list_body, true );
			$send_info['contactId'] = $contact_id;
			$send_info['responseStatusCode'] = $list_status_code;

			if ( $list_status_code >= 200 && $list_status_code < 300 ) {
				$send_info['status']  = 'success';
				$send_info['reason']  = 'Form submission data sent to ActiveCampaign.';
				$send_info['comment'] = 'ActiveCampaign contact synced and added to the configured list.';
			} else {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'ActiveCampaign list subscribe failed.';
				$send_info['comment'] = 'ActiveCampaign contact synced but could not be subscribed to the configured list.';
				if ( is_array( $list_json ) && isset( $list_json['message'] ) ) {
					$send_info['responseMessage'] = substr( sanitize_textarea_field( (string) $list_json['message'] ), 0, 500 );
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $list_body ), 0, 500 );
				}
			}

			return $send_info;
		}

		public static function is_activecampaign_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, 'activecampaign', 'active' ] ), ARRAY_A );
			return ! empty( $query_results );
		}
	}
}
