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

if ( ! class_exists( 'SftcyWordformConnectMake' ) ) {
	class SftcyWordformConnectMake {
		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_make_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_make_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_make_with_form_fields', [ __CLASS__, 'wordform_connect_create_make_with_form_fields' ] );
			self::$initiated = true;
		}

		public static function get_make_webhook_url() {
			$make_info = get_option( 'wordform_connect_make_info', [] );
			if ( isset( $make_info['webhookPostUrl'] ) && ! empty( $make_info['webhookPostUrl'] ) ) {
				return [
					'webhookPostUrl' => $make_info['webhookPostUrl'],
				];
			}

			return [];
		}

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

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

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

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

				self::$output['makeConfiguredInfoStatus'] = self::save_configured_make_webhook_application( $make_webhook_url );
				self::$output['configuredApplication']    = SftcyWordformConnectBase::get_configured_application_option_payload( 'make' );
			} else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Make webhook URL not in valid format.';
				self::$output['comment'] = 'Valid Make Webhook URL required.';
			}

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

		public static function save_configured_make_webhook_application( $make_webhook_url = '' ) {
			$application_slug = 'make';
			$application_name = 'Make';
			$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' => 'json',
					'webhookPostUrl'=> $make_webhook_url,
				]
			);

			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_make_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 ) ) {
						$make_info = self::get_make_webhook_url();
						if ( $make_info && isset( $make_info['webhookPostUrl'] ) && ! empty( $make_info['webhookPostUrl'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'webhookPostUrl'      => $make_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 );
							if ( false !== $db_result ) {
								self::$output['status']              = 'success';
								self::$output['formFields']          = $form_fields;
								self::$output['formName']            = $wordform_name;
								self::$output['reason']              = 'Make connected successfully.';
								self::$output['comment']             = 'Make 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 Make connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Make Webhook URL missing.';
							self::$output['comment'] = 'Make 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();
		}

		public static function wordform_send_forms_data_into_make_post_webhook( $payload = [], $make_webhook_url = '' ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'make';

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

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

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

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

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

			return $send_info;
		}

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