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

if ( ! class_exists( 'SftcyWordformConnectZapier' ) ) {
	class SftcyWordformConnectZapier {
		private static $initiated                          = false;
		public static $output 							   = [];
		public static $zapier_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() {
			// Enqueue scripts
			// add_action( 'admin_enqueue_scripts', array( __CLASS__, 'wordform_admin_connect_page_required_scripts' ) );
			
		    // Ajax : Calls
			
			add_action( 'wp_ajax_wordform_connect_save_zapier_data_as_wp_option_data', array( __CLASS__, 'wordform_connect_save_zapier_data_as_wp_option_data' ) );	
			add_action( 'wp_ajax_save_zapier_webhook_application', array( __CLASS__, 'save_zapier_webhook_application' ) );	
			add_action( 'wp_ajax_wordform_connect_create_zapier_with_form_fields', array( __CLASS__, 'wordform_connect_create_zapier_with_form_fields' ) );				
			// add_action( 'wp_ajax_wordform_connect_reconnect_googlesheet_with_form_fields', array( __CLASS__, 'wordform_connect_reconnect_googlesheet_with_form_fields' ) );						
						
			self::$initiated = true;
		}
		

		/**
		 * Get Zapier information data
		 * Zapier data stored as option data varibale 'wordform_connect_zapier_info'		 
		 * @return array
		 */
		public static function get_zapier_webhook_url() {
			$zapier_info = get_option('wordform_connect_zapier_info', [] );
			$zapierinfo = [];
			if ( isset( $zapier_info['webhookPostUrl'] ) && ! empty( $zapier_info['webhookPostUrl'] ) ) {
				$zapierinfo['webhookPostUrl'] = $zapier_info['webhookPostUrl'];								
				return $zapierinfo;
			}
			return [];
		}
		
		/**
         * Ajax request
		 * Store zapier information data as option data into 'wordform_connect_zapier_info' option variable		 		 		 
		 * @return json object
		 */
		public static function wordform_connect_save_zapier_data_as_wp_option_data() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );

			// print_r( $_POST['params'] );
			// exit();

			$zapier_webhook_url =  isset( $_POST['params']['zapierWebhookUrl'] )? esc_url( $_POST['params']['zapierWebhookUrl'] ) : '';            
			self::$output = [];			
			$zapier_info = self::get_zapier_webhook_url();			
			if ( ! empty( $zapier_webhook_url ) && filter_var( $zapier_webhook_url, FILTER_VALIDATE_URL ) ) {
				$zapier_info['webhookPostUrl'] = trim( $zapier_webhook_url );				
				if ( update_option( 'wordform_connect_zapier_info', $zapier_info ) ) {		
					self::$output['status']  = 'success';
					self::$output['reason']  = 'Zapier webhook URL saved as option value.';
					self::$output['comment'] = 'Zapier Webhook saved successfully.';
				}
				else {
					self::$output['status']  = 'warning';
					self::$output['reason']  = 'Zapier webhook URL not changed. Nothing changes.';
					// self::$output['comment'] = 'Nothing changes.';
					self::$output['comment'] = 'Zapier Webhook saved successfully.';
				}				
				// Save Application confgiured information
				self::$output['zapierConfiguredInfoStatus'] = self::save_configured_zapier_webhook_application( $zapier_webhook_url );
				self::$output['configuredApplication']      = SftcyWordformConnectBase::get_configured_application_option_payload( 'zapier' );
			}
			else {
				self::$output['status']  = 'fail';
				self::$output['reason']  = 'Zapier webhook URL not in valid format.';
				self::$output['comment'] = 'Zapier valid webhook URL required.';
			}
			echo wp_json_encode( self::$output , JSON_HEX_APOS );
			wp_die();
		}

		/**
		 * Keep record while configured Zapier
		 * If already record found then reconfiguring the Zapier application
		 * If exist then just update else add new record
		 * DB record field application_slug will be 'zapier'
		 * DB record field application_name will be 'Zapier'
		 * 
		 * @return integer
		 */
		public static function save_configured_zapier_webhook_application( $zapier_webhook_url = '' ) {
			$application_slug = 'zapier';
			$application_name = 'Zapier';							
			$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 ) {
				// return $query_results[0]['id'];
				$where = [ 'id' => $query_results[0]['id'] ];
				$configured_info = json_encode( ['reconfigured' => 'yes' , 'webhookPostUrl' => $zapier_webhook_url ] );
				$data['configured_info'] = $configured_info;
				$data['configured_status'] = 'active'; 
				return $wpdb->update( $table, $data, $where );
			}
			else {					
				$configured_info = json_encode( ['reconfigured' => 'no', 'webhookPostUrl' => $zapier_webhook_url ] );
				$data['configured_info'] = $configured_info;
				return $wpdb->insert( $table, $data );					
			}			
		}



		/**
		 * Ajax Call
		 * While Click on 'Connect' Button
		 * First Create Google Sheet as the name of Wordform name
		 * Then create header column names
		 * @since 1.0.0
		 * @return json object
		 */
		public static function wordform_connect_create_zapier_with_form_fields() {
			check_ajax_referer( 'scwordform_wpnonce', 'security' );
			// print_r( $_POST['params'] );
			// exit;
			self::$output = [];
			if ( isset( $_POST['params'] ) && array_filter( $_POST['params'] ) ) {
				$wordform_id = isset( $_POST['params']['wordFormID'] )? $_POST['params']['wordFormID'] : '';
				$application_slug = isset( $_POST['params']['applicationSlug'] )? $_POST['params']['applicationSlug'] : '';
				$wordform_name = isset( $_POST['params']['wordFormName'] )? $_POST['params']['wordFormName'] : '';

				$configured_application_id = isset( $_POST['params']['applicationID'] )? $_POST['params']['applicationID'] : '';
				$configured_application_name = isset( $_POST['params']['applicationName'] )? $_POST['params']['applicationName'] : '';
				
				if ( ! empty( $wordform_id ) && ! empty( $configured_application_id ) ) {
					$form_fields       = SftcyWordformBuildForm::wordform_get_field_names( $wordform_id );					
					// print_r( $form_fields );											
					// exit();
					if ( $form_fields && array_filter( $form_fields ) ) {						
						self::$output['formFields'] = $form_fields;						
						self::$output['formName'] = $wordform_name;	
						self::$output['isConnected'] = SftcyWordformConnectBase::is_wordform_with_application_connected( $configured_application_id, $wordform_id );
						self::$output['connectedApplicationSlug'] = $application_slug;
						// Get Zapier Webhook info					
						$zapier_info = self::get_zapier_webhook_url();						
						if ( $zapier_info && isset( $zapier_info['webhookPostUrl'] ) && ! empty( $zapier_info['webhookPostUrl'] ) ) {	
							$zapier_webhook_post_url = $zapier_info['webhookPostUrl'];
							$ch = curl_init();						
							curl_setopt($ch, CURLOPT_URL, $zapier_webhook_post_url );
							curl_setopt($ch, CURLOPT_POST, true);
							curl_setopt($ch, CURLOPT_POSTFIELDS, $form_fields );
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);							
							$response = curl_exec($ch);
							$curl_error = curl_error( $ch );
							$http_code  = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
							$response_data = json_decode( $response, true );
							$is_success   = false;
							if ( is_array( $response_data ) && isset( $response_data['status'] ) && 'success' === $response_data['status'] ) {
								$is_success = true;
							} elseif ( empty( $curl_error ) && $http_code >= 200 && $http_code < 300 ) {
								$is_success = true;
							}
							if ( $is_success ) {								
								self::$output['status'] = 'success';
								self::$output['requestId'] = is_array( $response_data ) && isset( $response_data['request_id'] ) ? $response_data['request_id'] : '';
								self::$output['reason'] = is_array( $response_data ) && isset( $response_data['status'] )
									? 'Zapier Server Connected Status: '. $response_data['status'] .''
									: 'Zapier webhook accepted the connection test request.';
								self::$output['comment'] = 'Connected Zapier Successfully.';
								// Create database record into 'scwordform_connects_data' Table
								$connection_info = json_encode(
									is_array( $response_data ) && array_filter( $response_data )
										? $response_data
										: [
											'status'    => 'success',
											'http_code' => $http_code,
											'response'  => is_string( $response ) ? substr( $response, 0, 1000 ) : '',
										]
								);
								$insertdata = [ 
												'configured_application_tbl_id' => $configured_application_id,
												'wordform_id' => $wordform_id,
												'connection_info' => $connection_info
												];
								self::$output['connectedInfoStored'] = SftcyWordformConnectBase::wordform_save_connected_application_info( $insertdata );			  									
							}
							else {
								self::$output['status'] = 'fail';								
								self::$output['reason'] = ! empty( $curl_error ) ? 'Zapier error: ' . $curl_error : 'Zapier error: ' . wp_json_encode( $response_data );
								self::$output['comment'] = 'Zapier server returned Error.';
							}		
						} // if ( $zapier_info && isset( $zapier_info['webhookPostUrl'] ) && ! empty( $zapier_info['webhookPostUrl'] ) )
						else {
								self::$output['status'] = 'fail';								
								self::$output['reason'] = 'Zapier Webhook Post URL missing.';
								self::$output['comment'] = 'Zapier Webhook URL not found. Please enter your Webhook URL and save.';
						}	
					} // if ( $form_fields && array_filter( $form_fields ) )
					else {
						self::$output['status'] = 'fail';
						self::$output['reason'] = 'WordForm form fields are not available.';
						self::$output['comment'] = 'WordForm Form fields not found.';
					}			

				} // if ( ! empty( $wordform_id ) && ! empty( $configured_application_id ) )
			} // if ( isset( $_POST['params'] ) && array_filter( $_POST['params'] ) )

			echo wp_json_encode( self::$output, JSON_HEX_AMP );
			wp_die();	
	    } // End function

		/**
		 * Send Forms data to Zapier Webhook Post
		 * @param $form_data array - user submitted form data - plain texts
		 * @param $zapier_webhook_post_url string webhook post URL
		 * @return mixed - array | boolean
		 */
		public static function wordform_send_forms_data_into_zapier_post_webhook( $form_data = [], $zapier_webhook_post_url = '' ) {			
			if ( $form_data && array_filter( $form_data ) ) {						
				$zapier_info = [];
				$zapier_info['applicationSlug'] = 'zapier';
				// Get Zapier Webhook info					
				//$zapier_info = self::get_zapier_webhook_url();						
				if ( isset( $zapier_webhook_post_url ) && ! empty( $zapier_webhook_post_url ) ) {	
					//$zapier_webhook_post_url = $zapier_info['webhookPostUrl'];
					$ch = curl_init();						
					curl_setopt($ch, CURLOPT_URL, $zapier_webhook_post_url );
					curl_setopt($ch, CURLOPT_POST, true);
					curl_setopt($ch, CURLOPT_POSTFIELDS, $form_data );
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);							
					$response = curl_exec($ch);
					$curl_error = curl_error( $ch );
					$http_code = (int) curl_getinfo( $ch, CURLINFO_HTTP_CODE );
					//var_dump( $curl_error );
					//var_dump( $response );
					$response_data = json_decode( $response, true );
					$is_success = false;
					if ( is_array( $response_data ) && isset( $response_data['status'] ) && 'success' === $response_data['status'] ) {
						$is_success = true;
					} elseif ( empty( $curl_error ) && $http_code >= 200 && $http_code < 300 ) {
						$is_success = true;
					}
					if ( $is_success ) {								
						$zapier_info['status']  = 'success';												
						$zapier_info['reason']  = 'Form submission data sent to Zapier zuccess.';
						$zapier_info['comment'] = 'Sent Form Data into Zapier Successfully.';
						$zapier_info['httpCode'] = $http_code;
					}
					else {
						$zapier_info['status']  = 'fail';
						$zapier_info['reason']  = 'Zapier response error.';								
						$zapier_info['zapierError']  =  $response_data;
						$zapier_info['curlError'] = $curl_error;
						$zapier_info['comment'] = 'Zapier server returned Error.May be Zapier Webhook not properly configured.';
					}		
				} 
				else {
						$zapier_info['status']  = 'fail';								
						$zapier_info['reason']  = 'Zapier Webhook Post URL missing.';
						$zapier_info['comment'] = 'Zapier Webhook URL not found during sending Form data.';
				}	
			return $zapier_info;	
			} 
		return false;	
		}
		/**
		 * Check 'configured_status' of the application is active or inactive
		 * @return boolean
		 */
		public static function is_zapier_configured_status_active() {
			$application_slug = 'zapier';			
			$data = [ 'application_slug' => $application_slug ];
			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'] ) && $query_results[0]['configured_status'] == 'active' )  {				
				return true;
			}
			else {
				return false;
			}
		}

	} // End class
}
