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

if ( ! class_exists( 'SftcyWordformConnectSlack' ) ) {
	class SftcyWordformConnectSlack {
		private static $initiated          = false;
		public static $output              = [];
		public static $slack_webhook_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_slack_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_slack_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_slack_with_form_fields', [ __CLASS__, 'wordform_connect_create_slack_with_form_fields' ] );

			self::$initiated = true;
		}

		/**
		 * Get Slack webhook information from option table.
		 *
		 * @return array
		 */
		public static function get_slack_webhook_url() {
			$slack_info = get_option( 'wordform_connect_slack_info', [] );
			if ( isset( $slack_info['webhookPostUrl'] ) && ! empty( $slack_info['webhookPostUrl'] ) ) {
				return [
					'webhookPostUrl' => $slack_info['webhookPostUrl'],
				];
			}

			return [];
		}

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

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

			if ( ! empty( $slack_webhook_url ) && filter_var( $slack_webhook_url, FILTER_VALIDATE_URL ) ) {
				$slack_info                   = [];
				$slack_info['webhookPostUrl'] = $slack_webhook_url;

				if ( update_option( 'wordform_connect_slack_info', $slack_info ) ) {
					self::$output['status']  = 'success';
					self::$output['reason']  = 'Slack webhook URL saved as option value.';
					self::$output['comment'] = 'Slack Webhook URL saved successfully.';
				} else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'Slack webhook URL did not change.';
					self::$output['comment'] = 'Slack Webhook URL saved successfully.';
				}

				self::$output['slackConfiguredInfoStatus'] = self::save_configured_slack_webhook_application( $slack_webhook_url );
				self::$output['configuredApplication']     = SftcyWordformConnectBase::get_configured_application_option_payload( 'slack' );
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Slack webhook URL not in valid format.';
				self::$output['comment'] = 'Valid Slack Webhook URL required.';
			}

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

		/**
		 * Keep record while configured Slack.
		 *
		 * @param string $slack_webhook_url Slack webhook URL.
		 * @return bool
		 */
		public static function save_configured_slack_webhook_application( $slack_webhook_url = '' ) {
			$application_slug = 'slack';
			$application_name = 'Slack';
			$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' => 'slack-message',
						'webhookPostUrl' => $slack_webhook_url,
					]
				);
				$data['configured_status'] = 'active';
				$update_result             = $wpdb->update( $table, $data, $where );
				if ( false === $update_result ) {
					return false;
				}
				return true;
			}

			$data['configured_info'] = wp_json_encode(
				[
					'reconfigured'  => 'no',
					'payloadFormat' => 'slack-message',
					'webhookPostUrl' => $slack_webhook_url,
				]
			);

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

		/**
		 * Ajax call.
		 * Store Slack connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_slack_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 ) ) {
						$slack_info = self::get_slack_webhook_url();
						if ( $slack_info && isset( $slack_info['webhookPostUrl'] ) && ! empty( $slack_info['webhookPostUrl'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'webhookPostUrl'      => $slack_info['webhookPostUrl'],
								'payloadFormat'       => 'slack-message',
								'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']              = 'Slack connected successfully.';
								self::$output['comment']             = 'Slack 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 Slack connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Slack Webhook URL missing.';
							self::$output['comment'] = 'Slack 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 into Slack incoming webhook.
		 *
		 * @param array  $payload Slack payload.
		 * @param string $slack_webhook_url Slack webhook URL.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_slack_webhook( $payload = [], $slack_webhook_url = '' ) {
			$slack_info                    = [];
			$slack_info['applicationSlug'] = 'slack';

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

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

			$response = wp_remote_post(
				$slack_webhook_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 ) ) {
				$slack_info['status']       = 'fail';
				$slack_info['reason']       = 'Slack request failed.';
				$slack_info['requestError'] = $response->get_error_message();
				$slack_info['comment']      = 'Slack Webhook request could not be completed.';
				return $slack_info;
			}

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

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

			return $slack_info;
		}

		/**
		 * Check configured_status of Slack application.
		 *
		 * @return bool
		 */
		public static function is_slack_configured_status_active() {
			$application_slug = 'slack';

			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
}
