<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals

if ( ! defined( 'ABSPATH' ) ) {
	 exit;
}

$dbhandler = new WPEFB_DBhandler();
$helper    = new WPEFB_Helper();

$fid = filter_input( INPUT_GET, 'id', FILTER_VALIDATE_INT );
if ( ! $fid && isset( $attributes['id'] ) ) {
	$fid = absint( $attributes['id'] );
}

if ( ! $fid ) {
	return '';
}

$form = $dbhandler->get_row( 'FORMS', $fid );
if ( ! $form ) {
	return '';
}

$form_id         = (int) $form->id;
$form_data       = ! empty( $form->form_options ) ? json_decode( $form->form_options, true ) : array();
$form_meta       = ! empty( $form->meta ) ? json_decode( $form->meta, true ) : array();
$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_show_limit_above_form' => $dbhandler->get_global_option_value( 'wpefb_show_limit_above_form', 0 ),
	'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 ),
);

$form_errors      = array();
$success          = false;
$success_message  = '';
$redirect_url     = '';
$posted_form_id   = isset( $_POST['wefb_form_id'] ) ? absint( wp_unslash( $_POST['wefb_form_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing
$should_handle_me = $posted_form_id > 0 && $posted_form_id === $form_id;
$activation_flag  = isset( $_GET['wefb_activation'] ) ? sanitize_key( wp_unslash( $_GET['wefb_activation'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'] && isset( $_POST['wefb_form_submit'] ) && $should_handle_me ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
	if ( ! isset( $_POST['wefb_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['wefb_nonce'] ) ), 'wefb_submit_form_' . $form_id ) ) {
		$form_errors[] = __( 'Security check failed. Please try again.', 'vedrixa-forms-registration-builder' );
	} else {
		$result = $helper->wefb_process_submission( $form_data, $form_id );
		if ( is_wp_error( $result ) ) {
			$form_errors = array_merge( $form_errors, $result->get_error_messages() );
		} else {
			$success = true;
			if ( is_array( $result ) ) {
				$success_message = ! empty( $result['success_message'] ) ? $result['success_message'] : '';
				$redirect_url    = ! empty( $result['redirect_url'] ) ? $result['redirect_url'] : '';
			}
		}
	}
}

if ( $success ) {
	if ( ! empty( $redirect_url ) ) {
		if ( ! headers_sent() ) {
			wp_safe_redirect( $redirect_url );
			exit;
		}
		echo '<div class="wefb-success">' . esc_html__( 'Submission received. Please use this link to continue.', 'vedrixa-forms-registration-builder' ) . ' <a href="' . esc_url( $redirect_url ) . '">' . esc_html__( 'Continue', 'vedrixa-forms-registration-builder' ) . '</a></div>';
		return;
	}
	if ( empty( $success_message ) ) {
		$success_message = __( 'Thank you! Your submission has been received.', 'vedrixa-forms-registration-builder' );
	}
	echo '<div class="wefb-success">' . wp_kses_post( $success_message ) . '</div>';
	return;
}

if ( empty( $form_data ) || empty( $form_data['sections'] ) ) {
	return '';
}

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

if ( ! $has_email_field ) {
	echo '<div class="wefb-errors"><ul><li>' . esc_html__( 'This form requires an Email field. Please contact the site administrator.', 'vedrixa-forms-registration-builder' ) . '</li></ul></div>';
	return '';
}

if ( 'success' === $activation_flag ) {
	echo '<div class="wefb-success">' . esc_html__( 'Your account has been activated. You can now log in.', 'vedrixa-forms-registration-builder' ) . '</div>';
} elseif ( 'invalid' === $activation_flag ) {
	echo '<div class="wefb-errors"><ul><li>' . esc_html__( 'Activation link is invalid or expired.', 'vedrixa-forms-registration-builder' ) . '</li></ul></div>';
}

if ( ! empty( $form_errors ) ) {
	echo '<div class="wefb-errors"><ul>';
	foreach ( $form_errors as $form_error ) {
		echo '<li>' . esc_html( $form_error ) . '</li>';
	}
	echo '</ul></div>';
}

$show_limit = ! empty( $form_meta['wpefb_limit_submissions'] ) && ! empty( $form_meta['wpefb_show_submission_status'] );
if ( $show_limit ) {
	$total_limit = isset( $form_meta['submission_limit'] ) ? (int) $form_meta['submission_limit'] : 0;
	if ( $total_limit > 0 ) {
		$current_count = (int) $dbhandler->wpefb_count( 'SUBMISSIONS', array( 'form_id' => $form_id ) );
		echo '<div class="wefb-limit-status">';
		/* translators: 1: Current submission count, 2: Total limit. */
		echo esc_html( sprintf( __( '%1$d of %2$d submissions received.', 'vedrixa-forms-registration-builder' ), $current_count, $total_limit ) );
		echo '</div>';
	}
}

if ( ! empty( $form_meta['wpefb_form_description'] ) ) {
	echo '<div class="wefb-form-description">' . wp_kses_post( wpautop( $form_meta['wpefb_form_description'] ) ) . '</div>';
}

$renderer = new WPEFB_Form_Renderer(
	$form_data,
	$attributes,
	array(
		'form_meta' => $form_meta,
		'global'    => $global_settings,
	)
);
if ( ! empty( $form_meta['before_form'] ) ) {
	echo '<div class="wefb-before-form">' . wp_kses_post( $form_meta['before_form'] ) . '</div>';
}
// Renderer returns full form HTML including controlled field markup.
echo $renderer->render_form( $form_id ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

if ( ! empty( $global_settings['wpefb_enable_recaptcha'] ) && ! empty( $global_settings['wpefb_recaptcha_site_key'] ) ) {
	$recaptcha_version  = ! empty( $global_settings['wpefb_recaptcha_version'] ) ? sanitize_key( $global_settings['wpefb_recaptcha_version'] ) : 'v2';
	$recaptcha_site_key = sanitize_text_field( $global_settings['wpefb_recaptcha_site_key'] );
	if ( 'v3' === $recaptcha_version ) {
		wp_enqueue_script(
			'wefb-recaptcha-v3',
			'https://www.google.com/recaptcha/api.js?render=' . rawurlencode( $recaptcha_site_key ),
			array(),
			WPEFB_PLUGIN_VERSION,
			true
		);
		wp_add_inline_script(
			'wefb-recaptcha-v3',
			"(function(){if(typeof grecaptcha==='undefined'){return;}grecaptcha.ready(function(){document.querySelectorAll('.wefb-frontend-form').forEach(function(formEl){formEl.addEventListener('submit',function(evt){var input=formEl.querySelector('.wefb-recaptcha-token');if(input&&input.value){return;}evt.preventDefault();grecaptcha.execute('" . esc_js( $recaptcha_site_key ) . "',{action:'submit'}).then(function(token){if(input){input.value=token;}formEl.submit();});});});});})();"
		);
	} else {
		wp_enqueue_script(
			'wefb-recaptcha-v2',
			'https://www.google.com/recaptcha/api.js',
			array(),
			WPEFB_PLUGIN_VERSION,
			true
		);
	}
}

wp_enqueue_script( 'easy-form-frontend-formbuilder' );
