<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://registrationformbuilder.com
 * @since      1.0.0
 *
 * @package    Vedrixa_Forms
 * @subpackage Vedrixa_Forms/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the Vedrixa Forms plugin version and example hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Vedrixa_Forms
 * @subpackage Vedrixa_Forms/admin
 * @author     Vedrixa <support@registrationformbuilder.com>
 */
class Registration_Form_Builder_Admin {

	/**
	 * Option name storing first-seen timestamp for review notice timing.
	 *
	 * @var string
	 */
	const REVIEW_NOTICE_INSTALLED_ON_OPTION = 'wpefb_review_notice_installed_on';

	/**
	 * Option name storing permanent dismissal state.
	 *
	 * @var string
	 */
	const REVIEW_NOTICE_DISMISSED_OPTION = 'wpefb_review_notice_dismissed';

	/**
	 * Option name storing snooze-until timestamp.
	 *
	 * @var string
	 */
	const REVIEW_NOTICE_REMIND_AFTER_OPTION = 'wpefb_review_notice_remind_after';

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $registration_form_builder    The ID of this plugin.
	 */
	private $registration_form_builder;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;

	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $registration_form_builder       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $registration_form_builder, $version ) {

		$this->registration_form_builder = $registration_form_builder;
		$this->version                   = $version;

	}

	private function get_pro_page_url() {
		return esc_url_raw( apply_filters( 'wpefb_pro_page_url', admin_url( 'admin.php?page=wpefb_pro' ) ) );
	}

	private function get_pricing_url() {
		return esc_url_raw( apply_filters( 'wpefb_upgrade_url', 'https://registrationformbuilder.com/pricing/' ) );
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles( $hook ) {
		if ( ! $this->should_load_admin_assets( $hook ) ) {
			return;
		}

		wp_enqueue_style( 'wp-color-picker' );

		$screen = get_current_screen();
		if ( isset( $screen ) && 'wpefb_forms_fields' === $screen->base ) {
			wp_enqueue_style( 'wpefb-jquery-ui-smoothness', plugin_dir_url( __FILE__ ) . 'css/jquery-ui.min.css', array(), $this->version );
		}

		wp_enqueue_style( 'wpefb-google-fonts', 'https://fonts.googleapis.com/icon?family=Material+Icons', array(), $this->version );
		wp_enqueue_style( $this->registration_form_builder, plugin_dir_url( __FILE__ ) . 'css/registration-form-builder-admin.css', array(), $this->version, 'all' );
		wp_enqueue_style( 'wef-admin', plugin_dir_url( __FILE__ ) . 'css/admin.css', array(), $this->version, 'all' );
		wp_enqueue_style( 'arf-admin', plugin_dir_url( __FILE__ ) . 'css/style.css', array(), $this->version, 'all' );
		wp_enqueue_style( 'erfb-formbuilder', plugin_dir_url( __FILE__ ) . 'css/formbuilder.css', array(), $this->version, 'all' );
	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts( $hook ) {
		if ( ! $this->should_load_admin_assets( $hook ) ) {
			return;
		}

		wp_enqueue_script( 'jquery' );
		wp_enqueue_script( 'jquery-ui-core' );
		wp_enqueue_script( 'jquery-ui-tabs' );
		wp_enqueue_script( 'jquery-ui-sortable' );
		wp_enqueue_script( 'jquery-ui-droppable' );
		wp_enqueue_script( 'wp-color-picker' );
		wp_enqueue_script( 'thickbox' );
		wp_enqueue_script( 'jquery-ui-dialog' );
		wp_enqueue_script( 'media-upload' );
		wp_enqueue_script( 'jquery-form' );
		wp_enqueue_script( 'jquery-ui-datepicker' );
		wp_enqueue_script( $this->registration_form_builder, plugin_dir_url( __FILE__ ) . 'js/registration-form-builder-admin.js', array( 'jquery' ), $this->version, true );
		wp_register_script( 'erfb-formbuilder', plugin_dir_url( __FILE__ ) . 'js/formbuilder.js', array( 'jquery' ), $this->version, true );

		wp_localize_script(
			$this->registration_form_builder,
			'wpefb_admin_ajax_object',
			array(
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'pro'      => array(
					'enabled'     => WPEFB_Features::is_pro_active(),
					'upgrade_url' => $this->get_pro_page_url(),
					'pricing_url' => $this->get_pricing_url(),
					'logo_url'    => esc_url_raw( apply_filters( 'wpefb_pro_logo_url', plugin_dir_url( __FILE__ ) . 'partials/images/vedrixa-logo.png' ) ),
				),
			)
		);
		$error                         = array();
		$error['valid_email']          = __( 'Please enter a valid e-mail address.', 'vedrixa-forms-registration-builder' );
		$error['valid_number']         = __( 'Please enter a valid number.', 'vedrixa-forms-registration-builder' );
		$error['valid_date']           = __( 'Please enter a valid date(yyyy-mm-dd format).', 'vedrixa-forms-registration-builder' );
		$error['required_field']       = __( 'This is a required field.', 'vedrixa-forms-registration-builder' );
		$error['file_type']            = __( 'This file type is not allowed.', 'vedrixa-forms-registration-builder' );
		$error['short_password']       = __( 'Your password should be at least 7 characters long.', 'vedrixa-forms-registration-builder' );
		$error['pass_not_match']       = __( 'Password and confirm password do not match.', 'vedrixa-forms-registration-builder' );
		$error['user_exist']           = __( 'Sorry, username already exist.', 'vedrixa-forms-registration-builder' );
		$error['email_exist']          = __( 'Sorry, email already exist.', 'vedrixa-forms-registration-builder' );
		$error['valid_facebook_url']   = __( 'Please enter a valid facebook url.', 'vedrixa-forms-registration-builder' );
		$error['valid_twitter_url']    = __( 'Please enter a valid twitter url.', 'vedrixa-forms-registration-builder' );
		$error['valid_google_url']     = __( 'Please enter a valid google+ url.', 'vedrixa-forms-registration-builder' );
		$error['valid_linked_in_url']  = __( 'Please enter a valid linkedin url.', 'vedrixa-forms-registration-builder' );
		$error['valid_youtube_url']    = __( 'Please enter a valid youtube url.', 'vedrixa-forms-registration-builder' );
		$error['valid_mixcloud_url']   = __( 'Please enter a valid Mixcloud url.', 'vedrixa-forms-registration-builder' );
		$error['valid_soundcloud_url'] = __( 'Please enter a valid SoundCloud url.', 'vedrixa-forms-registration-builder' );
		$error['valid_instagram_url']  = __( 'Please enter a valid instagram url.', 'vedrixa-forms-registration-builder' );
		$error['atleast_one_field']    = __( 'Select at least one field.', 'vedrixa-forms-registration-builder' );
		$error['seprator_not_empty']   = __( 'Seperator field can not be empty.', 'vedrixa-forms-registration-builder' );
		$error['choose_image']         = __( 'Choose Image', 'vedrixa-forms-registration-builder' );
		$error['valid_image']          = __( 'This is not a valid image', 'vedrixa-forms-registration-builder' );
		$error['valid_group_name']     = __( 'Please enter a valid group name.', 'vedrixa-forms-registration-builder' );
		$error['group_manager_first']  = __( 'You must define a Group Manager first, before making a Group closed.', 'vedrixa-forms-registration-builder' );
		$error['delete']               = __( 'Delete', 'vedrixa-forms-registration-builder' );
		$error['success']              = __( 'Success', 'vedrixa-forms-registration-builder' );
		$error['failure']              = __( 'Failure', 'vedrixa-forms-registration-builder' );
		$error['select_group']         = __( 'please select a group', 'vedrixa-forms-registration-builder' );
		$error['no_user_search']       = __( 'Sorry, no user with this username in this group.', 'vedrixa-forms-registration-builder' );
		$error['change_group']         = __( 'You are changing the group of this user. All data associated with form fields of old group will be hidden and the user will have to edit and fill form fields associated with the new group. Do you wish to continue?', 'vedrixa-forms-registration-builder' );
		wp_localize_script( $this->registration_form_builder, 'wpefb_admin_error_object', $error );
	}

	private function should_load_admin_assets( $hook ) {
		$plugin_pages = array(
			'wpefb_manage_forms',
			'wpefb_form_fields',
			'wpefb_global_settings',
			'wpefb_general_settings',
			'wpefb_security',
			'wpefb_user_accounts',
			'wpefb_email_configuration',
			'wpefb_form_dashboard',
			'wpefb_form_preview',
		);

		$current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		if ( is_string( $current_page ) && in_array( $current_page, $plugin_pages, true ) ) {
			return true;
		}

		return is_string( $hook ) && false !== strpos( $hook, 'wpefb_' );
	}

	public function registration_form_builder_admin_menu() {
         add_menu_page( 'Vedrixa Forms', 'Vedrixa Forms', 'manage_options', 'wpefb_manage_forms', array( $this, 'wpefb_manage_forms' ), 'dashicons-groups' );
		add_submenu_page( 'wpefb_manage_forms_hidden', __( 'Fields Manager', 'vedrixa-forms-registration-builder' ), __( 'Fields Manager', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_form_fields', array( $this, 'wpefb_form_fields' ) );

		add_submenu_page( 'wpefb_manage_forms', __( 'Global Settings', 'vedrixa-forms-registration-builder' ), __( 'Global Settings', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_global_settings', array( $this, 'wpefb_global_settings' ) );
		if ( ! WPEFB_Features::is_pro_active() ) {
			add_submenu_page( 'wpefb_manage_forms', __( 'Pro', 'vedrixa-forms-registration-builder' ), __( 'Pro', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_pro', array( $this, 'wpefb_pro' ) );
		}
		add_submenu_page( 'wpefb_global_settings', __( 'General Settings', 'vedrixa-forms-registration-builder' ), __( 'General Settings', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_general_settings', array( $this, 'wpefb_general_settings' ) );
		add_submenu_page( 'wpefb_global_settings', __( 'Security', 'vedrixa-forms-registration-builder' ), __( 'Security', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_security', array( $this, 'wpefb_security' ) );
		add_submenu_page( 'wpefb_global_settings', __( 'User Accounts', 'vedrixa-forms-registration-builder' ), __( 'User Accounts', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_user_accounts', array( $this, 'wpefb_user_accounts' ) );
		add_submenu_page( 'wpefb_global_settings', __( 'Email Configuration', 'vedrixa-forms-registration-builder' ), __( 'Email Configuration', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_email_configuration', array( $this, 'wpefb_email_configuration' ) );
		add_submenu_page( 'wpefb_manage_forms_hidden', __( 'Form Dashboard', 'vedrixa-forms-registration-builder' ), __( 'Form Dashboard', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_form_dashboard', array( $this, 'wpefb_form_dashboard' ) );
		add_submenu_page( 'wpefb_manage_forms_hidden', __( 'Form Preview', 'vedrixa-forms-registration-builder' ), __( 'Form Preview', 'vedrixa-forms-registration-builder' ), 'manage_options', 'wpefb_form_preview', array( $this, 'wpefb_form_preview' ) );

		/**
		 * Registers add-on admin menus after the free plugin menus exist.
		 *
		 * @param Registration_Form_Builder_Admin $admin_instance Current admin controller.
		 */
		do_action( 'wpefb_register_admin_menus', $this );
	}

	/**
	 * Handle review notice actions for the All Forms page.
	 *
	 * @return void
	 */
	public function maybe_handle_manage_forms_review_notice_action() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_manage_forms' !== $page ) {
			return;
		}

		$action = filter_input( INPUT_GET, 'wpefb_review_notice_action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! is_string( $action ) || '' === $action ) {
			return;
		}

		$nonce = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! wp_verify_nonce( sanitize_text_field( (string) $nonce ), 'wpefb_review_notice_action' ) ) {
			return;
		}

		$action = sanitize_key( $action );
		if ( 'dismiss' === $action || 'reviewed' === $action ) {
			update_option( self::REVIEW_NOTICE_DISMISSED_OPTION, 1 );
			delete_option( self::REVIEW_NOTICE_REMIND_AFTER_OPTION );
		} elseif ( 'later' === $action ) {
			update_option( self::REVIEW_NOTICE_REMIND_AFTER_OPTION, time() + WEEK_IN_SECONDS );
		}

		wp_safe_redirect( admin_url( 'admin.php?page=wpefb_manage_forms' ) );
		exit;
	}

	/**
	 * Render review notice inside the dedicated All Forms template slot.
	 *
	 * @return void
	 */
	public function render_manage_forms_review_notice() {
		if ( ! $this->should_show_manage_forms_review_notice() ) {
			return;
		}

		$review_url = 'https://wordpress.org/support/plugin/vedrixa-forms-registration-builder/reviews/?filter=5#new-post';
		$reviewed_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'                       => 'wpefb_manage_forms',
					'wpefb_review_notice_action' => 'reviewed',
				),
				admin_url( 'admin.php' )
			),
			'wpefb_review_notice_action'
		);
		$later_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'                       => 'wpefb_manage_forms',
					'wpefb_review_notice_action' => 'later',
				),
				admin_url( 'admin.php' )
			),
			'wpefb_review_notice_action'
		);
		$dismiss_url = wp_nonce_url(
			add_query_arg(
				array(
					'page'                       => 'wpefb_manage_forms',
					'wpefb_review_notice_action' => 'dismiss',
				),
				admin_url( 'admin.php' )
			),
			'wpefb_review_notice_action'
		);

		?>
		<div class="wpefb-review-request" role="region" aria-label="<?php echo esc_attr__( 'Vedrixa Forms review request', 'vedrixa-forms-registration-builder' ); ?>">
			<div class="wpefb-review-request__body">
				<p class="wpefb-review-request__title"><?php esc_html_e( 'Enjoying Vedrixa Forms?', 'vedrixa-forms-registration-builder' ); ?></p>
				<p class="wpefb-review-request__text"><?php esc_html_e( 'If Vedrixa Forms is helping you build contact or registration forms, a quick WordPress.org review would really help us grow.', 'vedrixa-forms-registration-builder' ); ?></p>
			</div>
			<div class="wpefb-review-request__actions">
				<a class="button button-primary" href="<?php echo esc_url( $review_url ); ?>" target="_blank" rel="noopener noreferrer"><?php esc_html_e( 'Leave a Review', 'vedrixa-forms-registration-builder' ); ?></a>
				<a class="button" href="<?php echo esc_url( $reviewed_url ); ?>"><?php esc_html_e( 'Already Reviewed', 'vedrixa-forms-registration-builder' ); ?></a>
				<a class="button-link" href="<?php echo esc_url( $later_url ); ?>"><?php esc_html_e( 'Maybe Later', 'vedrixa-forms-registration-builder' ); ?></a>
				<a class="button-link" href="<?php echo esc_url( $dismiss_url ); ?>"><?php esc_html_e( 'Dismiss', 'vedrixa-forms-registration-builder' ); ?></a>
			</div>
		</div>
		<?php
	}

	/**
	 * Determine whether the All Forms review notice should be displayed.
	 *
	 * @return bool
	 */
	private function should_show_manage_forms_review_notice() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return false;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_manage_forms' !== $page ) {
			return false;
		}

		if ( get_option( self::REVIEW_NOTICE_DISMISSED_OPTION, 0 ) ) {
			return false;
		}

		$installed_on = absint( get_option( self::REVIEW_NOTICE_INSTALLED_ON_OPTION, 0 ) );
		if ( $installed_on <= 0 ) {
			$installed_on = time();
			add_option( self::REVIEW_NOTICE_INSTALLED_ON_OPTION, $installed_on );
		}

		$remind_after = absint( get_option( self::REVIEW_NOTICE_REMIND_AFTER_OPTION, 0 ) );
		if ( $remind_after > time() ) {
			return false;
		}

		if ( ( time() - $installed_on ) < ( 3 * DAY_IN_SECONDS ) ) {
			return false;
		}

		$dbhandler  = new WPEFB_DBhandler();
		$form_count = $dbhandler->wpefb_count( 'FORMS' );

		return is_int( $form_count ) && $form_count > 0;
	}

	public function maybe_handle_form_dashboard_submission() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_form_dashboard' !== $page || ! filter_input( INPUT_POST, 'submit_form', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) {
			return;
		}

		$retrieved_nonce = filter_input( INPUT_POST, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! wp_verify_nonce( sanitize_text_field( (string) $retrieved_nonce ), 'save_wpefb_add_form' ) ) {
			wp_die( esc_html__( 'Failed security check', 'vedrixa-forms-registration-builder' ) );
		}

		$form_id = absint( filter_input( INPUT_POST, 'form_id', FILTER_SANITIZE_NUMBER_INT ) );
		if ( $form_id <= 0 ) {
			return;
		}

		$dbhandler     = new WPEFB_DBhandler();
		$wef_activator = new Registration_Form_Builder_Activator();
		$wefrequests   = new WPEFB_Request();
		$identifier    = 'FORMS';
		$row           = $dbhandler->get_row( $identifier, $form_id );
		$meta          = array();

		if ( is_object( $row ) && isset( $row->meta ) && '' !== $row->meta ) {
			$meta = json_decode( $row->meta, true );
			$meta = is_array( $meta ) ? $meta : array();
		}

		if ( ! isset( $_POST['meta']['wpefb_create_user'] ) ) {
			$_POST['meta']['wpefb_create_user'] = 0;
		}
		if ( ! isset( $_POST['meta']['wpefb_limit_submissions'] ) ) {
			$_POST['meta']['wpefb_limit_submissions'] = 0;
		}
		if ( ! isset( $_POST['meta']['wpefb_show_submission_status'] ) ) {
			$_POST['meta']['wpefb_show_submission_status'] = 0;
		}

		$exclude        = array( '_wpnonce', '_wp_http_referer', 'submit_form', 'form_id' );
		$data           = array();
		$arg            = array();
		$sanitized_post = $wefrequests->sanitize_request( $_POST, $identifier, $exclude );

		if ( false !== $sanitized_post && null !== $sanitized_post ) {
			if ( isset( $sanitized_post['meta'] ) ) {
				$incoming_meta = json_decode( $sanitized_post['meta'], true );
				$incoming_meta = is_array( $incoming_meta ) ? $incoming_meta : array();
				/**
				 * Filters form dashboard meta before it is merged and saved.
				 *
				 * @param array $incoming_meta Incoming sanitized meta from request.
				 * @param int   $form_id       Current form ID.
				 * @param array $meta          Existing persisted meta.
				 * @param array $row           Current form row object.
				 */
				$incoming_meta          = (array) apply_filters( 'wpefb_form_dashboard_meta_before_save', $incoming_meta, $form_id, $meta, $row );
				$sanitized_post['meta'] = wp_json_encode( array_merge( $meta, $incoming_meta ) );
			}

			foreach ( $sanitized_post as $key => $value ) {
				$data[ $key ] = $value;
				$arg[]        = $wef_activator->get_db_table_field_type( $identifier, $key );
			}
		}

		if ( ! empty( $data ) ) {
			$dbhandler->update_row( $identifier, 'id', $form_id, $data, $arg, '%d' );
		}

		/**
		 * Fires after a form dashboard settings save completes.
		 *
		 * @param int   $form_id Current form ID.
		 * @param array $data    Persisted row data.
		 * @param array $meta    Previously stored meta before merge.
		 * @param array $row     Current form row object.
		 */
		do_action( 'wpefb_after_form_dashboard_save', $form_id, $data, $meta, $row );

		$redirect_args = array(
			'page' => 'wpefb_form_dashboard',
			'id'   => $form_id,
		);
		$active_tab    = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$active_tab    = is_string( $active_tab ) ? sanitize_key( $active_tab ) : '';
		$active_type   = filter_input( INPUT_GET, 'type', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$active_type   = is_string( $active_type ) ? sanitize_key( $active_type ) : '';

		if ( '' !== $active_tab && in_array( $active_tab, array( 'build', 'submissions', 'configure' ), true ) ) {
			$redirect_args['tab'] = $active_tab;
		}

		if ( 'configure' === $active_tab && '' !== $active_type && in_array( $active_type, WPEFB_Features::get_configure_types(), true ) ) {
			$redirect_args['type'] = $active_type;
		}

		wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
		exit;
	}


	public function maybe_handle_global_settings_submission() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page          = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$page_defaults = array(
			'wpefb_general_settings'    => array( 'wpefb_hide_wordpress_toolbar', 'wpefb_enable_admin_toolbar', 'wpefb_show_limit_above_form', 'wpefb_show_asterisk' ),
			'wpefb_security'            => array( 'wpefb_enable_recaptcha', 'wpefb_enable_pswd_rules' ),
			'wpefb_user_accounts'       => array( 'wpefb_usr_pass_to_user', 'wpefb_snd_activation_email' ),
			'wpefb_email_configuration' => array( 'wpefb_notify_user_submission', 'wpefb_notify_site_admin', 'wpefb_smtp_authentication' ),
		);
		$page_defaults = (array) apply_filters( 'wpefb_global_settings_page_defaults', $page_defaults, $page );

		if ( ! isset( $page_defaults[ $page ] ) ) {
			return;
		}

		$retrieved_nonce = filter_input( INPUT_POST, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );

		if ( filter_input( INPUT_POST, 'submit_settings_back', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) {
			if ( ! wp_verify_nonce( sanitize_text_field( (string) $retrieved_nonce ), 'save_wpefb_global_settings' ) ) {
				wp_die( esc_html__( 'Failed security check', 'vedrixa-forms-registration-builder' ) );
			}

			wp_safe_redirect( admin_url( 'admin.php?page=wpefb_global_settings' ) );
			exit;
		}

		if ( ! filter_input( INPUT_POST, 'submit_settings', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) {
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( (string) $retrieved_nonce ), 'save_wpefb_global_settings' ) ) {
			wp_die( esc_html__( 'Failed security check', 'vedrixa-forms-registration-builder' ) );
		}

		$dbhandler      = new WPEFB_DBhandler();
		$wefrequests    = new WPEFB_Request();
		$identifier     = 'SETTINGS';
		$exclude        = array( '_wpnonce', '_wp_http_referer', 'submit_settings' );
		$sanitized_post = $wefrequests->sanitize_request( $_POST, $identifier, $exclude );

		if ( false !== $sanitized_post && null !== $sanitized_post ) {
			/**
			 * Filters global settings payload before saving.
			 *
			 * @param array  $sanitized_post Sanitized request payload.
			 * @param string $page           Current settings page slug.
			 */
			$sanitized_post = (array) apply_filters( 'wpefb_global_settings_before_save', $sanitized_post, $page );

			foreach ( $page_defaults[ $page ] as $option_key ) {
				if ( ! isset( $sanitized_post[ $option_key ] ) ) {
					$sanitized_post[ $option_key ] = 0;
				}
			}

			foreach ( $sanitized_post as $key => $value ) {
				$dbhandler->update_global_option_value( $key, $value );
			}
		}

		/**
		 * Fires after a global settings page is saved.
		 *
		 * @param string $page Current settings page slug.
		 */
		do_action( 'wpefb_after_global_settings_save', $page );

		$redirect_args = array(
			'page'    => $page,
			'updated' => 1,
		);

		/**
		 * Filters global settings redirect args after a successful save.
		 *
		 * @param array  $redirect_args Redirect query args.
		 * @param string $page          Current settings page slug.
		 */
		$redirect_args = (array) apply_filters( 'wpefb_global_settings_redirect_args', $redirect_args, $page );

		wp_safe_redirect( add_query_arg( $redirect_args, admin_url( 'admin.php' ) ) );
		exit;
	}


	public function maybe_handle_manage_forms_submission() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_manage_forms' !== $page ) {
			return;
		}

		$dbhandler     = new WPEFB_DBhandler();
		$wef_activator = new Registration_Form_Builder_Activator();
		$wefrequests   = new WPEFB_Request();
		$identifier    = 'FORMS';

		$action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'delete' === $action ) {
			$form_id = absint( filter_input( INPUT_GET, 'form_id', FILTER_SANITIZE_NUMBER_INT ) );
			$nonce   = sanitize_text_field( (string) filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) );
			if ( $form_id && wp_verify_nonce( $nonce, 'wpefb_delete_form_' . $form_id ) ) {
				$dbhandler->remove_row( 'FIELDS', 'form_id', $form_id );
				$dbhandler->remove_row( 'SECTION', 'form_id', $form_id );
				$dbhandler->remove_row( 'SUBMISSIONS', 'form_id', $form_id );
				$dbhandler->remove_row( 'FORMS', 'id', $form_id );
			}
			wp_safe_redirect( admin_url( 'admin.php?page=wpefb_manage_forms' ) );
			exit;
		}

		if ( ! isset( $_SERVER['REQUEST_METHOD'] ) || 'POST' !== $_SERVER['REQUEST_METHOD'] || ! isset( $_POST['_wpnonce'] ) ) {
			return;
		}

		$retrieved_nonce = sanitize_text_field( wp_unslash( (string) filter_input( INPUT_POST, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ) );
		if ( ! wp_verify_nonce( $retrieved_nonce, 'save_wpefb_add_form' ) ) {
			wp_die( esc_html__( 'Failed security check', 'vedrixa-forms-registration-builder' ) );
		}

		$form_id       = absint( filter_input( INPUT_POST, 'form_id', FILTER_SANITIZE_NUMBER_INT ) );
		$form_name_raw = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$form_type_raw = absint( filter_input( INPUT_POST, 'type', FILTER_SANITIZE_NUMBER_INT ) );
		if ( 0 === (int) $form_id ) {
			if ( '' === trim( $form_name_raw ) || ! in_array( $form_type_raw, array( 1, 2 ), true ) ) {
				wp_safe_redirect( add_query_arg( 'wefb_form_create_error', '1', admin_url( 'admin.php?page=wpefb_manage_forms' ) ) );
				exit;
			}

			$create_lock_key = 'wpefb_create_form_lock_' . get_current_user_id() . '_' . md5( strtolower( trim( $form_name_raw ) ) . '|' . $form_type_raw );
			if ( get_transient( $create_lock_key ) ) {
				wp_safe_redirect( admin_url( 'admin.php?page=wpefb_manage_forms' ) );
				exit;
			}
			set_transient( $create_lock_key, 1, 15 );
		}

		$exclude        = array( '_wpnonce', '_wp_http_referer', 'submit_form', 'form_id' );
		$data           = array();
		$arg            = array();
		$sanitized_post = $wefrequests->sanitize_request( $_POST, $identifier, $exclude );
		if ( false !== $sanitized_post && null !== $sanitized_post ) {
			foreach ( $sanitized_post as $key => $value ) {
				$data[ $key ] = $value;
				$arg[]        = $wef_activator->get_db_table_field_type( $identifier, $key );
			}
		}

		if ( 0 === (int) $form_id ) {
			$posted_form_type = absint( filter_input( INPUT_POST, 'type', FILTER_SANITIZE_NUMBER_INT ) );
			$form_type        = $posted_form_type > 0 ? $posted_form_type : ( isset( $data['type'] ) ? absint( $data['type'] ) : 2 );
			$data['type']     = in_array( $form_type, array( 1, 2 ), true ) ? $form_type : 2;
			$form_type        = (int) $data['type'];
			if ( ! isset( $data['meta'] ) || '' === (string) $data['meta'] ) {
				$data['meta'] = wp_json_encode( array() );
				$arg[]        = $wef_activator->get_db_table_field_type( $identifier, 'meta' );
			}

			$build_default_field = static function ( $type, $label, $name, $placeholder, $required = true, $extra = array() ) {
				$field = array(
					'type'              => $type,
					'label'             => $label,
					'name'              => $name,
					'placeholder'       => $placeholder,
					'required'          => (bool) $required,
					'css_class'         => '',
					'default_value'     => '',
					'max_length'        => null,
					'columns'           => null,
					'rows'              => null,
					'heading_tag'       => '',
					'paragraph_text'    => '',
					'options'           => array(),
					'visibility'        => 1,
					'conditional_logic' => array(
						'enabled'  => false,
						'field'    => '',
						'operator' => '',
						'value'    => '',
					),
				);

				if ( ! empty( $extra ) && is_array( $extra ) ) {
					$field = array_merge( $field, $extra );
				}

				return $field;
			};

			if ( 1 === $form_type ) {
				$sections = array(
					array(
						'columns' => 2,
						'fields'  => array(
							$build_default_field( 'first_name', __( 'First Name', 'vedrixa-forms-registration-builder' ), 'first_name', __( 'Enter first name', 'vedrixa-forms-registration-builder' ), true ),
							$build_default_field( 'last_name', __( 'Last Name', 'vedrixa-forms-registration-builder' ), 'last_name', __( 'Enter last name', 'vedrixa-forms-registration-builder' ), true ),
						),
					),
					array(
						'columns' => 2,
						'fields'  => array(
							$build_default_field( 'user_name', __( 'Username', 'vedrixa-forms-registration-builder' ), 'user_name', __( 'Choose username', 'vedrixa-forms-registration-builder' ), true ),
							$build_default_field( 'user_email', __( 'User Email', 'vedrixa-forms-registration-builder' ), 'user_email', __( 'Enter your email', 'vedrixa-forms-registration-builder' ), true ),
						),
					),
					array(
						'columns' => 2,
						'fields'  => array(
							$build_default_field(
								'user_pass',
								__( 'Password', 'vedrixa-forms-registration-builder' ),
								'user_pass',
								__( 'Create password', 'vedrixa-forms-registration-builder' ),
								true,
								array(
									'password_min_length' => 8,
									'password_require_uppercase' => true,
									'password_require_lowercase' => true,
									'password_require_number' => true,
									'password_require_special' => false,
									'password_show_strength' => true,
								)
							),
							$build_default_field( 'confirm_pass', __( 'Confirm Password', 'vedrixa-forms-registration-builder' ), 'confirm_pass', __( 'Confirm password', 'vedrixa-forms-registration-builder' ), true ),
						),
					),
				);
			} else {
				$sections = array(
					array(
						'columns' => 2,
						'fields'  => array(
							$build_default_field( 'text', __( 'Name', 'vedrixa-forms-registration-builder' ), 'name', __( 'Enter your name', 'vedrixa-forms-registration-builder' ), true ),
							$build_default_field( 'email', __( 'Email', 'vedrixa-forms-registration-builder' ), 'email', __( 'Enter your email', 'vedrixa-forms-registration-builder' ), true ),
						),
					),
					array(
						'columns' => 2,
						'fields'  => array(
							$build_default_field( 'text', __( 'Subject', 'vedrixa-forms-registration-builder' ), 'subject', __( 'Enter subject', 'vedrixa-forms-registration-builder' ), true ),
							$build_default_field( 'textarea', __( 'Message', 'vedrixa-forms-registration-builder' ), 'message', __( 'Enter your message', 'vedrixa-forms-registration-builder' ), true, array( 'rows' => 4 ) ),
						),
					),
				);
			}

			$data['form_options'] = wp_json_encode(
				array(
					'sections' => $sections,
				)
			);
			$arg[]                = $wef_activator->get_db_table_field_type( $identifier, 'form_options' );

			if ( 1 === $form_type ) {
				$current_meta                      = json_decode( (string) $data['meta'], true );
				$current_meta                      = is_array( $current_meta ) ? $current_meta : array();
				$current_meta['wpefb_create_user'] = 1;
				$data['meta']                      = wp_json_encode( $current_meta );
			}

			$new_form_id = $dbhandler->insert_row( $identifier, $data, $arg );
			do_action( 'wpefb_add_form', $new_form_id );
		} else {
			$dbhandler->update_row( $identifier, 'id', $form_id, $data, $arg, '%d' );
			do_action( 'wpefb_update_form', (int) $form_id, $data, array() );
		}

		wp_safe_redirect( admin_url( 'admin.php?page=wpefb_manage_forms' ) );
		exit;
	}

	public function maybe_handle_form_dashboard_navigation() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_form_dashboard' !== $page ) {
			return;
		}

		$current_form_id = absint( filter_input( INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT ) );
		$active_tab      = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$active_tab      = is_string( $active_tab ) ? sanitize_key( $active_tab ) : '';
		$active_type     = filter_input( INPUT_GET, 'type', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$active_type     = is_string( $active_type ) ? sanitize_key( $active_type ) : '';

		if ( '' === $active_tab ) {
			return;
		}

		$allowed_tabs = array( 'build', 'submissions', 'configure' );
		if ( ! in_array( $active_tab, $allowed_tabs, true ) ) {
			wp_safe_redirect( admin_url( 'admin.php?page=wpefb_form_dashboard&id=' . $current_form_id ) );
			exit;
		}

		if ( 'build' === $active_tab ) {
			wp_safe_redirect( admin_url( 'admin.php?page=wpefb_form_fields&id=' . $current_form_id ) );
			exit;
		}

		if ( 'configure' === $active_tab ) {
			$allowed_types = WPEFB_Features::get_configure_types();
			if ( ! in_array( $active_type, $allowed_types, true ) ) {
				wp_safe_redirect( admin_url( 'admin.php?page=wpefb_form_dashboard&id=' . $current_form_id ) );
				exit;
			}
		}
	}

	public function maybe_handle_submission_user_action() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		$page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$tab  = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'wpefb_form_dashboard' !== $page || 'submissions' !== $tab ) {
			return;
		}

		$user_action = filter_input( INPUT_GET, 'user_action', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$user_id     = absint( filter_input( INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT ) );
		$nonce       = sanitize_text_field( (string) filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) );
		if ( ! $user_action || ! $user_id || '' === $nonce ) {
			return;
		}

		$helper      = new WPEFB_Helper();
		$allowed     = array( 'activate', 'deactivate' );
		$user_action = sanitize_key( $user_action );
		if ( in_array( $user_action, $allowed, true ) && wp_verify_nonce( $nonce, 'wpefb_user_status_' . $user_id ) ) {
			$next_status = ( 'activate' === $user_action ) ? 'active' : 'inactive';
			$helper->update_user_account_status( $user_id, $next_status );
		}

		$current_request_uri = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$redirect_target     = '' !== $current_request_uri ? $current_request_uri : admin_url( 'admin.php?page=wpefb_form_dashboard&tab=submissions' );
		wp_safe_redirect( remove_query_arg( array( 'user_action', 'user_id', '_wpnonce' ), $redirect_target ) );
		exit;
	}

	public function wpefb_form_dashboard() {

		include __DIR__ . '/partials/arf-form-dashboard.php';
	}
	public function wpefb_form_preview() {

		include __DIR__ . '/partials/form-preview.php';
    }
	public function wpefb_manage_forms() {

		include __DIR__ . '/partials/arf-manage-forms.php';
    }

	public function wpefb_form_fields() {

		 include __DIR__ . '/partials/fields.php';
	}

	public function wpefb_global_settings() {

		 include __DIR__ . '/partials/global-settings.php';
	}

	public function wpefb_general_settings() {

		include __DIR__ . '/partials/global-settings-configure-general-settings.php';
	}

	public function wpefb_security() {

		include __DIR__ . '/partials/global-settings-configure-security.php';
	}

	public function wpefb_user_accounts() {

        include __DIR__ . '/partials/global-settings-configure-user-accounts.php';
	}

	public function wpefb_email_configuration() {

		include __DIR__ . '/partials/global-settings-configure-email-configuration.php';
	}

	public function wpefb_pro() {
		if ( WPEFB_Features::is_pro_active() ) {
			wp_safe_redirect( admin_url( 'admin.php?page=wpefb_manage_forms' ) );
			exit;
		}

		include __DIR__ . '/partials/pro-page.php';
	}

	public function wefb_save_form_structure() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error(
				array(
					'message' => esc_html__( 'Unauthorized.', 'vedrixa-forms-registration-builder' ),
				),
				403
			);
		}

		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'wpefb_save_form_structure' ) ) {
			wp_send_json_error(
				array(
					'message' => esc_html__( 'Failed security check.', 'vedrixa-forms-registration-builder' ),
				),
				403
			);
		}
		$dbhandler  = new WPEFB_DBhandler();
		$identifier = 'FORMS';

		$form_id      = isset( $_POST['form_id'] ) ? absint( $_POST['form_id'] ) : 0;
		$form_options = isset( $_POST['form_options'] ) ? sanitize_textarea_field( wp_unslash( $_POST['form_options'] ) ) : '';

		if ( ! $form_id || empty( $form_options ) ) {
			wp_send_json_error( array( 'message' => 'Invalid input' ) );
		}

		$form_options_array = json_decode( $form_options, true );
		if ( JSON_ERROR_NONE !== json_last_error() || ! is_array( $form_options_array ) ) {
			wp_send_json_error( array( 'message' => 'Invalid form options payload.' ) );
		}

		$pro_validation = $this->validate_pro_field_usage_for_save( $form_id, $form_options_array );
		if ( is_wp_error( $pro_validation ) ) {
			wp_send_json_error( array( 'message' => $pro_validation->get_error_message() ) );
		}

		$has_email_field = false;
		if ( ! empty( $form_options_array['sections'] ) && is_array( $form_options_array['sections'] ) ) {
			foreach ( $form_options_array['sections'] as $section ) {
				if ( empty( $section['fields'] ) || ! is_array( $section['fields'] ) ) {
					continue;
				}
				foreach ( $section['fields'] as $field ) {
					$type = isset( $field['type'] ) ? sanitize_key( (string) $field['type'] ) : '';
					if ( in_array( $type, array( 'email', 'user_email' ), true ) ) {
						$has_email_field = true;
						break 2;
					}
				}
			}
		}

		if ( ! $has_email_field ) {
			wp_send_json_error( array( 'message' => __( 'Please add at least one Email field before saving.', 'vedrixa-forms-registration-builder' ) ) );
		}

		$data   = array( 'form_options' => wp_json_encode( $form_options_array ) );
		$result = $dbhandler->update_row( $identifier, 'id', $form_id, $data, array( '%s' ), '%d' );

		if ( $result !== false ) {
			wp_send_json_success( array( 'message' => 'Form structure saved.' ) );
		} else {
			wp_send_json_error( array( 'message' => 'Database update failed.' ) );
		}
	}


	/**
	 * Validate whether submitted form options contain newly added pro-only fields.
	 *
	 * @param int   $form_id            Current form id.
	 * @param array $form_options_array Submitted form options payload.
	 * @return true|WP_Error
	 */
	private function validate_pro_field_usage_for_save( $form_id, $form_options_array ) {
		if ( WPEFB_Features::is_pro_active() ) {
			return true;
		}

		$locked_types = WPEFB_Features::get_locked_field_types();
		if ( empty( $locked_types ) ) {
			return true;
		}

		$incoming_locked = $this->collect_locked_fields_from_form_options( $form_options_array, $locked_types );
		if ( empty( $incoming_locked ) ) {
			return true;
		}

		$existing_locked = array();
		if ( $form_id > 0 ) {
			$dbhandler    = new WPEFB_DBhandler();
			$existing_row = $dbhandler->get_row( 'FORMS', $form_id );
			if ( is_object( $existing_row ) && isset( $existing_row->form_options ) && '' !== $existing_row->form_options ) {
				$existing_options = json_decode( (string) $existing_row->form_options, true );
				if ( is_array( $existing_options ) ) {
					$existing_locked = $this->collect_locked_fields_from_form_options( $existing_options, $locked_types );
				}
			}
		}

		$new_locked_types = array();
		foreach ( $incoming_locked as $incoming_id => $incoming_type ) {
			if ( '' === $incoming_id || ! isset( $existing_locked[ $incoming_id ] ) || $existing_locked[ $incoming_id ] !== $incoming_type ) {
				$new_locked_types[] = $incoming_type;
			}
		}

		if ( empty( $new_locked_types ) ) {
			return true;
		}

		$labels = array();
		foreach ( array_unique( $new_locked_types ) as $field_type ) {
			$labels[] = $this->format_field_type_label( $field_type );
		}

		/* translators: %s: Comma separated pro-only field names. */
		$message = sprintf( __( 'The following fields are available in Pro only: %s', 'vedrixa-forms-registration-builder' ), implode( ', ', $labels ) );

		return new WP_Error( 'wpefb_pro_fields_locked', $message );
	}

	/**
	 * Collect locked field IDs/types from form options payload.
	 *
	 * @param array $form_options Form options payload.
	 * @param array $locked_types Locked field types.
	 * @return array
	 */
	private function collect_locked_fields_from_form_options( $form_options, $locked_types ) {
		$collected = array();

		if ( empty( $form_options['sections'] ) || ! is_array( $form_options['sections'] ) ) {
			return $collected;
		}

		foreach ( $form_options['sections'] as $section ) {
			if ( empty( $section['fields'] ) || ! is_array( $section['fields'] ) ) {
				continue;
			}

			foreach ( $section['fields'] as $field ) {
				$type = isset( $field['type'] ) ? sanitize_key( (string) $field['type'] ) : '';
				if ( '' === $type || ! in_array( $type, $locked_types, true ) ) {
					continue;
				}

				$field_id               = isset( $field['id'] ) ? sanitize_key( (string) $field['id'] ) : '';
				$collected[ $field_id ] = $type;
			}
		}

		return $collected;
	}

	/**
	 * Convert field type key to readable label.
	 *
	 * @param string $field_type Field type key.
	 * @return string
	 */
	private function format_field_type_label( $field_type ) {
		$field_type = str_replace( '_', ' ', (string) $field_type );
		return ucwords( trim( $field_type ) );
	}

}
