<?php

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

/**
 * The public-facing 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/public
 * @author     Vedrixa <support@registrationformbuilder.com>
 */
class Registration_Form_Builder_Public {

	/**
	 * 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 the 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;

	}

	/**
	 * Register the stylesheets for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {
		if ( ! $this->should_load_public_assets() ) {
			return;
		}

		wp_enqueue_style( $this->registration_form_builder, plugin_dir_url( __FILE__ ) . 'css/registration-form-builder-public.css', array(), $this->version, 'all' );
	}

	/**
	 * Register the JavaScript for the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {
		if ( ! $this->should_load_public_assets() ) {
			return;
		}

		wp_enqueue_script( $this->registration_form_builder, plugin_dir_url( __FILE__ ) . 'js/registration-form-builder-public.js', array( 'jquery' ), $this->version, true );
		$error                                 = array();
		$error['valid_email']                  = esc_html__( 'Please enter a valid e-mail address.', 'vedrixa-forms-registration-builder' );
		$error['valid_number']                 = esc_html__( 'Please enter a valid number.', 'vedrixa-forms-registration-builder' );
		$error['required_field']               = esc_html__( 'This is a required field.', 'vedrixa-forms-registration-builder' );
		$error['required_comman_field']        = esc_html__( 'Please fill all the required fields.', 'vedrixa-forms-registration-builder' );
		$error['file_type']                    = esc_html__( 'This file type is not allowed.', 'vedrixa-forms-registration-builder' );
		$error['short_password']               = esc_html__( 'Your password should be at least 7 characters long.', 'vedrixa-forms-registration-builder' );
		$error['pass_not_match']               = esc_html__( 'Password and confirm password do not match.', 'vedrixa-forms-registration-builder' );
		$error['user_exist']                   = esc_html__( 'Sorry, username already exists.', 'vedrixa-forms-registration-builder' );
		$error['email_exist']                  = esc_html__( 'Sorry, email already exists.', 'vedrixa-forms-registration-builder' );
		$error['show_more']                    = esc_html__( 'More...', 'vedrixa-forms-registration-builder' );
		$error['show_less']                    = esc_html__( 'Show less', 'vedrixa-forms-registration-builder' );
		$error['user_not_exit']                = esc_html__( 'Username does not exists.', 'vedrixa-forms-registration-builder' );
		$error['password_change_successfully'] = esc_html__( 'Password changed Successfully', 'vedrixa-forms-registration-builder' );
		$error['valid_phone_number']           = esc_html__( 'Please enter a valid phone number.', 'vedrixa-forms-registration-builder' );
		$error['valid_mobile_number']          = esc_html__( 'Please enter a valid mobile number.', 'vedrixa-forms-registration-builder' );
		$error['valid_facebook_url']           = esc_html__( 'Please enter a valid Facebook url.', 'vedrixa-forms-registration-builder' );
		$error['valid_twitter_url']            = esc_html__( 'Please enter a Twitter url.', 'vedrixa-forms-registration-builder' );
		$error['valid_google_url']             = esc_html__( 'Please enter a valid Google url.', 'vedrixa-forms-registration-builder' );
		$error['valid_linked_in_url']          = esc_html__( 'Please enter a Linked In url.', 'vedrixa-forms-registration-builder' );
		$error['valid_youtube_url']            = esc_html__( 'Please enter a valid Youtube url.', 'vedrixa-forms-registration-builder' );
		$error['valid_mixcloud_url']           = esc_html__( 'Please enter a valid Mixcloud url.', 'vedrixa-forms-registration-builder' );
		$error['valid_soundcloud_url']         = esc_html__( 'Please enter a valid SoundCloud url.', 'vedrixa-forms-registration-builder' );
		$error['valid_instagram_url']          = esc_html__( 'Please enter a valid Instagram url.', 'vedrixa-forms-registration-builder' );
		$error['crop_alert_error']             = esc_html__( 'Please select a crop region then press submit.', 'vedrixa-forms-registration-builder' );
		$error['admin_note_error']             = esc_html__( 'Unable to add an empty note. Please write something and try again.', 'vedrixa-forms-registration-builder' );
		$error['empty_message_error']          = esc_html__( 'Unable to send an empty message. Please type something.', 'vedrixa-forms-registration-builder' );
		$error['invite_limit_error']           = esc_html__( 'Only ten users can be invited at a time.', 'vedrixa-forms-registration-builder' );
		$error['no_more_result']               = esc_html__( 'No More Result Found', 'vedrixa-forms-registration-builder' );
		$error['delete_friend_request']        = esc_html__( 'This will delete friend request from selected user(s). Do you wish to continue?', 'vedrixa-forms-registration-builder' );
		$error['remove_friend']                = esc_html__( 'This will remove selected user(s) from your friends list. Do you wish to continue?', 'vedrixa-forms-registration-builder' );
		$error['accept_friend_request_conf']   = esc_html__( 'This will accept request from selected user(s). Do you wish to continue?', 'vedrixa-forms-registration-builder' );
		$error['cancel_friend_request']        = esc_html__( 'This will cancel request from selected user(s). Do you wish to continue?', 'vedrixa-forms-registration-builder' );
		$error['next']                         = esc_html__( 'Next', 'vedrixa-forms-registration-builder' );
		$error['back']                         = esc_html__( 'Back', 'vedrixa-forms-registration-builder' );
		$error['submit']                       = esc_html__( 'Submit', 'vedrixa-forms-registration-builder' );
		$error['review_highlighted_fields']    = esc_html__( 'Please review the highlighted required fields.', 'vedrixa-forms-registration-builder' );
		$error['empty_chat_message']           = esc_html__( "I am sorry, I can't send an empty message. Please write something and try sending it again.", 'vedrixa-forms-registration-builder' );
		wp_localize_script( $this->registration_form_builder, 'wpefb_error_object', $error );

		wp_register_script( 'easy-form-frontend-formbuilder', plugin_dir_url( __FILE__ ) . 'js/registration-form-builder-main.js', array( 'jquery' ), $this->version, true );
	}

	private function should_load_public_assets() {
		if ( is_admin() ) {
			return false;
		}

		if ( is_singular() ) {
			$post_id = get_queried_object_id();
			if ( $post_id > 0 ) {
				$content = (string) get_post_field( 'post_content', $post_id );
				if ( has_shortcode( $content, 'wpefb_registration' ) ) {
					return true;
				}
			}
		}

		return false;
	}

	/**
	 * Configure SMTP transport for outgoing plugin emails.
	 *
	 * @param PHPMailer $phpmailer PHPMailer instance.
	 *
	 * @return void
	 */
	public function configure_phpmailer( $phpmailer ) {
		$dbhandler = new WPEFB_DBhandler();
		$handler   = sanitize_key( (string) $dbhandler->get_global_option_value( 'wpefb_outgoing_emails', 'WordPress' ) );
		if ( 'smtp' !== $handler ) {
			return;
		}

		$host = sanitize_text_field( (string) $dbhandler->get_global_option_value( 'wpefb_smtp_host', '' ) );
		if ( '' === $host ) {
			return;
		}

		$phpmailer->isSMTP();
		$phpmailer->Host = $host;

		$port = absint( $dbhandler->get_global_option_value( 'wpefb_smtp_port', 0 ) );
		if ( $port > 0 ) {
			$phpmailer->Port = $port;
		}

		$encryption_map = array(
			'enc_tls' => 'tls',
			'enc_ssl' => 'ssl',
		);
		$encryption_raw = sanitize_key( (string) $dbhandler->get_global_option_value( 'wpefb_encryption_type', 'none' ) );
		if ( isset( $encryption_map[ $encryption_raw ] ) ) {
			$phpmailer->SMTPSecure = $encryption_map[ $encryption_raw ];
		}

		$requires_auth       = ! empty( $dbhandler->get_global_option_value( 'wpefb_smtp_authentication', 0 ) );
		$phpmailer->SMTPAuth = $requires_auth;
		if ( $requires_auth ) {
			$phpmailer->Username = sanitize_text_field( (string) $dbhandler->get_global_option_value( 'wpefb_smtp_username', '' ) );
			$phpmailer->Password = (string) $dbhandler->get_global_option_value( 'wpefb_smtp_password', '' );
		}

		$from_email = sanitize_email( (string) $dbhandler->get_global_option_value( 'wpefb_smtp_sender_email', '' ) );
		if ( ! is_email( $from_email ) ) {
			$from_email = sanitize_email( (string) $dbhandler->get_global_option_value( 'wpefb_senders_email', get_option( 'admin_email' ) ) );
		}
		$from_name = sanitize_text_field( (string) $dbhandler->get_global_option_value( 'wpefb_senders_display_name', get_bloginfo( 'name' ) ) );
		if ( is_email( $from_email ) ) {
			$phpmailer->setFrom( $from_email, $from_name, false );
		}
	}

	/**
	 * Hide/show frontend admin toolbar based on plugin global settings.
	 *
	 * @param bool $show_admin_bar Current visibility.
	 *
	 * @return bool
	 */
	public function control_admin_toolbar_visibility( $show_admin_bar ) {
		if ( is_admin() || ! is_user_logged_in() ) {
			return $show_admin_bar;
		}

		$dbhandler    = new WPEFB_DBhandler();
		$hide_toolbar = ! empty( $dbhandler->get_global_option_value( 'wpefb_hide_wordpress_toolbar', 0 ) );
		if ( ! $hide_toolbar ) {
			return $show_admin_bar;
		}

		$allow_admin_toolbar = ! empty( $dbhandler->get_global_option_value( 'wpefb_enable_admin_toolbar', 0 ) );
		if ( $allow_admin_toolbar && current_user_can( 'manage_options' ) ) {
			return true;
		}

		return false;
	}

	public function register_shortcodes() {

            add_shortcode( 'wpefb_registration', array( $this, 'easy_form_builder_registration_form' ) );
	}

	public function register_preview_query_vars( $vars ) {

		$vars[] = 'wefb_preview';
		$vars[] = 'wefb_form_id';
		return $vars;
	}


	/**
	 * Process account activation links for verify-mode registrations.
	 *
	 * @return void
	 */
	public function maybe_process_account_activation() {
		$activate = absint( filter_input( INPUT_GET, 'wefb_activate', FILTER_SANITIZE_NUMBER_INT ) );
		if ( 1 !== $activate ) {
			return;
		}

		$user_id = absint( filter_input( INPUT_GET, 'uid', FILTER_SANITIZE_NUMBER_INT ) );
		$token   = sanitize_text_field( (string) filter_input( INPUT_GET, 'token', FILTER_SANITIZE_FULL_SPECIAL_CHARS ) );

		$redirect_base = $this->get_configured_registration_page_url();
		if ( '' === $redirect_base ) {
			$redirect_base = home_url( '/' );
		}

		if ( $user_id <= 0 || '' === $token ) {
			wp_safe_redirect( add_query_arg( 'wefb_activation', 'invalid', $redirect_base ) );
			exit;
		}

		$helper    = new WPEFB_Helper();
		$activated = $helper->activate_user_from_token( $user_id, $token );
		$status    = $activated ? 'success' : 'invalid';

		wp_safe_redirect( add_query_arg( 'wefb_activation', $status, $redirect_base ) );
		exit;
	}


	/**
	 * Render activation status notice after account verification redirect.
	 *
	 * @return void
	 */
	public function render_activation_notice() {
		static $notice_rendered = false;
		if ( $notice_rendered || is_admin() || $this->current_page_has_registration_shortcode() ) {
			return;
		}

		$activation_flag = isset( $_GET['wefb_activation'] ) ? sanitize_key( wp_unslash( $_GET['wefb_activation'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( '' === $activation_flag ) {
			return;
		}

		if ( 'success' === $activation_flag ) {
			$message = __( 'Your account has been activated successfully. You can now log in.', 'vedrixa-forms-registration-builder' );
			$class   = 'wefb-notice-success';
		} elseif ( 'invalid' === $activation_flag ) {
			$message = __( 'Activation link is invalid or expired.', 'vedrixa-forms-registration-builder' );
			$class   = 'wefb-notice-error';
		} else {
			return;
		}

		wp_register_style( 'wpefb-activation-notice', false, array(), $this->version );
		wp_enqueue_style( 'wpefb-activation-notice' );
		wp_add_inline_style( 'wpefb-activation-notice', '.wefb-activation-notice{max-width:960px;margin:16px auto;padding:12px 16px;border-radius:6px;font-size:14px;line-height:1.5}.wefb-notice-success{background:#ecf7ed;border:1px solid #9ad0a0;color:#0d532b}.wefb-notice-error{background:#fdecec;border:1px solid #ef9a9a;color:#7a1111}' );
		echo '<div class="wefb-activation-notice ' . esc_attr( $class ) . '">' . esc_html( $message ) . '</div>';
		$notice_rendered = true;
	}


	/**
	 * Override WordPress registration URL to configured registration form page.
	 *
	 * @param string $register_url Default registration URL.
	 *
	 * @return string
	 */
	public function filter_register_url( $register_url ) {
		$custom_url = $this->get_configured_registration_page_url();
		if ( '' !== $custom_url ) {
			return $custom_url;
		}

		return $register_url;
	}

	/**
	 * Resolve configured registration page URL from global settings.
	 *
	 * @return string
	 */
	private function get_configured_registration_page_url() {
		$dbhandler = new WPEFB_DBhandler();
		$page_id   = absint( $dbhandler->get_global_option_value( 'wpefb_registration_page_id', 0 ) );
		if ( $page_id <= 0 ) {
			return '';
		}

		$page = get_post( $page_id );
		if ( ! $page || 'page' !== $page->post_type || 'publish' !== $page->post_status ) {
			return '';
		}

		$page_url = get_permalink( $page_id );
		if ( ! is_string( $page_url ) || '' === $page_url ) {
			return '';
		}

		return $page_url;
	}

	/**
	 * Check whether current singular page includes the registration shortcode.
	 *
	 * @return bool
	 */
	private function current_page_has_registration_shortcode() {
		if ( ! is_singular( 'page' ) ) {
			return false;
		}

		$post_id = get_queried_object_id();
		if ( ! $post_id ) {
			return false;
		}

		$post = get_post( $post_id );
		if ( ! $post || ! isset( $post->post_content ) ) {
			return false;
		}

		return has_shortcode( (string) $post->post_content, 'wpefb_registration' );
	}

	/**
	 * Block login when plugin-managed status is inactive or pending.
	 *
	 * @param WP_User|WP_Error|null $user WP auth result.
	 * @param string                $username Username.
	 * @param string                $password Password.
	 *
	 * @return WP_User|WP_Error|null
	 */
	public function block_inactive_users_login( $user, $username, $password ) {
		unset( $username, $password );
		if ( ! $user instanceof WP_User ) {
			return $user;
		}

		$helper = new WPEFB_Helper();
		$status = $helper->get_user_account_status( $user->ID );

		if ( 'inactive' === $status ) {
			return new WP_Error( 'wpefb_user_inactive', __( 'Your account is pending admin approval.', 'vedrixa-forms-registration-builder' ) );
		}

		if ( 'pending' === $status ) {
			return new WP_Error( 'wpefb_user_pending', __( 'Please verify your email address before logging in.', 'vedrixa-forms-registration-builder' ) );
		}

		return $user;
	}

	public function maybe_render_preview() {

		$is_preview  = get_query_var( 'wefb_preview' );
		$get_preview = filter_input( INPUT_GET, 'wefb_preview', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( empty( $is_preview ) && empty( $get_preview ) ) {
			return;
		}

		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( esc_html__( 'You do not have permission to preview this form.', 'vedrixa-forms-registration-builder' ) );
		}

		$form_id     = absint( get_query_var( 'wefb_form_id' ) );
		$get_form_id = filter_input( INPUT_GET, 'wefb_form_id', FILTER_SANITIZE_NUMBER_INT );
		if ( ! $form_id && ! empty( $get_form_id ) ) {
			$form_id = absint( $get_form_id );
		}

		if ( ! $form_id ) {
			wp_die( esc_html__( 'Missing form ID.', 'vedrixa-forms-registration-builder' ) );
		}

		$dbhandler = new WPEFB_DBhandler();
		$form      = $dbhandler->get_row( 'FORMS', $form_id );
		if ( ! $form ) {
			wp_die( esc_html__( 'Form not found.', 'vedrixa-forms-registration-builder' ) );
		}

		$form_data = ! empty( $form->form_options ) ? json_decode( $form->form_options, true ) : array();
		$form_meta = ! empty( $form->meta ) ? json_decode( $form->meta, true ) : array();
		if ( empty( $form_data ) || empty( $form_data['sections'] ) ) {
			wp_die( esc_html__( 'Form has no fields to preview.', 'vedrixa-forms-registration-builder' ) );
		}
		$global_settings = array(
			'wpefb_show_asterisk'         => $dbhandler->get_global_option_value( 'wpefb_show_asterisk', 1 ),
			'wpefb_form_theme'            => $dbhandler->get_global_option_value( 'wpefb_form_theme', 'default' ),
			'wpefb_form_layout'           => $dbhandler->get_global_option_value( 'wpefb_form_layout', 'label_top' ),
			'wpefb_enable_recaptcha'      => $dbhandler->get_global_option_value( 'wpefb_enable_recaptcha', 0 ),
			'wpefb_recaptcha_version'     => $dbhandler->get_global_option_value( 'wpefb_recaptcha_version', 'v2' ),
			'wpefb_recaptcha_site_key'    => $dbhandler->get_global_option_value( 'wpefb_recaptcha_site_key', '' ),
			'wpefb_multiple_file_uploads' => $dbhandler->get_global_option_value( 'wpefb_multiple_file_uploads', 0 ),
		);
		status_header( 200 );
		nocache_headers();
		$this->enqueue_styles();
		$this->enqueue_scripts();
		get_header();
		echo '<main class="wefb-preview-wrap">';
		echo '<div class="wefb-preview-inner">';
		echo '<h1>' . esc_html__( 'Form Preview', 'vedrixa-forms-registration-builder' ) . '</h1>';
		if ( ! empty( $form_meta['wpefb_form_description'] ) ) {
			echo '<div class="wefb-form-description">' . wp_kses_post( wpautop( $form_meta['wpefb_form_description'] ) ) . '</div>';
		}
		if ( ! empty( $form_meta['before_form'] ) ) {
			echo '<div class="wefb-before-form">' . wp_kses_post( $form_meta['before_form'] ) . '</div>';
		}
		$renderer = new WPEFB_Form_Renderer(
            $form_data,
            array(),
            array(
				'form_meta' => $form_meta,
				'global'    => $global_settings,
			)
        );
		echo wp_kses_post( $renderer->render_form( $form_id ) );
		echo '</div>';
		echo '</main>';
		get_footer();
		exit;
	}

	public function easy_form_builder_registration_form( $atts ) {

            $atts = array_change_key_case( (array) $atts, CASE_LOWER );
		if ( empty( $atts['id'] ) ) {
			$request_id = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );
			if ( $request_id ) {
				$atts['id'] = absint( $request_id );
			}
		}
            $template = 'registration-form';
		return $this->easy_form_builder_get_template_html( $template, $atts );
	}


	public function easy_form_builder_get_template_html( $template_name, $attributes, $content = null ) {
		$template_name = sanitize_key( $template_name );
		$template_file = __DIR__ . '/partials/' . $template_name . '.php';
		if ( ! file_exists( $template_file ) ) {
			return '';
		}

		ob_start();
		do_action( 'wpefb_before_' . $template_name, $template_name, $attributes );
		require $template_file;
		do_action( 'wpefb_after_' . $template_name );
		$html = ob_get_contents();
		ob_end_clean();
		return $html;
	}

}
