<?php
global $arf_paypal;

class arforms_paypal_integration {

	public function __construct(){
		add_action( 'arfaftercreateentry', array( $this, 'arf_paypal_submission' ), 100, 2 );
		add_action( 'wp_ajax_arf_paypal_save_settings', array( $this, 'arf_paypal_save_settings_callback' ) );
		add_action('arf_afterdisplay_form', array($this, 'paypal_button_ui_dynamic'), 20, 1);

		add_action('wp_ajax_arf_paypal_check_submit_conditions', array($this, 'ajax_check_submit_conditions'));
    	add_action('wp_ajax_nopriv_arf_paypal_check_submit_conditions', array($this, 'ajax_check_submit_conditions'));

		add_action( 'arf_after_destroy_form_entry', array( $this, 'arf_remote_transactions_with_form_entry') );
	}

	function arf_remote_transactions_with_form_entry( $entry_id ){
		global $arf_paypal, $wpdb;
		$wpdb->delete(
			$arf_paypal->db_paypal_order,
			[
				'entry_id' => $entry_id
			]
		);
	}

	function arf_paypal_submission( $entry_id, $form_id ) {

		global $wpdb, $arfliterecordmeta, $arflitenotifymodel, $arformsmain, $arfsettings, $tbl_arf_forms, $tbl_arf_entry_values, $arf_debug_log_id, $arf_paypal, $arf_paypal;

		$form_data_row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $arf_paypal->db_paypal_forms . ' WHERE form_id = %d', $form_id ) ); //phpcs:ignore
		if ( ! $form_data_row ) { return; }
	
		$options = maybe_unserialize( $form_data_row->options );
		
		$form_data_row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $arf_paypal->db_paypal_forms . ' WHERE form_id = %d', $form_id ) ); //phpcs:ignore
		$options = maybe_unserialize( $form_data_row->options );
		$payment_gateway_type = isset( $options['payment_gateway_type'] ) ? $options['payment_gateway_type'] : 'default';

		if ( $payment_gateway_type === 'popup' ) {
			if ( isset( $_POST['arf_paypal_transaction_id'] ) && ! empty( $_POST['arf_paypal_transaction_id'] ) ) { //phpcs:ignore
		
				$amount_field_id = !empty($options['amount']) ? $options['amount'] : 0; //phpcs:ignore
				$amount = $wpdb->get_var( $wpdb->prepare("SELECT entry_value FROM {$wpdb->prefix}arf_entry_values WHERE entry_id = %d AND field_id = %d", $entry_id, $amount_field_id) ); //phpcs:ignore
		
				$payer_fname = isset($_POST['arf_paypal_payer_fname']) ? sanitize_text_field($_POST['arf_paypal_payer_fname']) : ''; //phpcs:ignore
				$payer_lname = isset($_POST['arf_paypal_payer_lname']) ? sanitize_text_field($_POST['arf_paypal_payer_lname']) : ''; //phpcs:ignore
				$payer_full_name = trim($payer_fname . ' ' . $payer_lname);
				$txn_id = sanitize_text_field( $_POST['arf_paypal_transaction_id'] ); //phpcs:ignore
	
				$payment_type_val = isset($options['payment_type']) ? $options['payment_type'] : 'product_service';
				$payment_type_val_int = ($payment_type_val === 'donation') ? 1 : 0;
		
				$insert_array = array(
					'item_name'      => isset($options['title']) ? $options['title'] : '', 
					'payer_name'     => $payer_full_name,
					'payment_type'   => $payment_type_val_int,
					'txn_id'         => $txn_id,
					'payment_status' => sanitize_text_field( $_POST['arf_paypal_payment_status'] ), //phpcs:ignore
					'mc_gross'       => floatval( $amount ),
					'mc_currency'    => isset( $options['currency'] ) ? $options['currency'] : 'USD',
					'quantity'    	 => '1',
					'payer_email'    => sanitize_email( $_POST['arf_paypal_payer_email'] ), //phpcs:ignore
					'user_id'        => get_current_user_id(),
					'payment_date'   => isset( $_POST['arf_paypal_payment_date'] ) ? sanitize_text_field($_POST['arf_paypal_payment_date']) : '', //phpcs:ignore
					'entry_id'       => $entry_id,
					'form_id'        => $form_id,
					'created_at'     => current_time( 'mysql' ),
					'is_verified'    => 1,
				);
				
				$db_result = $wpdb->insert( $arf_paypal->db_paypal_order, $insert_array );
				do_action( 'arf_after_paypal_successful_paymnet', $form_id, $entry_id, $txn_id );
		
				$log_data = ['success' => ($db_result !== false) ? 'true' : 'false', 'message' => 'Popup payment successful. Payment info logged.', 'details' => $insert_array];
				do_action('arforms_debug_log_entry', 'arflite_paypal_debug_log', 'Popup Payment Processed', 'arflite_paypal_data', $log_data, $arf_debug_log_id);
		
				$admin_email_notification_data = get_option( 'arf_paypal_admin_email_notification_' . $entry_id . '_' . $form_id );
				
				if( !empty( $admin_email_notification_data ) ){
	
					$admin_data = json_decode( $admin_email_notification_data, true );
					foreach( $admin_data['arf_admin_emails'] as $email ){
						if( $arformsmain->arforms_is_pro_active() ){ 
							global $arnotifymodel; 
							$arnotifymodel->send_notification_email_user( $email, $admin_data['arf_admin_subject'], $admin_data['arf_admin_mail_body'], $admin_data['arf_admin_reply_to'], $admin_data['arf_admin_reply_to_name'], $admin_data['arf_admin_plain_text'], $admin_data['arf_admin_attachments'], false, false, true, true, $admin_data['arf_admin_reply_to_email'], $admin_data['arf_admin_cc_emails'], $admin_data['arf_admin_bcc_emails'] ); 
						}
					}
					
					delete_option( 'arf_paypal_admin_email_notification_' . $entry_id . '_' . $form_id );
				}
		
				$user_email_notification_data = get_option( 'arf_paypal_user_email_notification_' . $entry_id . '_' . $form_id );
				
				if( !empty( $user_email_notification_data ) ){
					
					$user_data = json_decode( $user_email_notification_data, true );
					if( $arformsmain->arforms_is_pro_active() ){ 
						global $arnotifymodel; 
						$arnotifymodel->send_notification_email_user( $user_data['to'], $user_data['subject'], $user_data['message'], $user_data['reply_to'], $user_data['reply_to_name'], $user_data['plain_text'], $user_data['attachments'], $user_data['return_value'], $user_data['use_only_smtp'], true, false, $user_data['nreply_to'], (isset($user_data['cc_email']) ? $user_data['cc_email'] : ''), (isset($user_data['bcc_email']) ? $user_data['bcc_email'] : '') ); 
					}
					
					delete_option( 'arf_paypal_user_email_notification_' . $entry_id . '_' . $form_id );
				}
		
				if ( ( isset( $options['notification'] ) && $options['notification'] ) || ( isset( $options['user_notification'] ) && $options['user_notification'] ) ) {
					$arf_form_object = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $tbl_arf_forms . ' WHERE id = %d', $form_id ) );
					$arf_options   = maybe_unserialize( $arf_form_object->options );
					$admin_email = !is_email($arf_options['reply_to']) ? $arfsettings->reply_to : $arf_options['reply_to'];
					$reply_to_name = !empty($arf_options['ar_admin_from_name']) ? $arf_options['ar_admin_from_name'] : get_bloginfo('name');
					
					if ( isset( $options['notification'] ) && $options['notification'] ) {
						$subject = __( 'Payment received on', 'ARForms' ) . ' ' . get_option('blogname');
						$message = !empty($options['email_content']) ? nl2br($options['email_content']) : $arf_paypal->defalut_email_content();
						$message = str_replace( '[transaction_id]', $insert_array['txn_id'], $message );
						$message = str_replace( '[amount]', $insert_array['mc_gross'], $message );
						$message = str_replace( '[currency]', $insert_array['mc_currency'], $message );
						$message = str_replace( '[payer_email]', $insert_array['payer_email'], $message );
						$message = str_replace( '[payer_id]', $insert_array['user_id'], $message );
						$message = str_replace( '[payer_name]', $insert_array['payer_name'], $message );
						$message = str_replace( '[payer_fname]', $payer_fname, $message );
						$message = str_replace( '[payer_lname]', $payer_lname, $message );
						$message = str_replace( '[payment_date]', $insert_array['payment_date'], $message );
						$message = str_replace( '[site_name]', get_bloginfo('name'), $message );
						
						if($arformsmain->arforms_is_pro_active()){ 
							global $arnotifymodel; 
							$arnotifymodel->send_notification_email_user($admin_email, $subject, $message, $admin_email, $reply_to_name, false, array(), false, false, false, true, $admin_email); 
						}
					}
		
					if ( isset( $options['user_notification'] ) && $options['user_notification'] ) {
						$email_field_id = isset($options['email']) ? $options['email'] : 0;
						if($email_field_id){
							$user_email = $wpdb->get_var( $wpdb->prepare("SELECT entry_value FROM {$tbl_arf_entry_values} WHERE field_id = %d AND entry_id = %d", $email_field_id, $entry_id) );
							if( is_email($user_email) ){
								$user_from_name     = !empty($arf_options['ar_user_from_name']) ? $arf_options['ar_user_from_name'] : get_bloginfo('name');
								$user_from_email    = !empty($arf_options['ar_user_from_email']) ? $arf_options['ar_user_from_email'] : $admin_email;
								$user_reply_to_email= !empty($arf_options['ar_user_nreplyto_email']) ? $arf_options['ar_user_nreplyto_email'] : $user_from_email;
	
								$subject = __( 'Payment received on', 'ARForms' ) . ' ' . get_option('blogname');
								$message = !empty($options['user_email_content']) ? nl2br($options['user_email_content']) : $arf_paypal->user_defalut_email_content();
								$message = str_replace( '[transaction_id]', $insert_array['txn_id'], $message );
								$message = str_replace( '[amount]', $insert_array['mc_gross'], $message );
								$message = str_replace( '[currency]', $insert_array['mc_currency'], $message );
								$message = str_replace( '[payer_email]', $insert_array['payer_email'], $message );
								$message = str_replace( '[payer_id]', $insert_array['user_id'], $message );
								$message = str_replace( '[payer_name]', $insert_array['payer_name'], $message );
								$message = str_replace( '[payer_fname]', $payer_fname, $message );
								$message = str_replace( '[payer_lname]', $payer_lname, $message );
								$message = str_replace( '[payment_date]', $insert_array['payment_date'], $message );
								$message = str_replace( '[site_name]', get_bloginfo('name'), $message );
								
								if ( $arformsmain->arforms_is_pro_active() ) {
									global $arnotifymodel;
									$arnotifymodel->send_notification_email_user($user_email, $subject, $message, $user_from_email, $user_from_name, false, array(), false, false, true, false, $user_reply_to_email);
								}
							}
						}
					}
				}
				return; 
			}
		}

		if ( $payment_gateway_type === 'default' ) {

			$form_data = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM  ' . $arf_paypal->db_paypal_forms . ' WHERE form_id = %d', $form_id ) );//phpcs:ignore 
			

			if ( count( $form_data ) > 0 ) {

				$form_data = $form_data[0];

				$options = maybe_unserialize( $form_data->options );

				$paypal_field_amount = '';

				if ( '' != $options['amount'] ) {
					$paypal_field_amount = $options['amount'];
				}

				global $paypal_fields;
				$paypal_fields = array(
					'first_name' => $options['first_name'],
					'last_name'  => $options['last_name'],
					'email'      => $options['email'],
					'address1'   => $options['address'],
					'address2'   => $options['address_2'],
					'city'       => $options['city'],
					'state'      => $options['state'],
					'zip'        => $options['zip'],
					'country'    => $options['country'],
				);

				if ( ! isset( $paypal_field_amount ) || '' == $paypal_field_amount ) {
					return;
				}

				$entry_ids = array( $entry_id );
				$values    = $arfliterecordmeta->arflitegetAll( 'it.field_id != 0 and it.entry_id in ( ' . implode( ',', $entry_ids ) . ')', ' ORDER BY fi.id' );

				$amount        = '';
				$paypal_values = array();

				$mapped_conditional_field = array();

				$mapped_field_values = array();
				if ( count( $values ) > 0 ) {
					foreach ( $values as $value ) {
						if ( $value->field_id == $paypal_field_amount ) {
							$amount = $value->entry_value;
						}

						if ( $mapped_conditional_field ) {
							foreach ( $mapped_conditional_field as $rule_field ) {
								if ( $rule_field == $value->field_id ) {
									$mapped_field_values[ $value->field_id ] = $value->entry_value;
								}
							}
						}

						foreach ( $paypal_fields as $paypal_field_key => $paypal_field_id ) {
							if ( $value->field_id == $paypal_field_id ) {
								$paypal_values[ $paypal_field_key ] = $value->entry_value;
							}
						}
					}
				}

				$amount = isset( $amount ) ? $amount : 0;

				$sandbox = ( isset( $options['paypal_mode'] ) && 0 == $options['paypal_mode'] ) ? 'sandbox.' : '';

				$currency = ( isset( $options['currency'] ) ) ? $options['currency'] : 'USD';

				$merchant_email = ( isset( $options['merchant_email'] ) ) ? esc_attr( $options['merchant_email'] ) : '';

				$item_name = ( isset( $options['title'] ) ) ? esc_attr( $options['title'] ) : '';

				$cancel_url = ( isset( $options['cancel_url'] ) ) ? esc_attr( $options['cancel_url'] ) : '';

				$continue_text = ( isset( $options['continue_label'] ) ) ? esc_attr( $options['continue_label'] ) : '';

				if ( is_numeric( $amount ) && 0 == $amount ) {
					return;
				}

				$amount = str_replace(".", ".", $amount);

				if ( '' != $merchant_email ) {
					global $tbl_arf_entries;

					$pageURL = 'http';
					if ( isset( $_SERVER['HTTPS'] ) && 'on' == $_SERVER['HTTPS'] ) {
						$pageURL .= 's';
					}
					$pageURL .= '://';
					$_SERVER['SERVER_NAME'] = isset($_SERVER['SERVER_NAME']) ? sanitize_text_field($_SERVER['SERVER_NAME']) : '';
					$_SERVER['REQUEST_URI'] = isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '';
					if ( isset( $_SERVER['SERVER_PORT'] ) && '80' != $_SERVER['SERVER_PORT'] ) {
						$pageURL .= sanitize_text_field($_SERVER['SERVER_NAME']) . ':' . sanitize_text_field($_SERVER['SERVER_PORT']) . sanitize_text_field($_SERVER['REQUEST_URI']);
					} else {
						$pageURL .= sanitize_text_field($_SERVER['SERVER_NAME']) . sanitize_text_field($_SERVER['REQUEST_URI']);
					}

					$wpdb->update( $tbl_arf_entries, array( 'form_id' => '0' ), array( 'id' => $entry_id ) );

					$_SESSION['arf_return_url'][ $form_id ] = $pageURL;

					if ( is_numeric( $amount ) ) {
						$amount = number_format( (float) $amount, 2 );
					}

					if ( is_numeric( $amount ) && ( 'HUF' == $currency || 'JPY' == $currency || 'TWD' == $currency ) ) {
						$amount = (float) $amount;
						$amount = floor( $amount );
					}

					$amount = preg_replace( '/\,/', '', $amount );

					if ( ! isset( $cancel_url ) || empty( $cancel_url ) ) {
						$cancel_url = get_home_url();
					}

					if ( ! isset( $continue_text ) || empty( $continue_text ) ) {
						$continue_text = esc_html__( 'Click here to continue', 'ARForms' );
					}

					$payment_type_val_int = 0;
					if ( isset( $options['payment_type'] ) ) {
						if ( 'donation' == $options['payment_type'] ) {
							$payment_type_val_int = 1;
						} else {
							$payment_type_val_int = 0;
						}
					} else {
						$payment_type_val_int = 0;
					}
					$payment_type = $payment_type_val_int;

					$payment_type_val = ( isset( $options['payment_type'] ) ) ? $options['payment_type'] : 'product_service';

					if ( 'donation' == $payment_type_val ) {
						$cmd = '_donations';
					} elseif ( 'product_service' == $payment_type_val ) {
						$cmd = '_xclick';
					} else {
						$cmd = '_xclick';
					}

					$arf_pyapal_home_url = get_home_url() . '/';

					if ( strstr( $arf_pyapal_home_url, '?' ) ) {
						$apyapal_return_url    = $arf_pyapal_home_url . '&arf_page=arforms_paypal_response&custom=' . $entry_id . '|' . $form_id . '|' . $payment_type;
						$arf_pyapal_notify_url = $arf_pyapal_home_url . '&arf_page=arforms_paypal_api';
					} else {
						$apyapal_return_url    = $arf_pyapal_home_url . '?arf_page=arforms_paypal_response&custom=' . $entry_id . '|' . $form_id . '|' . $payment_type;
						$arf_pyapal_notify_url = $arf_pyapal_home_url . '?arf_page=arforms_paypal_api';
					}

					$arforms_all_settings = $arformsmain->arforms_global_option_data();
					$arflitesettings = json_decode( wp_json_encode( $arforms_all_settings['general_settings'] ) );
					
					if(1 == $arflitesettings->form_submit_type){
						$return['conf_method'] = 'addon';
					}
					
					$message          = '';
					$is_normal_submit = '';

					if ( 1 != $arflitesettings->form_submit_type ) {

						global $arf_paypal_assets_version;
						$is_normal_submit = 'arf_paypal_form_normal';
						wp_print_scripts( 'jquery' );
						wp_register_script( 'arf_paypal_front_js', ARFLITEURL . '/integrations/Payments/PayPal/js/arf_paypal_front.js', array(), $arf_paypal_assets_version );
						wp_print_scripts( 'arf_paypal_front_js' );
					}

					$message .= '<form name="_xclick" class="' . $is_normal_submit . '" id="arf_paypal_form" action="https://www.' . $sandbox . 'paypal.com/cgi-bin/webscr" method="post">
								<input type="hidden" name="cmd" value="' . $cmd . '">
								<input type="hidden" name="charset" value="UTF-8">
								<input type="hidden" name="business" value="' . $merchant_email . '">
								<input type="hidden" name="notify_url" value="' . esc_url( $arf_pyapal_notify_url ) . '">
								<input type="hidden" name="return" value="' . esc_url( $apyapal_return_url ) . '">
								<input type="hidden" name="cancel_return" value="' . $cancel_url . '">
							
								<input type="hidden" name="currency_code" value="' . $currency . '" />
								<input type="hidden" name="item_name" value="' . $item_name . '">
								
								<input type="hidden" name="custom" value="' . $entry_id . '|' . $form_id . '|' . $payment_type . '">
								
								<input type="hidden" name="cbt" value="' . $continue_text . '">
								<input type="hidden" name="rm" value="2">
								<input type="hidden" name="amount" value="' . $amount . '">';
				
					if ( isset( $options['shipping_info'] ) && 1 == $options['shipping_info'] ) {
						$message .= '<input type="hidden" name="first_name" value="' . ( isset( $paypal_values['first_name'] ) ? $paypal_values['first_name'] : '' ) . '" />
						<input type="hidden" name="last_name" value="' . ( isset( $paypal_values['last_name'] ) ? $paypal_values['last_name'] : '' ) . '" />
						<input type="hidden" name="email" value="' . ( isset( $paypal_values['email'] ) ? $paypal_values['email'] : '' ) . '" />
						<input type="hidden" name="address1" value="' . ( isset( $paypal_values['address1'] ) ? $paypal_values['address1'] : '' ) . '" />
						<input type="hidden" name="address2" value="' . ( isset( $paypal_values['address2'] ) ? $paypal_values['address2'] : '' ) . '" />
						<input type="hidden" name="city" value="' . ( isset( $paypal_values['city'] ) ? $paypal_values['city'] : '' ) . '" />
						<input type="hidden" name="state" value="' . ( isset( $paypal_values['state'] ) ? $paypal_values['state'] : '' ) . '" />
						<input type="hidden" name="zip" value="' . ( isset( $paypal_values['zip'] ) ? $paypal_values['zip'] : '' ) . '" />
						<input type="hidden" name="country" value="' . ( isset( $paypal_values['country'] ) ? $paypal_values['country'] : '' ) . '" />';
					}

					$message .= '</form>';

					$return['message'] = $message;

					

					$return = apply_filters( 'arflite_reset_built_in_captcha', $return, $_POST );//phpcs:ignore 

					if ( $arflitesettings->form_submit_type == 1 ) {
						echo wp_json_encode( $return );
					} else {
						echo esc_attr($message);
					}

					exit;
				}
			}
		}
	}
	
	function arf_paypal_save_settings_callback() {
		global $wpdb, $arfliteform, $armainhelper, $arf_paypal_version, $arflitefieldhelper, $arflitenotifymodel, $arf_paypal, $arflitefield, $tbl_arf_forms;

		$check_cap = $arf_paypal->arf_paypal_check_user_cap( 'arfpaypalconfiguration', true );

		if ( 'success' != $check_cap ) {
			$user_cap = json_decode( $check_cap, true );
			echo json_encode(
				array(
					'success' => false,
					'message' => $user_cap[0],
				)
			);
			die;
		}

		if ( isset( $_REQUEST['arfaction'] ) && 'edit' == $_REQUEST['arfaction'] ) {
			$id = isset( $_REQUEST['id'] ) ? sanitize_text_field($_REQUEST['id']) : '';

			if ( '' == $id ) {
				echo wp_json_encode(
					array(
						'success' => false,
						'message' => 'redirect',
						'url'     => admin_url( 'admin.php?page=ARForms-Paypal&err=1' ),
					)
				);
				die;
			} else {
				$arf_form_chk = $wpdb->get_results( $wpdb->prepare( 'SELECT id FROM `' . $tbl_arf_forms . '` WHERE id = %d', $_REQUEST['form_id'] ), ARRAY_A );//phpcs:ignore
				$form_chk     = $wpdb->get_results( $wpdb->prepare( 'SELECT id FROM `' . $arf_paypal->db_paypal_forms . '` WHERE id = %d', $id ), ARRAY_A );//phpcs:ignore
				if ( count( $arf_form_chk ) == 0 || count( $form_chk ) == 0 ) {
					echo wp_json_encode(
						array(
							'success' => false,
							'message' => 'redirect',
							'url'     => admin_url( 'admin.php?page=ARForms-Paypal&err=1' ),
						)
					);
					die;
				} else {
					$form_data = !empty($_REQUEST['form_id']) ? $arfliteform->arflitegetOne( sanitize_text_field($_REQUEST['form_id']) ) : '';

					$new_values['form_name'] = $form_data->name;

					$options['payment_gateway_type'] = isset($_REQUEST['payment_gateway_type']) ? esc_attr(sanitize_text_field($_REQUEST['payment_gateway_type'])) : 'default';
					
					$options['client_id']            = isset($_REQUEST['client_id']) ? esc_attr(sanitize_text_field($_REQUEST['client_id'])) : '';
					
					$options['client_secret']        = isset($_REQUEST['client_secret']) ? esc_attr(sanitize_text_field($_REQUEST['client_secret'])) : '';

					$options['merchant_email'] = !empty($_REQUEST['arf_paypal_email']) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_email']) ) : '';

					$options['paypal_mode'] = esc_attr($_REQUEST['arf_paypal_mode']) ;

					$options['cancel_url'] = !empty($_REQUEST['arf_paypal_cancel_url']) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_cancel_url'] )) : '';

					$options['notification'] = isset( $_REQUEST['arf_paypal_notification'] ) ? 1 : 0;

					$options['user_notification']  = isset( $_REQUEST['arf_paypal_user_notification'] ) ? 1 : 0;
					$options['user_email_content'] = isset( $_REQUEST['user_email_content'] ) ? esc_attr(sanitize_text_field($_REQUEST['user_email_content'])) : '' ;

					$options['title'] = isset($_REQUEST['arf_paypal_title']) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_title'] )) : '';

					$options['currency'] = isset($_REQUEST['arf_paypal_currency']) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_currency'] )) : '';

					$options['first_name'] = isset($_REQUEST['arf_first_name']) ? esc_attr( sanitize_text_field($_REQUEST['arf_first_name'] )) : '';

					$options['last_name'] = isset($_REQUEST['arf_last_name']) ? esc_attr( sanitize_text_field($_REQUEST['arf_last_name'] )) : '';

					$options['email'] = isset($_REQUEST['arf_email']) ? esc_attr( sanitize_text_field($_REQUEST['arf_email'] ) ) : '';

					$options['state'] = isset($_REQUEST['arf_state']) ? esc_attr(sanitize_text_field($_REQUEST['arf_state'] )) : '';

					$options['address'] = isset($_REQUEST['arf_address']) ? esc_attr( sanitize_text_field($_REQUEST['arf_address'] )) : '';

					$options['address_2'] = isset($_REQUEST['arf_address_2']) ? esc_attr( sanitize_text_field($_REQUEST['arf_address_2'] )) : '';

					$options['city'] = isset($_REQUEST['arf_city']) ? esc_attr( sanitize_text_field($_REQUEST['arf_city'] )) : '';

					$options['zip'] = isset($_REQUEST['arf_zip']) ? esc_attr( sanitize_text_field($_REQUEST['arf_zip'] )) : '';

					$options['country'] = isset($_REQUEST['arf_country']) ? esc_attr( sanitize_text_field($_REQUEST['arf_country'] )) : '';

					$options['amount'] = isset($_REQUEST['arf_amount']) ? esc_attr( $_REQUEST['arf_amount'] ) : '';

					$options['payment_type'] = isset($_REQUEST['arf_paypal_payment_type']) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_payment_type'] )) : '';

					$options['email_content'] = isset($_REQUEST['email_content']) ? esc_attr( sanitize_text_field($_REQUEST['email_content']) ) : '';

					$options['shipping_info'] = ( isset( $_REQUEST['shipping_info'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['shipping_info'] )) : 0;

					$options['paypal_condition'] = ( isset( $_REQUEST['arf_paypal_condition'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_condition'] )) : 0;

					$options['arf_payment_type'] = isset($_REQUEST['arf_payment_type']) ? esc_attr( sanitize_text_field($_REQUEST['arf_payment_type'] )) : '';

					$options['arf_multiple_product_service_type']           = ( isset( $_REQUEST['arf_multiple_product_service_type'] ) ) ? esc_attr(sanitize_text_field( $_REQUEST['arf_multiple_product_service_type'] )) : 0;
					$options['arf_cl_field_multiple_product_service_type']  = isset($_REQUEST['arf_cl_field_multiple_product_service_type']) ? esc_attr( sanitize_text_field($_REQUEST['arf_cl_field_multiple_product_service_type'] )) : '';
					$options['arf_cl_op_multiple_product_service_type']     = isset($_REQUEST['arf_cl_op_multiple_product_service_type']) ? esc_attr( sanitize_text_field($_REQUEST['arf_cl_op_multiple_product_service_type'] )) : '';
					$options['cl_rule_value_multiple_product_service_type'] = isset($_REQUEST['cl_rule_value_multiple_product_service_type']) ? esc_attr( sanitize_text_field($_REQUEST['cl_rule_value_multiple_product_service_type'] )) : '';
					$options['arf_multiple_product_service_amount'] = isset($_REQUEST['arf_multiple_product_service_amount']) ? esc_attr( sanitize_text_field($_REQUEST['arf_multiple_product_service_amount'] )) : '';

					$options['arf_multiple_donations_service_type'] = (isset($_REQUEST['arf_multiple_donations_service_type'])) ? esc_attr(sanitize_text_field($_REQUEST['arf_multiple_donations_service_type'])) : 0;
	                $options['arf_cl_field_multiple_donations_service_type'] = isset($_REQUEST['arf_cl_field_multiple_donations_service_type']) ? esc_attr(sanitize_text_field($_REQUEST['arf_cl_field_multiple_donations_service_type'])) : '';
	                $options['arf_cl_op_multiple_donations_service_type'] = isset($_REQUEST['arf_cl_op_multiple_donations_service_type']) ? esc_attr(sanitize_text_field($_REQUEST['arf_cl_op_multiple_donations_service_type'])) : '';
	                $options['cl_rule_value_multiple_donations_service_type'] = isset($_REQUEST['cl_rule_value_multiple_donations_service_type']) ? esc_attr(sanitize_text_field($_REQUEST['cl_rule_value_multiple_donations_service_type'])) : '';
	                $options['arf_multiple_donations_service_amount'] = isset($_REQUEST['arf_multiple_donations_service_amount']) ? esc_attr(sanitize_text_field($_REQUEST['arf_multiple_donations_service_amount'])) : '';

					

					

					$conditional_logic_rules = array();

					$rule_array = ( isset( $_REQUEST['rule_array_paypal'] ) && ! empty( $_REQUEST['rule_array_paypal'] ) ) ? sanitize_text_field($_REQUEST['rule_array_paypal']) : array();

					if ( count( $rule_array ) > 0 ) {
						$i = 1;
						foreach ( $rule_array as $v ) {

							$conditional_logic_field      = isset( $_REQUEST['arf_cl_field_paypal_' . $v] ) ? stripslashes_deep( sanitize_text_field($_REQUEST[ 'arf_cl_field_paypal_' . $v ] )) : '';
							$conditional_logic_field_type = $arflitefieldhelper->arflite_get_field_type( $conditional_logic_field );
							$conditional_logic_op         = isset( $_REQUEST['arf_cl_op_paypal_' . $v] ) ? stripslashes_deep( sanitize_text_field($_REQUEST[ 'arf_cl_op_paypal_' . $v ] )) : '';
							$conditional_logic_value      = isset( $_REQUEST['cl_rule_value_paypal_' . $v] ) ? stripslashes_deep( sanitize_text_field($_REQUEST[ 'cl_rule_value_paypal_' . $v ] )) : '';

							$conditional_logic_rules[ $i ] = array(
								'id'         => $i,
								'field_id'   => $conditional_logic_field,
								'field_type' => $conditional_logic_field_type,
								'operator'   => $conditional_logic_op,
								'value'      => $conditional_logic_value,
							);
							$i++;
						}
					}

					$options['conditional_logic'] = array(
						'if_cond' => isset( $_REQUEST['conditional_logic_if_cond_paypal'] ) ? esc_attr( sanitize_text_field($_REQUEST['conditional_logic_if_cond_paypal'] )) : '',
						'rules'   => $conditional_logic_rules,
					);

					$options['paypal_days']   = ( isset( $_REQUEST['arf_paypal_days'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_days'] )) : 1;
					$options['paypal_months'] = ( isset( $_REQUEST['arf_paypal_months'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_months'] )) : 1;
					$options['paypal_years']  = ( isset( $_REQUEST['arf_paypal_years'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_years'] )) : 1;

					$options['paypal_recurring_type'] = ( isset( $_REQUEST['arf_paypal_recurring_type'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_recurring_type'] )) : 'M';
					$options['paypal_recurring_time'] = ( isset( $_REQUEST['arf_paypal_recurring_time'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_recurring_time'] )) : 'infinite';

					$options['paypal_recurring_retry'] = ( isset( $_REQUEST['arf_paypal_recurring_retry'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_recurring_retry'] )) : '0';

					$options['paypal_trial_period'] = ( isset( $_REQUEST['arf_paypal_trial_period'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_period']) ) : '0';
					$options['paypal_trial_amount'] = ( isset( $_REQUEST['arf_paypal_trial_amount'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_amount'] )) : '0';
					$options['paypal_trial_days']   = ( isset( $_REQUEST['arf_paypal_trial_days'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_days'] )) : '1';
					$options['paypal_trial_months'] = ( isset( $_REQUEST['arf_paypal_trial_months'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_months'] )) : '1';
					$options['paypal_trial_years']  = ( isset( $_REQUEST['arf_paypal_trial_years'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_years']) ) : '1';

					$options['paypal_trial_recurring_type'] = ( isset( $_REQUEST['arf_paypal_trial_recurring_type'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['arf_paypal_trial_recurring_type'] )) : 'M';

					$form_options                    = maybe_unserialize( $form_data->options );
					$form_options['success_action']  = isset($_REQUEST['success_action']) ? esc_attr( sanitize_text_field($_REQUEST['success_action'] )) : '';
					$form_options['success_msg']     = isset($_REQUEST['success_msg']) ? esc_attr( sanitize_text_field($_REQUEST['success_msg'] )) : '';
					$form_options['success_url']     = isset($_REQUEST['success_url']) ? esc_attr( sanitize_text_field($_REQUEST['success_url'] )) : '';
					$form_options['success_page_id'] = isset($_REQUEST['success_page_id']) ? esc_attr( sanitize_text_field($_REQUEST['success_page_id'] )) : '';
					$new_form_options                = maybe_serialize( $form_options );

					$opt_to_update = array(
						'options' => $new_form_options,
					);
					
					$form_options = maybe_unserialize( $form_data->arf_mapped_addon );
					if ( isset( $form_options['arf_mapped_addon'] ) && ! empty( $form_options['arf_mapped_addon'] ) ) {
						if ( ! in_array( 'paypal', $form_options['arf_mapped_addon'] ) ) {
							array_push( $form_options['arf_mapped_addon'], 'paypal' );
						}
					} else {
						$form_options                     = array();
						$form_options['arf_mapped_addon'] = array( 'paypal' );
					}

					$new_form_options_mapped_addon     = maybe_serialize( $form_options );
					$opt_to_update['arf_mapped_addon'] = $new_form_options_mapped_addon;
					

					$wpdb->update(
						$tbl_arf_forms,
						$opt_to_update,
						array( 'id' => $form_data->id )
					);

					$options               = apply_filters( 'arf_trim_values', $options );
					$new_values['options'] = maybe_serialize( $options );

					global $arf_paypal;
					$res = $wpdb->update( $arf_paypal->db_paypal_forms, $new_values, array( 'id' => $id ) );

					$values = array();

					$values = $new_values;

					$values['form_id'] = esc_attr( sanitize_text_field($_REQUEST['form_id']) );

					$values['form_name'] = isset($_REQUEST['form_name']) ? esc_attr( sanitize_text_field($_REQUEST['form_name'] )) : '';

					$values['success_action'] = isset($_REQUEST['success_action']) ? esc_attr( sanitize_text_field($_REQUEST['success_action'] )) : '';

					$values['success_msg'] = isset($_REQUEST['success_msg']) ? esc_attr( sanitize_text_field($_REQUEST['success_msg'] )) : '';

					$values['success_url'] = isset($_REQUEST['success_url']) ? esc_attr( sanitize_text_field($_REQUEST['success_url'] )) : '';

					$values['success_page_id'] = isset($_REQUEST['success_page_id']) ? esc_attr( sanitize_text_field($_REQUEST['success_page_id'] )) : '';

					$values['id'] = $id;

					unset( $values['options'] );

					foreach ( $options as $option_key => $option_val ) {
						   $values[ $option_key ] = $option_val;
					}

					$arfaction = 'edit';

					$message = esc_html__( 'Configuration saved successfully.', 'ARForms' );

					echo wp_json_encode(
						array(
							'success' => true,
							'message' => $message,
						)
					);
					die;
				}
			}
		} else {

			if ( isset( $_REQUEST['arf_paypal_form'] ) && '' != $_REQUEST['arf_paypal_form'] ) {
				$new_form_id = sanitize_text_field($_REQUEST['arf_paypal_form']);

				$form_data = $arfliteform->arflitegetOne( $new_form_id );

				$new_values['form_id'] = $new_form_id;

				$new_values['form_name'] = $form_data->name;

				$options['payment_gateway_type'] = isset($_REQUEST['payment_gateway_type']) ? esc_attr(sanitize_text_field($_REQUEST['payment_gateway_type'])) : 'default';
				
				$options['client_id']            = isset($_REQUEST['client_id']) ? esc_attr(sanitize_text_field($_REQUEST['client_id'])) : '';

				$options['client_secret']        = isset($_REQUEST['client_secret']) ? esc_attr(sanitize_text_field($_REQUEST['client_secret'])) : '';

				$options['merchant_email'] = esc_attr( sanitize_text_field($_REQUEST['arf_paypal_email'] ));

				$options['paypal_mode'] = esc_attr( $_REQUEST['arf_paypal_mode'] );

				$options['cancel_url'] = esc_attr(sanitize_text_field($_REQUEST['arf_paypal_cancel_url'] ));

				$options['notification'] = isset( $_REQUEST['arf_paypal_notification'] ) ? 1 : 0;

				$options['user_notification']  = isset( $_REQUEST['arf_paypal_user_notification'] ) ? 1 : 0;
				$options['user_email_content'] = esc_attr( isset( $_REQUEST['user_email_content'] ) ? sanitize_text_field($_REQUEST['user_email_content']) : '' );

				$options['title'] = esc_attr( sanitize_text_field($_REQUEST['arf_paypal_title']) );

				$options['currency'] = esc_attr( sanitize_text_field($_REQUEST['arf_paypal_currency'] ));

				$options['first_name'] = esc_attr( sanitize_text_field($_REQUEST['arf_first_name']) );

				$options['last_name'] = esc_attr( sanitize_text_field($_REQUEST['arf_last_name']) );

				$options['email'] = esc_attr( sanitize_text_field($_REQUEST['arf_email']) );

				$options['state'] = esc_attr( sanitize_text_field($_REQUEST['arf_state']) );

				$options['address'] = esc_attr( sanitize_text_field($_REQUEST['arf_address']) );

				$options['address_2'] = esc_attr( sanitize_text_field($_REQUEST['arf_address_2'] ));

				$options['city'] = esc_attr( sanitize_text_field($_REQUEST['arf_city']) );

				$options['zip'] = esc_attr( sanitize_text_field($_REQUEST['arf_zip']) );

				$options['country'] = esc_attr( sanitize_text_field($_REQUEST['arf_country']) );

				$options['amount'] = esc_attr( $_REQUEST['arf_amount'] );

				$options['payment_type'] = esc_attr( sanitize_text_field($_REQUEST['arf_paypal_payment_type'] ));

				$options['email_content'] = esc_attr( sanitize_text_field($_REQUEST['email_content']) );

				$options['shipping_info'] = ( isset( $_REQUEST['shipping_info'] ) ) ? esc_attr( sanitize_text_field($_REQUEST['shipping_info'] )) : 0;

				$form_options                    = maybe_unserialize( $form_data->options );
				$form_options['success_action']  = esc_attr( sanitize_text_field($_REQUEST['success_action']) );
				$form_options['success_msg']     = esc_attr( sanitize_text_field($_REQUEST['success_msg'] ));
				$form_options['success_url']     = esc_attr( sanitize_text_field($_REQUEST['success_url'] ));
				$form_options['success_page_id'] = esc_attr( sanitize_text_field($_REQUEST['success_page_id'] ));

				$new_form_options                = maybe_serialize( $form_options );

				$opt_to_update = array(
					'options' => $new_form_options,
				);
				
				$form_arf_mapped_addon = maybe_unserialize( $form_data->arf_mapped_addon );
				if ( isset( $form_arf_mapped_addon['arf_mapped_addon'] ) && ! empty( $form_arf_mapped_addon['arf_mapped_addon'] ) ) {
					if ( ! in_array( 'paypal', $form_arf_mapped_addon['arf_mapped_addon'] ) ) {
						array_push( $form_arf_mapped_addon['arf_mapped_addon'], 'paypal' );
					}
				} else {
					$form_arf_mapped_addon                     = array();
					$form_arf_mapped_addon['arf_mapped_addon'] = array( 'paypal' );
				}
				$new_form_arf_mapped_addon         = maybe_serialize( $form_arf_mapped_addon );
				$opt_to_update['arf_mapped_addon'] = $new_form_arf_mapped_addon;
				

				$wpdb->update(
					$tbl_arf_forms,
					$opt_to_update,
					array( 'id' => $form_data->id )
				);

				$options               = apply_filters( 'arf_trim_values', $options );

				$new_values['options'] = maybe_serialize( $options );

				$new_values['created_at'] = current_time( 'mysql' );

				$id = $wpdb->insert( $arf_paypal->db_paypal_forms, $new_values );

				$id = $wpdb->insert_id;

				$values = array();

				$values = $new_values;

				$values['success_action'] = esc_attr( sanitize_text_field($_REQUEST['success_action']) );

				$values['success_msg'] = esc_attr( sanitize_text_field($_REQUEST['success_msg']) );

				$values['success_url'] = esc_attr( sanitize_text_field($_REQUEST['success_url']) );

				$values['success_page_id'] = esc_attr(sanitize_text_field($_REQUEST['success_page_id'] ));

				$values['id'] = $id;

				unset( $values['options'] );

				foreach ( $options as $option_key => $option_val ) {
						  $values[ $option_key ] = $option_val;
				}

				$arfaction = 'edit';

				$message = esc_html__( 'Configuration saved successfully.', 'ARForms' );

				echo wp_json_encode(
					array(
						'success'   => true,
						'message'   => $message,
						'arfaction' => 'new',
						'new_id'    => $id,
						'form_id'   => $new_form_id,
						'form_name' => $new_values['form_name'],
					)
				);
			}
		}
		die;
	}

	public function ajax_check_submit_conditions() {
		global $wpdb;

		check_ajax_referer('arforms_wp_nonce', 'nonce');

		$form_id     = isset($_POST['form_id']) ? intval($_POST['form_id']) : 0;
		$posted_data = isset($_POST['posted_data']) ? stripslashes_deep($_POST['posted_data']) : array();

		if (empty($form_id)) {
			wp_send_json_error();
		}

		$form_options_raw = $wpdb->get_var($wpdb->prepare("SELECT options FROM {$wpdb->prefix}arf_forms WHERE id = %d", $form_id));
		$form_options     = maybe_unserialize($form_options_raw);
		$logic            = isset($form_options['submit_conditional_logic']) ? $form_options['submit_conditional_logic'] : array();

		if (!isset($logic['enable']) || $logic['enable'] != '1' || empty($logic['rules'])) {
			wp_send_json_success(array('condition_met' => true));
		}

		$match_count = 0;
		$total_rules = count($logic['rules']);

		foreach ($logic['rules'] as $index => $rule) {
			$field_id    = $rule['field_id'];
			$field_value = isset($posted_data[$field_id]) ? $posted_data[$field_id] : '';
			
			if (is_string($field_value) && strpos($field_value, '|') !== false) {
				$parts       = explode('|', $field_value);
				$field_value = $parts[0];
			}

			$rule_value  = $rule['value'];
			$operator    = $rule['operator'];
			$is_rule_met = false;

			switch ($operator) {
				case 'is':
				case 'equals':
					$is_rule_met = (strval($field_value) == strval($rule_value));
					break;
				case 'is not':
				case 'not equal':
					$is_rule_met = (strval($field_value) != strval($rule_value));
					break;
				case 'greater than':
					$is_rule_met = (floatval($field_value) > floatval($rule_value));
					break;
				case 'less than':
					$is_rule_met = (floatval($field_value) < floatval($rule_value));
					break;
				case 'contains':
					$is_rule_met = (strpos($field_value, $rule_value) !== false);
					break;
				case 'not contains':
					$is_rule_met = (strpos($field_value, $rule_value) === false);
					break;
			}

			if ($is_rule_met) {
				$match_count++;
			}
		}

		$conditions_passed = false;
		if ($logic['if_cond'] == 'all' && $match_count == $total_rules) {
			$conditions_passed = true;
		} elseif ($logic['if_cond'] == 'any' && $match_count > 0) {
			$conditions_passed = true;
		}

		$final_result = ($logic['display'] == 'show') ? $conditions_passed : !$conditions_passed;
		wp_send_json_success(array('condition_met' => $final_result));
	}
	
	public function paypal_button_ui_dynamic($form) {
		global $wpdb, $arf_paypal;
	
		if (!is_object($form) || !isset($form->id)) { return; }
		$form_id = $form->id;
	
		$config_row = $wpdb->get_row($wpdb->prepare("SELECT options FROM " . $arf_paypal->db_paypal_forms . " WHERE form_id = %d", $form_id));
		if (!$config_row) { return; }
	
		$options = maybe_unserialize($config_row->options);
		if (!isset($options['payment_gateway_type']) || $options['payment_gateway_type'] !== 'popup' || empty($options['client_id']) || empty($options['amount'])) {
			return;
		}
		
		$form_options_raw = $wpdb->get_var($wpdb->prepare("SELECT options FROM {$wpdb->prefix}arf_forms WHERE id = %d", $form_id));
		$form_options = maybe_unserialize($form_options_raw);
	
		$amount_field_id = $options['amount'];
		$amount_field_key = $wpdb->get_var($wpdb->prepare("SELECT field_key FROM {$wpdb->prefix}arf_fields WHERE id = %d", $amount_field_id));
		if (!$amount_field_key) { return; }
	
		$submit_logic = isset($form_options['submit_conditional_logic']) ? $form_options['submit_conditional_logic'] : array();
		$is_submit_conditional = (isset($submit_logic['enable']) && $submit_logic['enable'] == '1' && !empty($submit_logic['rules']));
		
		$conditional_fields_keys = array();
		if ($is_submit_conditional) {
			foreach ($submit_logic['rules'] as $rule) {
				$field_id = $rule['field_id'];
				$field_key = $wpdb->get_var($wpdb->prepare("SELECT field_key FROM {$wpdb->prefix}arf_fields WHERE id = %d", $field_id));
				if ($field_key) {
					$conditional_fields_keys[] = array('id' => $field_id, 'key' => $field_key);
				}
			}
		}
	error_log(isset($options['payment_type']) ? $options['payment_type'] : 'No data');
		$config_data = array(
			'form_id'                  => $form_id,
			'form_key'                 => esc_js($form->form_key),
			'amount_field_key'         => esc_js($amount_field_key),
			'client_id'                => $options['client_id'],
			'currency'                 => isset($options['currency']) ? $options['currency'] : 'USD',
			'is_submit_conditional'    => $is_submit_conditional,
			'conditional_fields'       => $conditional_fields_keys,
			'single_payment_type'       => isset($options['payment_type']) ? $options['payment_type'] : 'product_service',
			'ajax_url'                 => admin_url('admin-ajax.php'),
			'nonce'                    => wp_create_nonce('arforms_wp_nonce'),
		);
	
		static $paypal_configs = array();
		$paypal_configs[$form->form_key] = $config_data;
	
		wp_enqueue_script('arf_paypal_front_js');
		wp_localize_script('arf_paypal_front_js', 'arfDynamicPayPalConfigs', $paypal_configs);
	}

}

global $arforms_paypal_integration;
$arforms_paypal_integration = new arforms_paypal_integration();