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

if ( ! class_exists( 'SftcyWordformConnectMailerlite' ) ) {
	class SftcyWordformConnectMailerlite {
		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_mailerlite_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_mailerlite_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_mailerlite_with_form_fields', [ __CLASS__, 'wordform_connect_create_mailerlite_with_form_fields' ] );
			add_action( 'wp_ajax_wordform_connect_fetch_mailerlite_groups', [ __CLASS__, 'wordform_connect_fetch_mailerlite_groups' ] );

			self::$initiated = true;
		}

		/**
		 * Get MailerLite configured information from option table.
		 *
		 * @return array
		 */
		public static function get_mailerlite_configured_info() {
			$mailerlite_info = get_option( 'wordform_connect_mailerlite_info', [] );
			if ( isset( $mailerlite_info['apiToken'], $mailerlite_info['groupId'] ) && ! empty( $mailerlite_info['apiToken'] ) && ! empty( $mailerlite_info['groupId'] ) ) {
				return [
					'apiToken'   => $mailerlite_info['apiToken'],
					'groupId'    => $mailerlite_info['groupId'],
					'groupLabel' => isset( $mailerlite_info['groupLabel'] ) ? $mailerlite_info['groupLabel'] : '',
				];
			}

			return [];
		}

		/**
		 * Ajax request.
		 * Store MailerLite API token and group ID as option data.
		 *
		 * @return void
		 */
		public static function wordform_connect_save_mailerlite_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$mailerlite_api_token   = isset( $_POST['params']['mailerliteApiToken'] ) ? sanitize_text_field( trim( $_POST['params']['mailerliteApiToken'] ) ) : '';
			$mailerlite_group_id    = isset( $_POST['params']['mailerliteGroupId'] ) ? sanitize_text_field( trim( $_POST['params']['mailerliteGroupId'] ) ) : '';
			$mailerlite_group_label = isset( $_POST['params']['mailerliteGroupLabel'] ) ? sanitize_text_field( trim( $_POST['params']['mailerliteGroupLabel'] ) ) : '';
			self::$output           = [];

			if ( empty( $mailerlite_api_token ) || empty( $mailerlite_group_id ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'MailerLite API token or Group ID missing.';
				self::$output['comment'] = 'MailerLite API token and Group ID are required.';
			} else {
				$mailerlite_info = [
					'apiToken'   => $mailerlite_api_token,
					'groupId'    => $mailerlite_group_id,
					'groupLabel' => $mailerlite_group_label,
				];

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

				self::$output['mailerliteConfiguredInfoStatus'] = self::save_configured_mailerlite_application( $mailerlite_info );
				self::$output['configuredApplication']          = SftcyWordformConnectBase::get_configured_application_option_payload( 'mailerlite' );
			}

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

		/**
		 * Save configured MailerLite application into configured applications table.
		 *
		 * @param array $mailerlite_info MailerLite configuration.
		 * @return bool
		 */
		public static function save_configured_mailerlite_application( $mailerlite_info = [] ) {
			if ( ! is_array( $mailerlite_info ) || ! isset( $mailerlite_info['apiToken'], $mailerlite_info['groupId'] ) ) {
				return false;
			}

			$application_slug = 'mailerlite';
			$application_name = 'MailerLite';
			$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' => 'mailerlite-subscriber',
					'apiToken'      => $mailerlite_info['apiToken'],
					'groupId'       => $mailerlite_info['groupId'],
					'groupLabel'    => isset( $mailerlite_info['groupLabel'] ) ? $mailerlite_info['groupLabel'] : '',
				]
			);

			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 MailerLite connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_mailerlite_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 ) ) {
						$mailerlite_info = self::get_mailerlite_configured_info();
						if ( isset( $mailerlite_info['apiToken'], $mailerlite_info['groupId'] ) && ! empty( $mailerlite_info['apiToken'] ) && ! empty( $mailerlite_info['groupId'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'mailerlite-subscriber',
								'apiToken'            => $mailerlite_info['apiToken'],
								'groupId'             => $mailerlite_info['groupId'],
								'groupLabel'          => isset( $mailerlite_info['groupLabel'] ) ? $mailerlite_info['groupLabel'] : '',
								'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']              = 'MailerLite connected successfully.';
								self::$output['comment']             = 'MailerLite 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 MailerLite connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'MailerLite configuration missing.';
							self::$output['comment'] = 'MailerLite API token or Group ID not found. Please save MailerLite 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 MailerLite groups.
		 *
		 * @return void
		 */
		public static function wordform_connect_fetch_mailerlite_groups() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$mailerlite_api_token = isset( $_POST['params']['mailerliteApiToken'] ) ? sanitize_text_field( trim( $_POST['params']['mailerliteApiToken'] ) ) : '';
			$response             = self::get_mailerlite_groups( $mailerlite_api_token );

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

		/**
		 * Fetch MailerLite groups.
		 *
		 * @param string $mailerlite_api_token MailerLite API token.
		 * @return array
		 */
		private static function get_mailerlite_groups( $mailerlite_api_token = '' ) {
			$mailerlite_api_token = sanitize_text_field( trim( (string) $mailerlite_api_token ) );
			if ( empty( $mailerlite_api_token ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Please enter a valid MailerLite API token first.',
					'mailerlite',
					[
					'fixTip' => 'Create a MailerLite API token with subscriber and group access, then paste it here exactly as copied.',
						'logStage' => 'verify_load',
					]
				);
			}

			$response = wp_remote_get(
				'https://connect.mailerlite.com/api/groups',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $mailerlite_api_token,
						'Accept'        => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'MailerLite groups could not be loaded right now: ' . $response->get_error_message(),
					'mailerlite',
					[
					'fixTip' => 'Check outbound HTTPS access from this site, then verify the MailerLite token and try again.',
						'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      = 'MailerLite API token could not be verified.';
				if ( false !== stripos( $remote_error, 'Enable JavaScript and cookies to continue' ) ) {
					$remote_error = 'MailerLite returned a browser challenge instead of a normal API response.';
				}
				if ( ! empty( $remote_error ) ) {
					$comment .= ' ' . $remote_error;
				}

				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					$comment,
					'mailerlite',
					[
						'fixTip'            => 'Confirm the token is active and belongs to the MailerLite account that contains the target group.',
						'responseStatusCode'=> $status_code,
						'logStage'          => 'verify_load',
					]
				);
			}

			$groups_payload = [];
			if ( isset( $json['data'] ) && is_array( $json['data'] ) ) {
				$groups_payload = $json['data'];
			} elseif ( isset( $json['groups'] ) && is_array( $json['groups'] ) ) {
				$groups_payload = $json['groups'];
			} elseif ( array_values( $json ) === $json ) {
				$groups_payload = $json;
			}

			$resources = [];
			foreach ( $groups_payload as $group ) {
				if ( ! is_array( $group ) || empty( $group['id'] ) ) {
					continue;
				}

				$group_id    = sanitize_text_field( (string) $group['id'] );
				$group_label = isset( $group['name'] ) && '' !== trim( (string) $group['name'] ) ? sanitize_text_field( (string) $group['name'] ) : $group_id;
				$resources[] = [
					'value' => $group_id,
					'label' => $group_label,
				];
			}

			if ( empty( $resources ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'No MailerLite groups were found for this API token.',
					'mailerlite',
					[
						'fixTip' => 'Create at least one group in MailerLite, or verify that the token can access existing groups.',
						'logStage' => 'verify_load',
					]
				);
			}

			return SftcyWordformConnectBase::build_connect_feedback_payload(
				'success',
				'MailerLite groups loaded successfully.',
				'mailerlite',
				[
					'resources' => $resources,
				]
			);
		}

		/**
		 * Send form submission data into MailerLite subscribers.
		 *
		 * @param array $forms_data Processed form fields.
		 * @param array $mailerlite_info MailerLite configuration.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_mailerlite( $forms_data = [], $mailerlite_info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'mailerlite';

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

			$mailerlite_api_token = isset( $mailerlite_info['apiToken'] ) ? sanitize_text_field( (string) $mailerlite_info['apiToken'] ) : '';
			$mailerlite_group_id  = isset( $mailerlite_info['groupId'] ) ? sanitize_text_field( (string) $mailerlite_info['groupId'] ) : '';
			if ( empty( $mailerlite_api_token ) || empty( $mailerlite_group_id ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'MailerLite configuration incomplete.';
				$send_info['comment'] = 'MailerLite API token or Group 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'] = 'MailerLite requires at least one valid email field in the connected form.';
				return $send_info;
			}

			$request_body = [
				'email'  => $contact_properties['email'],
				'groups' => [ $mailerlite_group_id ],
				'status' => 'active',
			];

			$fields = [];
			if ( ! empty( $contact_properties['firstName'] ) ) {
				$fields['name'] = $contact_properties['firstName'];
			}
			if ( ! empty( $contact_properties['lastName'] ) ) {
				$fields['last_name'] = $contact_properties['lastName'];
			}
			if ( ! empty( $contact_properties['phone'] ) ) {
				$fields['phone'] = $contact_properties['phone'];
			}
			if ( ! empty( $contact_properties['company'] ) ) {
				$fields['company'] = $contact_properties['company'];
			}
			if ( $fields ) {
				$request_body['fields'] = $fields;
			}

			$response = wp_remote_post(
				'https://connect.mailerlite.com/api/subscribers',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $mailerlite_api_token,
						'Accept'        => 'application/json',
						'Content-Type'  => 'application/json; charset=utf-8',
					],
					'body'    => wp_json_encode( $request_body ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'MailerLite request failed.';
				$send_info['requestError'] = $response->get_error_message();
				$send_info['comment']      = 'MailerLite API 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 ) {
				$subscriber_data = [];
				if ( is_array( $response_json ) && isset( $response_json['data'] ) && is_array( $response_json['data'] ) ) {
					$subscriber_data = $response_json['data'];
				} elseif ( is_array( $response_json ) ) {
					$subscriber_data = $response_json;
				}

				$send_info['status']  = 'success';
				$send_info['reason']  = 'Form submission data sent to MailerLite.';
				$send_info['comment'] = 'MailerLite subscriber synced successfully.';
				if ( isset( $subscriber_data['id'] ) ) {
					$send_info['subscriberId'] = sanitize_text_field( (string) $subscriber_data['id'] );
				}
				if ( isset( $subscriber_data['status'] ) ) {
					$send_info['subscriberStatus'] = sanitize_text_field( (string) $subscriber_data['status'] );
				}
			} else {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'MailerLite response status indicates failure.';
				$send_info['comment'] = 'MailerLite API returned non-success HTTP status.';

				if ( is_array( $response_json ) ) {
					if ( isset( $response_json['message'] ) ) {
						$send_info['responseMessage'] = substr( sanitize_textarea_field( (string) $response_json['message'] ), 0, 500 );
					}

					if ( isset( $response_json['errors'] ) ) {
						$send_info['responseErrors'] = substr( sanitize_textarea_field( wp_json_encode( $response_json['errors'] ) ), 0, 500 );
					}
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $response_body ), 0, 500 );
				}
			}

			return $send_info;
		}

		/**
		 * Check whether MailerLite configured app status is active.
		 *
		 * @return bool
		 */
		public static function is_mailerlite_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,
						'mailerlite',
						'active',
					]
				),
				ARRAY_A
			);

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