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

/**
 * Function that enqueues the necessary styles and scripts in backend
 */
function wppb_in_ffc_scripts() {
	$screen = get_current_screen();

	if(  $screen->id == 'profile-builder_page_manage-fields' || $screen->id == 'wppb-rf-cpt' || $screen->id == 'wppb-epf-cpt' ) {
		wp_enqueue_style( 'wppb-ffc-style', plugin_dir_url( __FILE__ ) . 'assets/css/form-fields-in-columns.css', '', PROFILE_BUILDER_VERSION );
		wp_enqueue_script( 'wppb-ffc-script', plugin_dir_url( __FILE__ ) . 'assets/js/form-fields-in-columns.js', array( 'jquery' ), PROFILE_BUILDER_VERSION );

		$vars_array = array(
			'ajaxUrl'				    => admin_url( 'admin-ajax.php' ),
			'ajaxNonce'                 => wp_create_nonce( 'wppb_ffc_backend_nonce' ),
			'alertUnsavedForm'          => __( 'Publish the form before adding Break Points!', 'profile-builder' ),
			'alertAjaxRequestInProcess' => __( 'Request in process, please wait a few seconds before a new one!', 'profile-builder' ),
			'breakpointStartTitle'        => __( 'Set column start', 'profile-builder' ),
			'breakpointEndTitle'     => __( 'Set column end', 'profile-builder' ),
			'breakpointRemoveStartTitle'        => __( 'Unset column start', 'profile-builder' ),
			'breakpointRemoveEndTitle'     => __( 'Unset column end', 'profile-builder' )
		);

		wp_localize_script( 'wppb-ffc-script', 'wppb_ffc_data', $vars_array );
	}
}
add_action( 'admin_enqueue_scripts', 'wppb_in_ffc_scripts' );

/**
 * Function that enqueues the necessary scripts in frontend and edit mode
 */

function wppb_in_ffc_maybe_print_styles(){

    static $style_added = false;
    if ( $style_added ) {
        return;
    }
    $style_added = true;

    echo '<style>
                .ffc-wrapper {
                    display: flex;
                    gap: 24px;
                }

                .ffc-wrapper li.wppb-form-field {
                    flex: 1;
                    flex-shrink: 0;
                }
                
                @media screen and (max-width: 550px) {
                    .ffc-wrapper {
                        display: block;
                    }
                }
               </style>';
}

/**
 * Function that adds a message for when there are unpaired break points
 */
function wppb_ffc_unpaired_break_points_message(){
    $screen = get_current_screen();

    if(  $screen->id == 'profile-builder_page_manage-fields' || $screen->id == 'wppb-rf-cpt' || $screen->id == 'wppb-epf-cpt' ){
        ?>
            <div id="ffc-breakpoint-message" > <?php echo esc_html__( 'Please remove or close unpaired breakpoints.', 'profile-builder');?> </div>
        <?php
    }
}
add_action('admin_footer', 'wppb_ffc_unpaired_break_points_message');

/**
 * Function that adds the Meta Boxes on each Manage Fields and Multiple Registration / Edit Profile Forms
 */
function wppb_in_ffc_add_meta_boxes() {
	add_meta_box( 'wppb-ffc-side', __( 'Form Fields in Columns', 'profile-builder' ), 'wppb_in_ffc_meta_boxes_content', array( 'wppb-epf-cpt', 'wppb-rf-cpt' ), 'side', 'low' );

    // skip this meta-box for the Repeater Field -> Edit Field Group view
    if ( !isset( $_GET['wppb_rpf_repeater_meta_name'] ) )
        add_meta_box( 'wppb-ffc-side', __( 'Form Fields in Columns', 'profile-builder' ), 'wppb_in_ffc_meta_boxes_content',  'profile-builder_page_manage-fields', 'normal', 'low' );
}
add_action( 'add_meta_boxes', 'wppb_in_ffc_add_meta_boxes', 11 );
add_action( 'wck_add_meta_boxes', 'wppb_in_ffc_add_meta_boxes', 11 );

/**
 * Function that adds content to Meta Boxes on each Manage Fields and Multiple Registration / Edit-Profile Forms
 *
 * @param   WP_Post  $post   current post
 */
function wppb_in_ffc_meta_boxes_content( $post ) {
	$screen = get_current_screen();

	if( $screen->id == 'profile-builder_page_manage-fields' ) {
        $wppb_ffc_options = get_option( 'wppb_ffc_options', 'not_found' );

        if( $wppb_ffc_options == 'not_found' ) {
            $wppb_ffc_options = array( 'pb-ffc-default-register' => 'yes', 'pb-ffc-default-edit-profile' => 'yes' );
            update_option( 'wppb_ffc_options', $wppb_ffc_options );
        }

        if( isset( $_POST['wppb_ffc_save_options'] ) && wp_verify_nonce( sanitize_text_field( $_POST['wppb_ffc_save_options'] ), 'wppb-ffc-options-verify' ) ) {
            $wppb_ffc_options = array(
                'pb-ffc-default-register'		=> isset( $_POST['pb-ffc-default-register'] ) ? sanitize_text_field( $_POST['pb-ffc-default-register'] ) : 'no',
                'pb-ffc-default-edit-profile'	=> isset( $_POST['pb-ffc-default-edit-profile'] ) ? sanitize_text_field( $_POST['pb-ffc-default-edit-profile'] ) : 'no'
            );

            update_option( 'wppb_ffc_options', $wppb_ffc_options );

            echo '<div class="notice notice-success is-dismissible"><p>'. esc_html__( 'Form Fields in Columns options updated.', 'profile-builder' ) .'</p></div>';
        }

        ?>
        <form id="wppb-ffc-options" name="wppb-ffc-options" method="POST" action="">
            <div class="cozmoslabs-columns-container">
                <div class="cozmoslabs-column">
                    <h4 class="cozmoslabs-subsection-title"><?php echo esc_html__( 'Enable on Forms', 'profile-builder' ); ?></h4>

                    <div class="cozmoslabs-form-field-wrapper cozmoslabs-toggle-switch">
                        <label class="cozmoslabs-form-field-label" for="pb-ffc-default-register"><?php esc_html_e( 'PB Default Register Form', 'profile-builder' ); ?></label>

                        <div class="cozmoslabs-toggle-container">
                            <input type="checkbox" id="pb-ffc-default-register" name="pb-ffc-default-register" value="yes" <?php echo $wppb_ffc_options != 'not_found' && $wppb_ffc_options['pb-ffc-default-register'] == 'yes' ? 'checked' : ''; ?>>
                            <label class="cozmoslabs-toggle-track" for="pb-ffc-default-register"></label>
                        </div>
                    </div>

                    <div class="cozmoslabs-form-field-wrapper cozmoslabs-toggle-switch">
                        <label class="cozmoslabs-form-field-label" for="pb-default-edit-profile"><?php esc_html_e( 'PB Default Edit Profile Form', 'profile-builder' ); ?></label>

                        <div class="cozmoslabs-toggle-container">
                            <input type="checkbox" id="pb-ffc-default-edit-profile" name="pb-ffc-default-edit-profile" value="yes" <?php echo $wppb_ffc_options != 'not_found' && $wppb_ffc_options['pb-ffc-default-edit-profile'] == 'yes' ? 'checked' : ''; ?>>
                            <label class="cozmoslabs-toggle-track" for="pb-ffc-default-edit-profile"></label>
                        </div>
                    </div>

                    <p class="cozmoslabs-description" style="margin-top: 20px !important;"><?php esc_html_e( 'Enable or Disable Form Fields in Columns on default Register and Edit Profile forms.', 'profile-builder' ); ?></p>
                </div>

            </div>

            <div id="major-publishing-actions" style="border: none; background: none;"><input name="save" type="submit" class="button button-primary button-large" id="wppb_ffc_submit" value="<?php esc_html_e( 'Update Form Fields in Columns', 'profile-builder' ); ?>"></div>
            <?php wp_nonce_field( 'wppb-ffc-options-verify', 'wppb_ffc_save_options', false ); ?>
        </form>
        <?php
    }
    else{
		$wppb_ffc_post_options = get_post_meta( $post->ID, 'wppb_ffc_post_options', true );
		$wppb_ffc_post_options = is_array( $wppb_ffc_post_options ) ? $wppb_ffc_post_options : 'not_found';

		if( $wppb_ffc_post_options == 'not_found' ) {
			$wppb_ffc_post_options = array( 'ffc-enable' => 'yes' );
			update_post_meta( $post->ID, 'wppb_ffc_post_options', $wppb_ffc_post_options );
		}

		$wppb_ffc_check_post_status = '';
		if( get_post_status( $post->ID ) !== 'publish' ) {
			$wppb_ffc_check_post_status = '<p class="description wppb-ffc-post-publish-error">'. esc_html__( 'Publish the form before adding Interval Break Points! - Form Fields in Columns', 'profile-builder' ) .'</p>';
		}

		?>

		<p class="cozmoslabs-description"><?php esc_html_e( 'Begin by placing Start and End break points on your fields. Use the option below to disable the columns without removing the breakpoints.', 'profile-builder' ); ?></p>

		<?php echo $wppb_ffc_check_post_status; //phpcs:ignore ?>

		<div class="cozmoslabs-form-field-wrapper cozmoslabs-toggle-switch">
			<label class="cozmoslabs-form-field-label" for="ffc-enable"><?php esc_html_e( 'Enable', 'profile-builder' ); ?></label>

			<div class="cozmoslabs-toggle-container">
				<input type="checkbox" id="ffc-enable" name="ffc-enable" value="yes" <?php echo $wppb_ffc_post_options != 'not_found' && $wppb_ffc_post_options['ffc-enable'] == 'yes' ? 'checked' : ''; ?>>
				<label class="cozmoslabs-toggle-track" for="ffc-enable"></label>
			</div>
		</div>

		<?php
		wp_nonce_field( 'wppb-ffc-post-'. $post->ID .'-options-verify', 'wppb_ffc_save_post_options', false );
	}

}

/**
 * Function that save content from Meta Boxes on each Multiple Registration / Edit-Profile Forms
 *
 * @param   int     $post_id    Post ID
 */
function wppb_in_ffc_save_metabox_content( $post_id ) {
	if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}

	if( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	if( isset( $_POST['wppb_ffc_save_post_options'] ) && wp_verify_nonce( sanitize_text_field( $_POST['wppb_ffc_save_post_options'] ), 'wppb-ffc-post-'. $post_id .'-options-verify' ) ) {
		$wppb_ffc_post_options = array(
			'ffc-enable'	        => isset( $_POST['ffc-enable'] ) ? sanitize_text_field( $_POST['ffc-enable'] ) : 'no',
		);

		update_post_meta( $post_id, 'wppb_ffc_post_options', $wppb_ffc_post_options );
	}
}
add_action( 'save_post', 'wppb_in_ffc_save_metabox_content' );

/**
 * Function that outputs code for start steps before a form field
 *
 * @param   string  $field_output   code to output after field
 * @param   array   $field  array with the field details
 * @param   string  $error_var
 * @param   string  $role       role of the form
 * @param   string  $form_id    ID of the form
 * @param   string  $form_type   type of the form
 *
 * @return  string  $field_output
 */
function wppb_in_ffc_output_before_form_field( $field_output, $field, $error_var, $role, $form_id, $form_type ) {
	if( ! is_null( $form_id ) && !empty( $form_id ) ) {
		$break_points = get_post_meta( $form_id, 'wppb_ffc_break_points', true );
		$break_points = is_array( $break_points ) ? $break_points : 'not_found';
        $wppb_ffc_options = get_post_meta( $form_id, 'wppb_ffc_post_options', true );

        if( !empty( $wppb_ffc_options ) &&  $wppb_ffc_options['ffc-enable'] == 'no' ){
            return $field_output;
        }

	} else {
		$break_points = get_option( 'wppb_ffc_break_points', 'not_found' );
        $wppb_ffc_options = get_option( 'wppb_ffc_options', 'not_found' );

        if( $wppb_ffc_options != 'not_found' ) {
            if( ( $wppb_ffc_options['pb-ffc-default-register'] == 'no' && $form_type == 'register' ) || ( $wppb_ffc_options['pb-ffc-default-edit-profile'] == 'no' && $form_type == 'edit_profile' ) ) {
                return $field_output;
            }
        }
	}

	if( $break_points != 'not_found' && array_key_exists( $field['id'], $break_points )  && $break_points[$field['id']] == 'start' ) {

        $keys = array_keys( $break_points );
        $current_index = array_search( $field['id'], $keys );

        if ( isset( $keys[ $current_index + 1 ] ) ){
            $next_key = $keys[ $current_index + 1 ];

            if ( $break_points[ $next_key ] == 'end' ){
                $field_output = '<div class="ffc-wrapper">' . $field_output;
            }
        }
	}

	return $field_output;
}
add_filter( 'wppb_output_before_form_field', 'wppb_in_ffc_output_before_form_field', 7, 6 );


/**
 * Function that outputs code for end steps after a form field
 *
 * @param   string  $field_output   code to output after field
 * @param   array   $field  array with the field details
 * @param   string  $form_id    ID of the form
 * @param   string  $form_type   type of the form
 *
 * @return  string  $field_output
 */
function wppb_in_ffc_output_after_form_field( $field_output, $field, $form_id, $form_type, $called_from ) {
	if( ! is_null( $form_id ) ) {
		$break_points = get_post_meta( $form_id, 'wppb_ffc_break_points', true );
		$break_points = is_array( $break_points ) ? $break_points : 'not_found';
        $wppb_ffc_options = get_post_meta( $form_id, 'wppb_ffc_post_options', true );

        if( !empty( $wppb_ffc_options ) &&  $wppb_ffc_options['ffc-enable'] == 'no' ){
            return $field_output;
        }
	} else {
		$break_points = get_option( 'wppb_ffc_break_points', 'not_found' );
        $wppb_ffc_options = get_option( 'wppb_ffc_options', 'not_found' );

        if( $wppb_ffc_options != 'not_found' ) {
            if( ( $wppb_ffc_options['pb-ffc-default-register'] == 'no' && $form_type == 'register' ) || ( $wppb_ffc_options['pb-ffc-default-edit-profile'] == 'no' && $form_type == 'edit_profile' ) ) {
                return $field_output;
            }
        }
	}

	if( $break_points != 'not_found' && array_key_exists( $field['id'], $break_points )  && is_null( $called_from ) && $break_points[$field['id']] == 'end' ) {

        $keys = array_keys( $break_points );
        $current_index = array_search( $field['id'], $keys );

        if ( isset( $keys[ $current_index - 1 ] ) ){
            $previous_key = $keys[ $current_index - 1 ];

            if ( $break_points[ $previous_key ] == 'start' ){
                $field_output .= '</div>';
                wppb_in_ffc_maybe_print_styles();
            }
        }
	}

	return $field_output;
}
add_filter( 'wppb_output_after_form_field', 'wppb_in_ffc_output_after_form_field', 7, 5 );

/**
 * Function that adds Start/End Break Points column in back-end (Manage Fields, Multiple Registration and Edit-Profile Forms)
 *
 * @param   string  $content    columns content added by filter
 * @param   string  $list       table content
 * @param   string  $meta       post meta
 *
 * @return  string
 */
function wppb_in_ffc_column_content( $content, $list, $meta ) {
	if( isset( $_GET['wppb_rpf_repeater_meta_name'] ) ) {
		return $content;
	}

	if( $meta == 'wppb_manage_fields' || $meta == 'wppb_rf_fields' || $meta == 'wppb_epf_fields' ) {
		$content .= '<td class="wck-ffc"><span class="wppb-ffc-break" style="display: none;"><b class="wppb-ffc-add-sign">+</b></span></td>';
	}

	return $content;
}
add_filter( 'wck_add_content_after_columns', 'wppb_in_ffc_column_content', 10, 3 );

/**
 * Function that saves a break point on a field
 */
function wppb_in_ffc_save_break_points() {
	check_ajax_referer( 'wppb_ffc_backend_nonce', 'wppb_ffc_ajax_nonce' );

	if( isset( $_POST['wppb_ffc_form_id'] ) ) {
		if ($_POST['wppb_ffc_form_id'] === 'manage-fields') {
			$break_points = get_option('wppb_ffc_break_points', 'not_found');
		} else {
			$break_points = get_post_meta( sanitize_text_field( $_POST['wppb_ffc_form_id'] ), 'wppb_ffc_break_points', true);
			$break_points = is_array($break_points) ? $break_points : 'not_found';
		}
	}

	if( isset( $_POST['wppb_ffc_action'] ) && isset( $_POST['wppb_ffc_field_id'] ) && isset( $_POST['wppb_ffc_interval_point'] ) ) {
		if ( $_POST['wppb_ffc_action'] === 'add' ) {
			if ($break_points == 'not_found') {
				$break_points = array( absint($_POST['wppb_ffc_field_id'] ) => sanitize_text_field( $_POST['wppb_ffc_interval_point'] ) );
			} else {
				$break_points[absint($_POST['wppb_ffc_field_id'])] = sanitize_text_field( $_POST['wppb_ffc_interval_point'] );
			}
		} elseif ( $_POST['wppb_ffc_action'] === 'remove' && $break_points != 'not_found' ) {
			unset( $break_points[absint( $_POST['wppb_ffc_field_id'] )] );
		}
	}

	if( isset( $_POST['wppb_ffc_form_id'] ) ){
		if( $_POST['wppb_ffc_form_id'] === 'manage-fields' ) {
			update_option( 'wppb_ffc_break_points', $break_points );
		} else {
			update_post_meta( absint( $_POST['wppb_ffc_form_id'] ), 'wppb_ffc_break_points', $break_points );
		}
	}

	die( 'option_updated' );
}
add_action( 'wp_ajax_wppb_ffc_save_break_points', 'wppb_in_ffc_save_break_points' );

/**
 * Function that deletes break points attached to deleted fields
 *
 * @param   string  $post_meta
 * @param   int     $post_id
 * @param   int     $element_id
 */
function wppb_in_ffc_delete_break_points( $post_meta, $post_id, $element_id = NULL ) {
	if( isset( $element_id ) ) {
		if( isset( $post_meta ) && $post_meta == 'wppb_manage_fields' ) {
			$wppb_manage_fields = get_option( 'wppb_manage_fields', 'not_found' );
			$break_points = get_option( 'wppb_ffc_break_points', 'not_found' );

			if( $wppb_manage_fields != 'not_found' && $break_points != 'not_found') {
				unset( $break_points[$wppb_manage_fields[$element_id]['id']] );
				update_option( 'wppb_ffc_break_points', $break_points );
			}

		} elseif( isset( $post_meta ) && isset( $post_id ) ) {
			$wppb_form_fields = get_post_meta( $post_id, $post_meta, true );
			$break_points = get_post_meta( $post_id, 'wppb_ffc_break_points', true );
			$break_points = is_array( $break_points ) ? $break_points : 'not_found';

			if( $break_points != 'not_found' ) {
				unset( $break_points[$wppb_form_fields[$element_id]['id']] );
				update_post_meta( $post_id, 'wppb_ffc_break_points', $break_points );
			}
		}
	} elseif( isset( $post_id ) ) {
		delete_post_meta( $post_id, 'wppb_ffc_break_points' );
	}
}
add_action( 'wck_before_remove_meta', 'wppb_in_ffc_delete_break_points', 10 , 3 );
add_action( 'wppb_before_remove_all_fields', 'wppb_in_ffc_delete_break_points', 10 , 2 );

/**
 * Function that checks database for break points attached to fields
 */
function wppb_in_ffc_check_break_points() {
	if( !isset( $_POST['wppb_ffc_form_id'] ) )
		die();

	if( $_POST['wppb_ffc_form_id'] === 'manage-fields' ) {
		$break_points = get_option( 'wppb_ffc_break_points', 'not_found' );
	} else {
		$break_points = get_post_meta( sanitize_text_field( $_POST['wppb_ffc_form_id'] ), 'wppb_ffc_break_points', true );
		$break_points = is_array( $break_points ) ? $break_points : 'not_found';
	}

	if( $_POST['wppb_ffc_form_id'] === NULL ) {
		die( 'NULL' );
	} elseif( $break_points == 'not_found' ) {
		die( $break_points ); //phpcs:ignore
	} else {
		$break_points = array_combine(
			array_map( 'absint', array_keys($break_points) ),
			array_values( $break_points )
		);
		die( json_encode( $break_points ) );
	}
}
add_action( 'wp_ajax_wppb_ffc_check_break_points', 'wppb_in_ffc_check_break_points' );
add_action( 'wp_ajax_nopriv_wppb_ffc_check_break_points', 'wppb_in_ffc_check_break_points' );

/**
 * Function that checks database for break points attached to fields after fields reorder
 *
 * @param   int  $id   ID of the form
 */
function wppb_in_ffc_after_reorder_check_break_points( $id ) {
	if( empty( $id ) ) {
		$break_points = get_option( 'wppb_ffc_break_points', 'not_found' );
		$id = '\'manage-fields\'';
	} else {
		$break_points = get_post_meta( $id, 'wppb_ffc_break_points', true );
	}

	if( $break_points != 'not_found' && ! empty( $break_points ) ) {
		$break_points = array_combine(
			array_map( 'absint', array_keys( $break_points ) ),
			array_values( $break_points )
		);
		echo '<script>
                wppb_ffc_add_break_points( '. json_encode( $break_points ) .' )
                   
              </script>';
	}

	echo '<script>wppb_ffc_break_points_buttons( '. $id .' )</script>'; // phpcs:ignore
	echo '<script>wppb_ffc_remove_unpaired_break_points_after_reorder( '. $id .' )</script>'; // phpcs:ignore
	echo '<script>if( typeof wppb_msf_compatibility_ffc === \'function\' ){ wppb_msf_compatibility_ffc( '. $id .' ) }</script>'; // phpcs:ignore
}
add_action( 'wck_refresh_list_wppb_manage_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
add_action( 'wck_refresh_entry_wppb_manage_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
add_action( 'wck_refresh_list_wppb_rf_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
add_action( 'wck_refresh_entry_wppb_rf_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
add_action( 'wck_refresh_list_wppb_epf_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
add_action( 'wck_refresh_entry_wppb_epf_fields', 'wppb_in_ffc_after_reorder_check_break_points' );
