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

if ( ! class_exists( 'SftcyWordformConnectBrevo' ) ) {
	class SftcyWordformConnectBrevo {
		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_brevo_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_brevo_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_brevo_with_form_fields', [ __CLASS__, 'wordform_connect_create_brevo_with_form_fields' ] );
			add_action( 'wp_ajax_wordform_connect_fetch_brevo_lists', [ __CLASS__, 'wordform_connect_fetch_brevo_lists' ] );

			self::$initiated = true;
		}

		/**
		 * Get Brevo configured information from option table.
		 *
		 * @return array
		 */
		public static function get_brevo_configured_info() {
			$brevo_info = get_option( 'wordform_connect_brevo_info', [] );
			if ( isset( $brevo_info['apiKey'], $brevo_info['listId'] ) && ! empty( $brevo_info['apiKey'] ) && ! empty( $brevo_info['listId'] ) ) {
				return [
					'apiKey'    => $brevo_info['apiKey'],
					'listId'    => (int) $brevo_info['listId'],
					'listLabel' => isset( $brevo_info['listLabel'] ) ? $brevo_info['listLabel'] : '',
				];
			}

			return [];
		}

		/**
		 * Ajax request.
		 * Store Brevo API key and list ID as option data.
		 *
		 * @return void
		 */
		public static function wordform_connect_save_brevo_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$brevo_api_key = isset( $_POST['params']['brevoApiKey'] ) ? sanitize_text_field( trim( $_POST['params']['brevoApiKey'] ) ) : '';
			$brevo_list_id = isset( $_POST['params']['brevoListId'] ) ? absint( $_POST['params']['brevoListId'] ) : 0;
			$brevo_list_label = isset( $_POST['params']['brevoListLabel'] ) ? sanitize_text_field( trim( $_POST['params']['brevoListLabel'] ) ) : '';
			self::$output  = [];

			if ( empty( $brevo_api_key ) || $brevo_list_id <= 0 ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Brevo API key or List ID missing.';
				self::$output['comment'] = 'Brevo API key and valid List ID are required.';
			} else {
				$brevo_info = [
					'apiKey'    => $brevo_api_key,
					'listId'    => $brevo_list_id,
					'listLabel' => $brevo_list_label,
				];

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

				self::$output['brevoConfiguredInfoStatus'] = self::save_configured_brevo_application( $brevo_info );
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( 'brevo' );
			}

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

		/**
		 * Save configured Brevo application into configured applications table.
		 *
		 * @param array $brevo_info Brevo configuration.
		 * @return bool
		 */
		public static function save_configured_brevo_application( $brevo_info = [] ) {
			if ( ! is_array( $brevo_info ) || ! isset( $brevo_info['apiKey'], $brevo_info['listId'] ) ) {
				return false;
			}

			$application_slug = 'brevo';
			$application_name = 'Brevo';
			$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' => 'brevo-contact',
					'apiKey'        => $brevo_info['apiKey'],
					'listId'        => (int) $brevo_info['listId'],
					'listLabel'     => isset( $brevo_info['listLabel'] ) ? $brevo_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;
		}

		/**
		 * Ajax call.
		 * Store Brevo connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_brevo_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 ) ) {
						$brevo_info = self::get_brevo_configured_info();
						if ( isset( $brevo_info['apiKey'], $brevo_info['listId'] ) && ! empty( $brevo_info['apiKey'] ) && ! empty( $brevo_info['listId'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'brevo-contact',
								'apiKey'              => $brevo_info['apiKey'],
								'listId'              => (int) $brevo_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']              = 'Brevo connected successfully.';
								self::$output['comment']             = 'Brevo 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 Brevo connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Brevo configuration missing.';
							self::$output['comment'] = 'Brevo API key or List ID not found. Please save Brevo 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 Brevo contact lists.
		 *
		 * @return void
		 */
		public static function wordform_connect_fetch_brevo_lists() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$brevo_api_key = isset( $_POST['params']['brevoApiKey'] ) ? sanitize_text_field( trim( $_POST['params']['brevoApiKey'] ) ) : '';
			$response      = self::get_brevo_lists( $brevo_api_key );

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

		/**
		 * Fetch Brevo contact lists.
		 *
		 * @param string $brevo_api_key
		 * @return array
		 */
		private static function get_brevo_lists( $brevo_api_key = '' ) {
			$brevo_api_key = sanitize_text_field( trim( (string) $brevo_api_key ) );
			if ( empty( $brevo_api_key ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Please enter a valid Brevo API key first.',
					'brevo',
					[
					'fixTip' => 'Create an API key with contact and list access in Brevo, then paste it here exactly as copied.',
						'logStage' => 'verify_load',
					]
				);
			}

			$response = wp_remote_get(
				'https://api.brevo.com/v3/contacts/lists?limit=500',
				[
					'timeout' => 20,
					'headers' => [
						'api-key' => $brevo_api_key,
						'accept'  => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Brevo lists could not be loaded right now: ' . $response->get_error_message(),
					'brevo',
					[
					'fixTip' => 'Check outbound HTTPS access from this site, then try verifying the Brevo API key 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      = 'Brevo API key could not be verified.';
				if ( ! empty( $remote_error ) ) {
					$comment .= ' ' . $remote_error;
				}

				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					$comment,
					'brevo',
					[
						'fixTip'            => 'Confirm the API key is active and has contact list access, then run Verify & Load Lists again.',
						'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 Brevo lists were found for this API key.',
					'brevo',
					[
						'fixTip' => 'Check whether the connected Brevo account already has at least one contact list created.',
						'logStage' => 'verify_load',
					]
				);
			}

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

		/**
		 * Send form submission data into Brevo contacts list.
		 * Creates or updates a contact and assigns the configured list ID.
		 *
		 * @param array $forms_data Processed form fields.
		 * @param array $brevo_info Brevo configuration.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_brevo( $forms_data = [], $brevo_info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'brevo';

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

			$brevo_api_key = isset( $brevo_info['apiKey'] ) ? sanitize_text_field( (string) $brevo_info['apiKey'] ) : '';
			$brevo_list_id = isset( $brevo_info['listId'] ) ? absint( $brevo_info['listId'] ) : 0;
			if ( empty( $brevo_api_key ) || $brevo_list_id <= 0 ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Brevo configuration incomplete.';
				$send_info['comment'] = 'Brevo API key or List ID missing.';
				return $send_info;
			}

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

			$name_parts = SftcyWordformConnectBase::extract_name_parts_from_submission_fields( $forms_data );
			$attributes = [];
			if ( ! empty( $name_parts['firstName'] ) ) {
				$attributes['FNAME'] = $name_parts['firstName'];
			}
			if ( ! empty( $name_parts['lastName'] ) ) {
				$attributes['LNAME'] = $name_parts['lastName'];
			}

			$request_body = [
				'email'         => $email_address,
				'listIds'       => [ $brevo_list_id ],
				'updateEnabled' => true,
			];
			if ( $attributes ) {
				$request_body['attributes'] = $attributes;
			}

			$response = wp_remote_post(
				'https://api.brevo.com/v3/contacts',
				[
					'timeout' => 20,
					'headers' => [
						'Content-Type' => 'application/json; charset=utf-8',
						'accept'       => 'application/json',
						'api-key'      => $brevo_api_key,
					],
					'body'    => wp_json_encode( $request_body ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'Brevo request failed.';
				$send_info['requestError'] = $response->get_error_message();
				$send_info['comment']      = 'Brevo 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 ) {
				$send_info['status']  = 'success';
				$send_info['reason']  = 'Form submission data sent to Brevo.';
				$send_info['comment'] = 'Brevo 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']  = 'Brevo response status indicates failure.';
				$send_info['comment'] = 'Brevo API returned non-success HTTP status.';
				if ( is_array( $response_json ) ) {
					if ( isset( $response_json['code'] ) ) {
						$send_info['responseCode'] = sanitize_text_field( (string) $response_json['code'] );
					}
					if ( 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 Brevo configured app status is active.
		 *
		 * @return bool
		 */
		public static function is_brevo_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,
						'brevo',
						'active',
					]
				),
				ARRAY_A
			);

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