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

if ( ! class_exists( 'SftcyWordformConnectAirtable' ) ) {
	class SftcyWordformConnectAirtable {
		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_airtable_data_as_wp_option_data', [ __CLASS__, 'wordform_connect_save_airtable_data_as_wp_option_data' ] );
			add_action( 'wp_ajax_wordform_connect_create_airtable_with_form_fields', [ __CLASS__, 'wordform_connect_create_airtable_with_form_fields' ] );
			add_action( 'wp_ajax_wordform_connect_fetch_airtable_tables', [ __CLASS__, 'wordform_connect_fetch_airtable_tables' ] );

			self::$initiated = true;
		}

		/**
		 * Get Airtable configured information from option table.
		 *
		 * @return array
		 */
		public static function get_airtable_configured_info() {
			$airtable_info = get_option( 'wordform_connect_airtable_info', [] );
			if ( isset( $airtable_info['accessToken'], $airtable_info['baseId'], $airtable_info['tableName'] ) && ! empty( $airtable_info['accessToken'] ) && ! empty( $airtable_info['baseId'] ) && ! empty( $airtable_info['tableName'] ) ) {
				return [
					'accessToken' => $airtable_info['accessToken'],
					'baseId'      => $airtable_info['baseId'],
					'tableName'   => $airtable_info['tableName'],
				];
			}

			return [];
		}

		/**
		 * Ajax request.
		 * Store Airtable access token, base ID, and table name as option data.
		 *
		 * @return void
		 */
		public static function wordform_connect_save_airtable_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$access_token = isset( $_POST['params']['airtableAccessToken'] ) ? sanitize_text_field( trim( $_POST['params']['airtableAccessToken'] ) ) : '';
			$base_id      = isset( $_POST['params']['airtableBaseId'] ) ? sanitize_text_field( trim( $_POST['params']['airtableBaseId'] ) ) : '';
			$table_name   = isset( $_POST['params']['airtableTableName'] ) ? sanitize_text_field( trim( $_POST['params']['airtableTableName'] ) ) : '';
			self::$output = [];

			if ( empty( $access_token ) || empty( $base_id ) || empty( $table_name ) ) {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Airtable credentials are missing.';
				self::$output['comment'] = 'Airtable access token, Base ID, and Table Name are required.';
			} else {
				$airtable_info = [
					'accessToken' => $access_token,
					'baseId'      => $base_id,
					'tableName'   => $table_name,
				];

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

				self::$output['airtableConfiguredInfoStatus'] = self::save_configured_airtable_application( $airtable_info );
				self::$output['configuredApplication'] = SftcyWordformConnectBase::get_configured_application_option_payload( 'airtable' );
			}

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

		/**
		 * Save configured Airtable application into configured applications table.
		 *
		 * @param array $airtable_info Airtable configuration.
		 * @return bool
		 */
		public static function save_configured_airtable_application( $airtable_info = [] ) {
			if ( ! is_array( $airtable_info ) || ! isset( $airtable_info['accessToken'], $airtable_info['baseId'], $airtable_info['tableName'] ) ) {
				return false;
			}

			$application_slug = 'airtable';
			$application_name = 'Airtable';
			$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' => 'airtable-record',
					'accessToken'   => $airtable_info['accessToken'],
					'baseId'        => $airtable_info['baseId'],
					'tableName'     => $airtable_info['tableName'],
				]
			);

			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 Airtable connection record against selected WordForm.
		 *
		 * @return void
		 */
		public static function wordform_connect_create_airtable_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 ) ) {
						$airtable_info = self::get_airtable_configured_info();
						if ( isset( $airtable_info['accessToken'], $airtable_info['baseId'], $airtable_info['tableName'] ) && ! empty( $airtable_info['accessToken'] ) && ! empty( $airtable_info['baseId'] ) && ! empty( $airtable_info['tableName'] ) ) {
							$connection_info = [
								'applicationName'     => $configured_application_name,
								'formName'            => $wordform_name,
								'formFields'          => $form_fields,
								'payloadFormat'       => 'airtable-record',
								'accessToken'         => $airtable_info['accessToken'],
								'baseId'              => $airtable_info['baseId'],
								'tableName'           => $airtable_info['tableName'],
								'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']              = 'Airtable connected successfully.';
								self::$output['comment']             = 'Airtable 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 Airtable connection record.';
							}
						} else {
							self::$output['status']  = 'fail';
							self::$output['reason']  = 'Airtable configuration missing.';
							self::$output['comment'] = 'Airtable access token, Base ID, or Table Name not found. Please save Airtable 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 Airtable tables for the selected base.
		 *
		 * @return void
		 */
		public static function wordform_connect_fetch_airtable_tables() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			$access_token = isset( $_POST['params']['airtableAccessToken'] ) ? sanitize_text_field( trim( $_POST['params']['airtableAccessToken'] ) ) : '';
			$base_id      = isset( $_POST['params']['airtableBaseId'] ) ? sanitize_text_field( trim( $_POST['params']['airtableBaseId'] ) ) : '';
			$response     = self::get_airtable_tables( $access_token, $base_id );

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

		/**
		 * Fetch Airtable tables.
		 *
		 * @param string $access_token
		 * @param string $base_id
		 * @return array
		 */
		private static function get_airtable_tables( $access_token = '', $base_id = '' ) {
			$access_token = sanitize_text_field( trim( (string) $access_token ) );
			$base_id      = sanitize_text_field( trim( (string) $base_id ) );

			if ( empty( $access_token ) || empty( $base_id ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Please enter a valid Airtable access token and Base ID first.',
					'airtable',
					[
					'fixTip' => 'Use a Personal Access Token with metadata and record access to the selected base.',
						'logStage' => 'verify_load',
					]
				);
			}

			$response = wp_remote_get(
				'https://api.airtable.com/v0/meta/bases/' . rawurlencode( $base_id ) . '/tables',
				[
					'timeout' => 20,
					'headers' => [
						'Authorization' => 'Bearer ' . $access_token,
						'Accept'        => 'application/json',
					],
				]
			);

			if ( is_wp_error( $response ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'Airtable tables could not be loaded right now: ' . $response->get_error_message(),
					'airtable',
					[
					'fixTip' => 'Check outbound HTTPS access from this site, then confirm the token and Base ID are copied exactly.',
						'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      = 'Airtable credentials could not be verified, or the token does not have table metadata access.';
				if ( ! empty( $remote_error ) ) {
					$comment .= ' ' . $remote_error;
				}

				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					$comment,
					'airtable',
					[
						'fixTip'            => 'Make sure the token includes schema and record permissions for this base, then try Verify & Load Tables again.',
						'responseStatusCode'=> $status_code,
						'logStage'          => 'verify_load',
					]
				);
			}

			$resources = [];
			if ( ! empty( $json['tables'] ) && is_array( $json['tables'] ) ) {
				foreach ( $json['tables'] as $table ) {
					if ( empty( $table['name'] ) ) {
						continue;
					}
					$resources[] = [
						'value' => sanitize_text_field( $table['name'] ),
						'label' => sanitize_text_field( $table['name'] ),
					];
				}
			}

			if ( empty( $resources ) ) {
				return SftcyWordformConnectBase::build_connect_feedback_payload(
					'fail',
					'No Airtable tables were found for this base.',
					'airtable',
					[
						'fixTip' => 'Confirm the Base ID is correct and that the token can read table metadata for that base.',
						'logStage' => 'verify_load',
					]
				);
			}

			return SftcyWordformConnectBase::build_connect_feedback_payload(
				'success',
				'Airtable tables loaded successfully.',
				'airtable',
				[
					'resources' => $resources,
				]
			);
		}

		/**
		 * Send form submission data into Airtable by creating a record.
		 * Airtable table field names should match WordForm field labels.
		 *
		 * @param array $forms_data Processed form fields.
		 * @param array $airtable_info Airtable configuration.
		 * @return array
		 */
		public static function wordform_send_forms_data_into_airtable( $forms_data = [], $airtable_info = [] ) {
			$send_info                    = [];
			$send_info['applicationSlug'] = 'airtable';

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

			$access_token = isset( $airtable_info['accessToken'] ) ? sanitize_text_field( (string) $airtable_info['accessToken'] ) : '';
			$base_id      = isset( $airtable_info['baseId'] ) ? sanitize_text_field( (string) $airtable_info['baseId'] ) : '';
			$table_name   = isset( $airtable_info['tableName'] ) ? sanitize_text_field( (string) $airtable_info['tableName'] ) : '';

			if ( empty( $access_token ) || empty( $base_id ) || empty( $table_name ) ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Airtable configuration incomplete.';
				$send_info['comment'] = 'Airtable access token, Base ID, or Table Name missing.';
				return $send_info;
			}

			$fields_map = SftcyWordformConnectBase::extract_submission_fields_map( $forms_data );
			if ( ! $fields_map ) {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Submission fields map is empty.';
				$send_info['comment'] = 'Could not build Airtable fields map from form submission.';
				return $send_info;
			}

			$endpoint_url = sprintf(
				'https://api.airtable.com/v0/%1$s/%2$s',
				rawurlencode( $base_id ),
				rawurlencode( $table_name )
			);

			$request_body = [
				'records'  => [
					[
						'fields' => $fields_map,
					],
				],
				'typecast' => true,
			];

			$response = wp_remote_post(
				$endpoint_url,
				[
					'timeout' => 20,
					'headers' => [
						'Content-Type'  => 'application/json; charset=utf-8',
						'Authorization' => 'Bearer ' . $access_token,
					],
					'body'    => wp_json_encode( $request_body ),
				]
			);

			if ( is_wp_error( $response ) ) {
				$send_info['status']       = 'fail';
				$send_info['reason']       = 'Airtable request failed.';
				$send_info['requestError'] = $response->get_error_message();
				$send_info['comment']      = 'Airtable 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 Airtable.';
				$send_info['comment'] = 'Airtable record created successfully.';
				if ( isset( $response_json['records'][0]['id'] ) ) {
					$send_info['recordId'] = sanitize_text_field( $response_json['records'][0]['id'] );
				}
			} else {
				$send_info['status']  = 'fail';
				$send_info['reason']  = 'Airtable response status indicates failure.';
				$send_info['comment'] = 'Airtable API returned non-success HTTP status.';
				if ( is_array( $response_json ) ) {
					if ( isset( $response_json['error']['type'] ) ) {
						$send_info['responseErrorType'] = sanitize_text_field( $response_json['error']['type'] );
					}
					if ( isset( $response_json['error']['message'] ) ) {
						$send_info['responseErrorMessage'] = substr( sanitize_textarea_field( (string) $response_json['error']['message'] ), 0, 500 );
					}
				} else {
					$send_info['responseBody'] = substr( sanitize_textarea_field( (string) $response_body ), 0, 500 );
				}
			}

			return $send_info;
		}

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

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