<?php
    if ( ! defined( 'ABSPATH' ) ) { exit; }
    
	add_action( 'wp_ajax_piotnetforms_ajax_form_builder_preview_submission', 'piotnetforms_ajax_form_builder_preview_submission' );
	add_action( 'wp_ajax_nopriv_piotnetforms_ajax_form_builder_preview_submission', 'piotnetforms_ajax_form_builder_preview_submission' );

	function set_val_preview_piotnetforms( &$array, $path, $val ) {
		for ( $i=&$array; $key=array_shift( $path ); $i=&$i[$key] ) {
			if ( !isset( $i[$key] ) ) {
				$i[$key] = [];
			}
		}
		$i = $val;
	}

	function piotnetforms_merge_string_preview( &$string, $string_add ) {
		$string = $string . $string_add;
	}

	function piotnetforms_unset_string_preview( &$string ) {
		$string = '';
	}

	function piotnetforms_set_string_preview( &$string, $string_set ) {
		$string = $string_set;
	}

	function replace_email_preview_piotnetforms( $content, $fields, $payment_status = 'succeeded', $payment_id = '', $succeeded = 'succeeded', $pending = 'pending', $failed = 'failed', $submit_id = 0 ) {
		$message = $content;

		$message_all_fields = '';

		if ( !empty( $fields ) ) {

			// all fields
			foreach ( $fields as $field ) {
				$field_value = $field['value'];
				$field_label = isset( $field['label'] ) ? $field['label'] : '';
				if ( isset( $field['value_label'] ) ) {
					$field_value = $field['value_label'];
				}

				$repeater_id = $field['repeater_id'];
				$repeater_id_string = '';
				$repeater_id_array = array_reverse( explode( ',', rtrim( $repeater_id, ',' ) ) );
				foreach ( $repeater_id_array as $repeater ) {
					$repeater_array = explode( '|', $repeater );
					array_pop( $repeater_array );
					$repeater_id_string .= join( ',', $repeater_array );
				}
				$repeater_index = $field['repeater_index'];
				$repeater_index_1 = $repeater_index + 1;
				$repeater_label = '<span data-id="' . esc_attr( $repeater_id_string ) . '"><strong>' . $field['repeater_label'] . ' ' . $repeater_index_1 . ': </strong></span><br>';

				$repeater_remove_this_field = false;
				if ( isset( $field['repeater_remove_this_field'] ) ) {
					$repeater_remove_this_field = true;
				}

				if ( !empty( $repeater_id ) && !empty( $repeater_label ) && $repeater_remove_this_field == false ) {
					if ( strpos( $message_all_fields, $repeater_label ) !== false ) {
						$message_all_fields .= '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
					} else {
						$message_all_fields .= $repeater_label;
						$message_all_fields .= '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
					}
				// if ($field['repeater_index'] != ($field['repeater_length'] - 1)) {
				// 	$message .=  '</div>';
				// }
				} else {
                    if(!is_null($field['type']) && $field['type'] == 'image_select'){
                        $image_selected_options = !empty($field['image_selected_options']) ? $field['image_selected_options'] : false;
                        if($image_selected_options){
                            $image_select_html = '<div class="piotnetforms-image-select-preview"><label class="piotnetforms-preview-submission__item-label">'.$field_label.': </label><ul class="thumbnails image_picker_selector">';
                            foreach($image_selected_options as $label => $image){
                                $image_select_html .= '<li><div class="thumbnail"><img class="image_picker_image" src="'.$image.'"><p>'.$label.'</p></li>';
                            }
                            $image_select_html .= '</ul></div>';
                            $message_all_fields .= $image_select_html;
                        } 
                    }else {
                        if ( strpos( $field['name'], 'piotnetforms-end-repeater' ) === false ) {
                            $message_all_fields .= '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
                        }
                    }
					
				}
			}

			$message = str_replace( '[all-fields]', $message_all_fields, $message );

			// each field

			$repeater_content = '';
			$repeater_id_one = '';
			foreach ( $fields as $field ) {
				$field_value = $field['value'];
				$field_label = isset( $field['label'] ) ? $field['label'] : '';
				if ( isset( $field['value_label'] ) ) {
					$field_value = $field['value_label'];
				}

				$search_remove_line_if_field_empty = '[field id="' . $field['name'] . '"]' . '[remove_line_if_field_empty]';

				if ( empty( $field_value ) ) {
					$lines = explode( "\n", $message );
					$lines_found = [];

					foreach ( $lines as $num => $line ) {
						$pos = strpos( $line, $search_remove_line_if_field_empty );
						if ( $pos !== false ) {
							$lines_found[] = $line;
						}
					}

					if ( !empty( $lines_found ) ) {
						foreach ( $lines_found as $line ) {
							$message = str_replace( [ $line . "\n", "\n" . $line ], '', $message );
						}
					}
				}

				$search = '[field id="' . $field['name'] . '"]';
				$message = str_replace( $search, $field_value, $message );

				$repeater_id = $field['repeater_id'];
				$repeater_id_string = '';
				$repeater_id_array = array_reverse( explode( ',', rtrim( $repeater_id, ',' ) ) );
				foreach ( $repeater_id_array as $repeater ) {
					$repeater_array = explode( '|', $repeater );
					array_pop( $repeater_array );
					$repeater_id_string .= join( ',', $repeater_array );
				}
				$repeater_index = $field['repeater_index'];
				$repeater_index_1 = $repeater_index + 1;
				$repeater_label = '<span data-id="' . esc_attr( $repeater_id_string ) . '"><strong>' . $field['repeater_label'] . ' ' . $repeater_index_1 . ': </strong></span><br>';

				$repeater_remove_this_field = false;
				if ( isset( $field['repeater_remove_this_field'] ) ) {
					$repeater_remove_this_field = true;
				}

				if ( !empty( $repeater_id ) && !empty( $repeater_label ) && $repeater_remove_this_field == false ) {
					if ( strpos( $repeater_content, $repeater_label ) !== false ) {
						$string_add = '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
						piotnetforms_merge_string_preview( $repeater_content, $string_add );
					} else {
						$string_add = $repeater_label . '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
						piotnetforms_merge_string_preview( $repeater_content, $string_add );
					}
					if ( substr_count( $field['repeater_id'], '|' ) == 2 ) {
						piotnetforms_set_string_preview( $repeater_id_one, $field['repeater_id_one'] );
					}
				}

				if ( empty( $repeater_id ) ) {
					if ( !empty( $repeater_id_one ) && !empty( $repeater_content ) ) {
						$search_repeater = '[repeater id="' . $repeater_id_one . '"]';
						$message = str_replace( $search_repeater, $repeater_content, $message );
						piotnetforms_unset_string_preview( $repeater_content );
						piotnetforms_unset_string_preview( $repeater_id_one );
					}
				}
			}
		}

		$search_remove_line_if_field_empty = '"]' . '[remove_line_if_field_empty]'; // fix alert [

		$lines = explode( "\n", $message );
		$lines_found = [];

		foreach ( $lines as $num => $line ) {
			$pos = strpos( $line, $search_remove_line_if_field_empty );
			if ( $pos !== false ) {
				$lines_found[] = $line;
			}
		}

		if ( !empty( $lines_found ) ) {
			foreach ( $lines_found as $line ) {
				$message = str_replace( [ $line . "\n", "\n" . $line ], '', $message );
			}
		}

		$message = str_replace( [ '[remove_line_if_field_empty]' ], '', $message );

		$message = str_replace( [ "\r\n", "\n", "\r", '[remove_line_if_field_empty]' ], '<br />', $message );

		if ( $payment_status == 'succeeded' ) {
			$message = str_replace( '[payment_status]', $succeeded, $message );
		}

		if ( $payment_status == 'pending' ) {
			$message = str_replace( '[payment_status]', $pending, $message );
		}

		if ( $payment_status == 'failed' ) {
			$message = str_replace( '[payment_status]', $failed, $message );
		}

		if ( !empty( $payment_id ) ) {
			$message = str_replace( '[payment_id]', $payment_id, $message );
		}

		if ( !empty( $submit_id ) ) {
			$message = str_replace( '[submit_id]', $submit_id, $message );
		}

		return $message;
	}

	function get_field_name_shortcode_preview_piotnetforms( $content ) {
		$field_name = str_replace( '[field id="', '', $content );
		$field_name = str_replace( '[repeater id="', '', $field_name ); // fix alert ]
		$field_name = str_replace( '"]', '', $field_name );
		return trim( $field_name );
	}

	function piotnetforms_get_field_value_preview( $field_name, $fields, $payment_status = 'succeeded', $payment_id = '', $succeeded = 'succeeded', $pending = 'pending', $failed = 'failed' ) {
		$field_name_first = $field_name;

		if ( strpos( $field_name, '[repeater id' ) !== false ) { // ] [ [ fix alert
			$field_name = str_replace( 'id="', "id='", $field_name );
			$field_name = str_replace( '"]', "']", $field_name );
			$message = $field_name;
			$repeater_content = '';
			$repeater_id_one = '';
			foreach ( $fields as $field ) {
				$field_value = $field['value'];
				$field_label = isset( $field['label'] ) ? $field['label'] : '';
				if ( isset( $field['value_label'] ) ) {
					$field_value = $field['value_label'];
				}

				$search = '[field id="' . $field['name'] . '"]';
				$message = str_replace( $search, $field_value, $message );

				$repeater_id = $field['repeater_id'];
				$repeater_id_string = '';
				$repeater_id_array = array_reverse( explode( ',', rtrim( $repeater_id, ',' ) ) );
				foreach ( $repeater_id_array as $repeater ) {
					$repeater_array = explode( '|', $repeater );
					array_pop( $repeater_array );
					$repeater_id_string .= join( ',', $repeater_array );
				}
				$repeater_index = $field['repeater_index'];
				$repeater_index_1 = $repeater_index + 1;
				$repeater_label = $field['repeater_label'] . ' ' . $repeater_index_1 . '</div>';

				$repeater_remove_this_field = false;
				if ( isset( $field['repeater_remove_this_field'] ) ) {
					$repeater_remove_this_field = true;
				}

				if ( !empty( $repeater_id ) && !empty( $repeater_label ) && $repeater_remove_this_field == false ) {
					if ( strpos( $repeater_content, $repeater_label ) !== false ) {
						$string_add = '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
						piotnetforms_merge_string_preview( $repeater_content, $string_add );
					} else {
						$string_add = $repeater_label . '<div class="piotnetforms-preview-submission__item"><label class="piotnetforms-preview-submission__item-label">' . $field_label . ': </label>' . '<span class="piotnetforms-preview-submission__item-value">' . $field_value . '</span>' . '</div>';
						piotnetforms_merge_string_preview( $repeater_content, $string_add );
					}
					if ( substr_count( $field['repeater_id'], '|' ) == 2 ) {
						piotnetforms_set_string_preview( $repeater_id_one, $field['repeater_id_one'] );
					}
				}

				if ( empty( $repeater_id ) ) {
					if ( !empty( $repeater_id_one ) && !empty( $repeater_content ) ) {
						$search_repeater = "[repeater id='" . $repeater_id_one . "']";
						$message = str_replace( $search_repeater, $repeater_content, $message );

						piotnetforms_unset_string_preview( $repeater_content );
						piotnetforms_unset_string_preview( $repeater_id_one );
					}
				}
			}

			$field_value = $message;
		} else {
			$field_name = get_field_name_shortcode_preview_piotnetforms( $field_name );
			$field_value = '';
			foreach ( $fields as $key_field=>$field ) {
				if ( $fields[$key_field]['name'] == $field_name ) {
					// if (!empty($fields[$key_field]['value'])) {
					// 	$field_value = $fields[$key_field]['value'];
					// }

					if ( isset( $fields[$key_field]['calculation_results'] ) ) {
						$field_value = $fields[$key_field]['calculation_results'];
					} else {
						$field_value = $fields[$key_field]['value'];
					}
				}
			}
		}

		if ( strpos( $field_name_first, '[payment_status]' ) !== false || strpos( $field_name_first, '[payment_id]' ) !== false ) {
			if ( $payment_status == 'succeeded' ) {
				$field_value = str_replace( '[payment_status]', $succeeded, $field_name_first );
			}

			if ( $payment_status == 'pending' ) {
				$field_value = str_replace( '[payment_status]', $pending, $field_name_first );
			}

			if ( $payment_status == 'failed' ) {
				$field_value = str_replace( '[payment_status]', $failed, $field_name_first );
			}

			if ( !empty( $payment_id ) && strpos( $field_name_first, '[payment_id]' ) !== false ) {
				$field_value = str_replace( '[payment_id]', $payment_id, $field_name_first );
			}
		}

		return trim( $field_value );
	}

	function piotnetforms_ajax_form_builder_preview_submission() {
		if ( !empty( $_POST['fields'] ) ) {
			$fields = stripslashes( $_POST['fields'] );
			$fields = json_decode( $fields, true );
			$fields = array_unique( $fields, SORT_REGULAR );

			if ( isset( $_POST['remove_empty_fields'] ) ) {
				$fields_new = [];
				foreach ( $fields as $field ) {
					if ( !empty( $field['value'] ) ) {
						$fields_new[] = $field;
					}
				}
				$fields = $fields_new;
			}

			if ( isset( $_POST['custom_list_fields'] ) ) {
				$fields_name = [];

				$custom_list_fields = json_decode( stripslashes( $_POST['custom_list_fields'] ), true );

				foreach ( $custom_list_fields as $shortcode ) {
					$fields_name[] = get_field_name_shortcode_preview_piotnetforms( $shortcode['field_shortcode'] );
				}

				$fields_new = [];
				foreach ( $fields as $field ) {
					if ( in_array( $field['name'], $fields_name ) ) {
						$fields_new[] = $field;
					}
				}
				$fields = $fields_new;
			}

			$output = replace_email_preview_piotnetforms( '[all-fields]', $fields );

			if ( $output != '[all-fields]' ) {
				echo $output;
			} else {
				echo '';
			}
		}

		wp_die();
	}
