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

if ( ! class_exists( 'SftcyWordformConnectCustomWebhook' ) ) {
	class SftcyWordformConnectCustomWebhook {
		private static $initiated              = false;
		public static $output                  = [];
		public static $custom_webhook_post_url = null;
		public static $configure_spinning_icon = '<i class="fa-solid fa-gear fa-spin"></i>';

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

		/**
		 * Init hooks.
		 */
		private static function initiate_hooks() {
			add_action( 'wp_ajax_wordform_connect_save_custom_webhook_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_custom_webhook_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_custom_webhook_with_form_fields', [ __CLASS__, 'wordform_connect_create_custom_webhook_with_form_fields' ] );

			self::$initiated = true;
		}

		/**
		 * Get custom webhook information from option table.
		 * Option key: wordform_connect_custom_webhook_info
		 *
		 * @return array
		 */
		public static function get_custom_webhook_url() {
			$custom_webhook_info = get_option( 'wordform_connect_custom_webhook_info', [] );
			$custom_info         = [];
			if ( isset( $custom_webhook_info['webhookPostUrl'] ) && ! empty( $custom_webhook_info['webhookPostUrl'] ) ) {
				$custom_info['webhookPostUrl'] = $custom_webhook_info['webhookPostUrl'];
				return $custom_info;
			}
			return [];
		}

		/**
		 * Ajax request.
		 * Store custom webhook URL as option data.
		 *
		 * @return void
		 */
		public static function wordform_connect_save_custom_webhook_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$custom_webhook_post_url = isset( $_POST['params']['customWebhookUrl'] ) ? esc_url_raw( trim( $_POST['params']['customWebhookUrl'] ) ) : '';
			self::$output            = [];

			if ( ! empty( $custom_webhook_post_url ) && filter_var( $custom_webhook_post_url, FILTER_VALIDATE_URL ) ) {
				$custom_webhook_info                   = [];
				$custom_webhook_info['webhookPostUrl'] = $custom_webhook_post_url;
				if ( update_option( 'wordform_connect_custom_webhook_info', $custom_webhook_info ) ) {
					self::$output['status']  = 'success';
					self::$output['reason']  = 'Custom Webhook URL saved as option value.';
					self::$output['comment'] = 'Custom Webhook URL saved successfully.';
				} else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'Custom Webhook URL did not change.';
					self::$output['comment'] = 'Custom Webhook URL saved successfully.';
				}

				self::$output['customWebhookConfiguredInfoStatus'] = self::save_configured_custom_webhook_application( $custom_webhook_post_url );
				self::$output['configuredApplication']             = SftcyWordformConnectBase::get_configured_application_option_payload( 'customwebhook' );
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Custom Webhook URL not in valid format.';
				self::$output['comment'] = 'Valid Custom Webhook URL required.';
			}

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

		/**
		 * Keep record while configured Custom Webhook.
		 * DB record field application_slug: customwebhook
		 * DB record field application_name: Custom Webhook
		 *
		 * @param string $custom_webhook_post_url Webhook post URL.
		 * @return bool
		 */
		public static function save_configured_custom_webhook_application( $custom_webhook_post_url = '' ) {
			$application_slug = 'customwebhook';
			$application_name = 'Custom Webhook';
			$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 );
			if ( $query_results ) {
				$where                    = [ 'id' => $query_results[0]['id'] ];
				$data['configured_info']  = wp_json_encode(
					[
						'reconfigured'  => 'yes',
						'payloadFormat' => 'json',
						'webhookPostUrl' => $custom_webhook_post_url,
					]
				);
				$data['configured_status'] = 'active';
				$update_result             = $wpdb->update( $table, $data, $where );
				// 0 means query succeeded but no changed row values.
				if ( false === $update_result ) {
					return false;
				}
				return true;
			}

			$data['configured_info'] = wp_json_encode(
				[
					'reconfigured'  => 'no',
					'payloadFormat' => 'json',
					'webhookPostUrl' => $custom_webhook_post_url,
				]
			);
			$insert_result           = $wpdb->insert( $table, $data );
			return false !== $insert_result;
		}

		/**
		 * Ajax call.
		 * While click on Connect/ReConnect button for Custom Webhook.
		 * Store connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_custom_webhook_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 ) ) {
						$custom_webhook_info = self::get_custom_webhook_url();
						if ( $custom_webhook_info && isset( $custom_webhook_info['webhookPostUrl'] ) && ! empty( $custom_webhook_info['webhookPostUrl'] ) ) {
							$connection_info = [
								'applicationName'  => $configured_application_name,
								'formName'         => $wordform_name,
								'formFields'       => $form_fields,
								'webhookPostUrl'   => $custom_webhook_info['webhookPostUrl'],
								'payloadFormat'    => 'json',
								'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 );
							// wpdb update may return 0 if unchanged; treat as success because connection already exists.
							if ( false !== $db_result ) {
								self::$output['status']              = 'success';
								self::$output['formFields']          = $form_fields;
								self::$output['formName']            = $wordform_name;
								self::$output['reason']              = 'Custom Webhook connected successfully.';
								self::$output['comment']             = 'Custom Webhook 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 Custom Webhook connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Custom Webhook URL missing.';
							self::$output['comment'] = 'Custom Webhook URL not found. Please save webhook URL 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 forms submission data to configured custom webhook as JSON payload.
		 *
		 * @param array  $payload JSON serializable payload.
		 * @param string $custom_webhook_post_url Webhook URL.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_custom_post_webhook( $payload = [], $custom_webhook_post_url = '' ) {
			$custom_info                    = [];
			$custom_info['applicationSlug'] = 'customwebhook';

			if ( ! is_array( $payload ) || ! array_filter( $payload ) ) {
				$custom_info['status']  = 'fail';
				$custom_info['reason']  = 'Payload is empty.';
				$custom_info['comment'] = 'No JSON payload found to send.';
				return $custom_info;
			}

			if ( empty( $custom_webhook_post_url ) || ! filter_var( $custom_webhook_post_url, FILTER_VALIDATE_URL ) ) {
				$custom_info['status']  = 'fail';
				$custom_info['reason']  = 'Invalid webhook URL.';
				$custom_info['comment'] = 'Custom Webhook URL is invalid or missing.';
				return $custom_info;
			}

			$response = wp_remote_post(
				$custom_webhook_post_url,
				[
					'timeout' => 20,
					'headers' => [
						'Content-Type' => 'application/json; charset=utf-8',
						'Accept'       => 'application/json, text/plain, */*',
					],
					'body'    => wp_json_encode( $payload ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$custom_info['status']       = 'fail';
				$custom_info['reason']       = 'Webhook request failed.';
				$custom_info['requestError'] = $response->get_error_message();
				$custom_info['comment']      = 'Custom Webhook request could not be completed.';
				return $custom_info;
			}

			$status_code = (int) wp_remote_retrieve_response_code( $response );
			$response_body = wp_remote_retrieve_body( $response );
			$custom_info['responseStatusCode'] = $status_code;

			if ( $status_code >= 200 && $status_code < 300 ) {
				$custom_info['status']  = 'success';
				$custom_info['reason']  = 'Form submission data sent to Custom Webhook.';
				$custom_info['comment'] = 'Sent JSON payload into Custom Webhook successfully.';
			} else {
				$custom_info['status']       = 'fail';
				$custom_info['reason']       = 'Custom Webhook response status indicates failure.';
				$custom_info['responseBody'] = substr( sanitize_textarea_field( (string) $response_body ), 0, 500 );
				$custom_info['comment']      = 'Custom Webhook endpoint returned non-success HTTP status.';
			}

			return $custom_info;
		}

		/**
		 * Check configured_status of Custom Webhook application.
		 *
		 * @return bool
		 */
		public static function is_custom_webhook_configured_status_active() {
			$application_slug = 'customwebhook';

			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 );
			if ( $query_results && isset( $query_results[0]['configured_status'] ) && 'active' === $query_results[0]['configured_status'] ) {
				return true;
			}
			return false;
		}
	} // End class
}
