<?php
/**
 * Contact and newsletter forms.
 *
 * Both forms remain available as shortcodes for backwards compatibility and
 * are also rendered by native dynamic Gutenberg blocks.
 *
 * @package HaPantheon
 */

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

/**
 * Build a safe return URL for front-end forms.
 *
 * @param string $status_query Query-string key and value.
 * @return string
 */
function hapantheon_form_return_url( $status_query ) {
	$referer = wp_get_referer();
	if ( ! $referer ) {
		$referer = home_url( '/' );
	}
	$referer = wp_validate_redirect( $referer, home_url( '/' ) );

	$referer = remove_query_arg(
		array(
			'hapantheon_contact',
			'hapantheon_newsletter',
			'_wpnonce',
		),
		$referer
	);

	$parts = explode( '=', $status_query, 2 );
	return add_query_arg( sanitize_key( $parts[0] ), isset( $parts[1] ) ? sanitize_key( $parts[1] ) : '1', $referer );
}

/**
 * Default labels and messages for the contact form block.
 *
 * @return array
 */
function hapantheon_contact_form_defaults() {
	return array(
		'nameLabel'          => __( 'שם מלא', 'hapantheon' ),
		'emailLabel'         => __( 'דוא״ל לחזרה', 'hapantheon' ),
		'topicLabel'         => __( 'נושא הפנייה', 'hapantheon' ),
		'subjectLabel'       => __( 'כותרת קצרה', 'hapantheon' ),
		'messageLabel'       => __( 'ההודעה', 'hapantheon' ),
		'submitLabel'        => __( 'שליחת ההודעה', 'hapantheon' ),
		'namePlaceholder'    => __( 'ישראל ישראלי', 'hapantheon' ),
		'emailPlaceholder'   => 'you@mail.com',
		'subjectPlaceholder' => __( 'על מה המכתב?', 'hapantheon' ),
		'messagePlaceholder' => __( 'כתבו בחופשיות — אנחנו קוראים הכול.', 'hapantheon' ),
		'generalLabel'       => __( 'שאלה כללית', 'hapantheon' ),
		'contentLabel'       => __( 'הצעת תוכן', 'hapantheon' ),
		'correctionLabel'    => __( 'תיקון טעות', 'hapantheon' ),
		'oracleLabel'        => __( 'שאלה לאורקל', 'hapantheon' ),
		'consentText'        => __( 'אני מאשר/ת שהפרטים ישמשו למענה על הפנייה בלבד, בהתאם ל%s.', 'hapantheon' ),
		'privacyLabel'       => __( 'מדיניות הפרטיות', 'hapantheon' ),
		'securityNote'       => __( 'מאובטח באמצעות WordPress. הפרטים משמשים למענה בלבד.', 'hapantheon' ),
		'successMessage'     => __( 'ההודעה התקבלה. נשיב בהקדם.', 'hapantheon' ),
		'invalidMessage'     => __( 'בדקו את שדות החובה ונסו שוב.', 'hapantheon' ),
		'failedMessage'      => __( 'לא הצלחנו לשלוח את ההודעה. נסו שוב או פנו בדוא״ל למנהל האתר.', 'hapantheon' ),
	);
}

/**
 * Default labels and messages for the newsletter block.
 *
 * @return array
 */
function hapantheon_newsletter_defaults() {
	return array(
		'source'            => 'site',
		'style'             => 'teal',
		'emailLabel'        => __( 'כתובת דוא״ל', 'hapantheon' ),
		'placeholder'       => __( 'הדוא״ל שלכם', 'hapantheon' ),
		'buttonLabel'       => __( 'הרשמה', 'hapantheon' ),
		'subscribedMessage' => __( 'נרשמתם לפנתאון. המגילה הבאה — אליכם.', 'hapantheon' ),
		'existsMessage'     => __( 'כתובת הדוא״ל הזו כבר רשומה.', 'hapantheon' ),
		'invalidMessage'    => __( 'הזינו כתובת דוא״ל תקינה.', 'hapantheon' ),
	);
}

/**
 * Normalize editable form attributes to plain strings.
 *
 * @param array $atts Attributes.
 * @return array
 */
function hapantheon_sanitize_form_attributes( $atts ) {
	foreach ( $atts as $key => $value ) {
		if ( is_scalar( $value ) ) {
			$atts[ $key ] = sanitize_text_field( (string) $value );
		}
	}
	return $atts;
}

/**
 * Render the contact-form shortcode or dynamic block.
 *
 * @param array $atts Form attributes.
 * @return string
 */
function hapantheon_contact_form_shortcode( $atts = array() ) {
	$atts = shortcode_atts(
		hapantheon_contact_form_defaults(),
		(array) $atts,
		'hapantheon_contact_form'
	);
	$atts = hapantheon_sanitize_form_attributes( $atts );

	$status = isset( $_GET['hapantheon_contact'] ) ? sanitize_key( wp_unslash( $_GET['hapantheon_contact'] ) ) : '';
	$notice = '';
	if ( 'sent' === $status ) {
		$notice = '<p class="form-status success" role="status">' . esc_html( $atts['successMessage'] ) . '</p>';
	} elseif ( 'invalid' === $status ) {
		$notice = '<p class="form-status error" role="alert">' . esc_html( $atts['invalidMessage'] ) . '</p>';
	} elseif ( 'failed' === $status ) {
		$notice = '<p class="form-status error" role="alert">' . esc_html( $atts['failedMessage'] ) . '</p>';
	}

	$privacy_url = get_privacy_policy_url();
	if ( ! $privacy_url ) {
		$privacy_url = hapantheon_get_page_url_by_slug( 'privacy-policy' );
	}

	$privacy_link = '<a href="' . esc_url( $privacy_url ) . '">' . esc_html( $atts['privacyLabel'] ) . '</a>';
	$consent_text = esc_html( $atts['consentText'] );
	if ( false !== strpos( $consent_text, '%s' ) ) {
		$consent_html = str_replace( '%s', $privacy_link, $consent_text );
	} else {
		$consent_html = $consent_text . ' ' . $privacy_link;
	}

	$prefix       = wp_unique_id( 'hapantheon-contact-' );
	$name_id      = $prefix . '-name';
	$email_id     = $prefix . '-email';
	$subject_id   = $prefix . '-subject';
	$message_id   = $prefix . '-message';
	$honeypot_id  = $prefix . '-website';
	$topic_id     = $prefix . '-topic';
	$form_id      = $prefix . '-form';

	ob_start();
	?>
	<form class="cform rv" id="<?php echo esc_attr( $form_id ); ?>" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
		<input type="hidden" name="action" value="hapantheon_contact">
		<input type="hidden" name="contact_type" data-hapantheon-contact-type value="<?php echo esc_attr( $atts['generalLabel'] ); ?>">
		<?php wp_nonce_field( 'hapantheon_contact_submit', 'hapantheon_contact_nonce' ); ?>
		<div class="hp-field" aria-hidden="true">
			<label for="<?php echo esc_attr( $honeypot_id ); ?>"><?php esc_html_e( 'אתר', 'hapantheon' ); ?></label>
			<input id="<?php echo esc_attr( $honeypot_id ); ?>" name="website" type="text" tabindex="-1" autocomplete="off">
		</div>
		<div class="f2">
			<div class="field">
				<label for="<?php echo esc_attr( $name_id ); ?>"><?php echo esc_html( $atts['nameLabel'] ); ?></label>
				<input id="<?php echo esc_attr( $name_id ); ?>" name="name" type="text" required autocomplete="name" placeholder="<?php echo esc_attr( $atts['namePlaceholder'] ); ?>">
			</div>
			<div class="field">
				<label for="<?php echo esc_attr( $email_id ); ?>"><?php echo esc_html( $atts['emailLabel'] ); ?></label>
				<input id="<?php echo esc_attr( $email_id ); ?>" name="email" type="email" required autocomplete="email" class="en" dir="ltr" placeholder="<?php echo esc_attr( $atts['emailPlaceholder'] ); ?>">
			</div>
		</div>
		<div class="field">
			<label id="<?php echo esc_attr( $topic_id ); ?>"><?php echo esc_html( $atts['topicLabel'] ); ?></label>
			<div class="seg" role="group" aria-labelledby="<?php echo esc_attr( $topic_id ); ?>">
				<button type="button" data-contact-type="<?php echo esc_attr( $atts['generalLabel'] ); ?>" aria-pressed="true"><?php echo esc_html( $atts['generalLabel'] ); ?></button>
				<button type="button" data-contact-type="<?php echo esc_attr( $atts['contentLabel'] ); ?>" aria-pressed="false"><?php echo esc_html( $atts['contentLabel'] ); ?></button>
				<button type="button" data-contact-type="<?php echo esc_attr( $atts['correctionLabel'] ); ?>" aria-pressed="false"><?php echo esc_html( $atts['correctionLabel'] ); ?></button>
				<button type="button" data-contact-type="<?php echo esc_attr( $atts['oracleLabel'] ); ?>" aria-pressed="false"><?php echo esc_html( $atts['oracleLabel'] ); ?></button>
			</div>
		</div>
		<div class="field">
			<label for="<?php echo esc_attr( $subject_id ); ?>"><?php echo esc_html( $atts['subjectLabel'] ); ?></label>
			<input id="<?php echo esc_attr( $subject_id ); ?>" name="subject" type="text" required maxlength="180" placeholder="<?php echo esc_attr( $atts['subjectPlaceholder'] ); ?>">
		</div>
		<div class="field">
			<label for="<?php echo esc_attr( $message_id ); ?>"><?php echo esc_html( $atts['messageLabel'] ); ?></label>
			<textarea id="<?php echo esc_attr( $message_id ); ?>" name="message" required maxlength="12000" placeholder="<?php echo esc_attr( $atts['messagePlaceholder'] ); ?>"></textarea>
		</div>
		<label class="consent">
			<input type="checkbox" name="consent" value="1" required>
			<?php echo wp_kses_post( $consent_html ); ?>
		</label>
		<button class="btn-teal" type="submit">
			<?php echo esc_html( $atts['submitLabel'] ); ?>
			<?php echo hapantheon_icon( 'send' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		</button>
		<?php echo $notice; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
		<p class="form-note">
			<?php echo hapantheon_icon( 'shield' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php echo esc_html( $atts['securityNote'] ); ?>
		</p>
	</form>
	<?php
	return ob_get_clean();
}
add_shortcode( 'hapantheon_contact_form', 'hapantheon_contact_form_shortcode' );

/**
 * Handle a contact-form submission.
 */
function hapantheon_handle_contact_form() {
	if (
		! isset( $_POST['hapantheon_contact_nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hapantheon_contact_nonce'] ) ), 'hapantheon_contact_submit' )
	) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_contact=invalid' ) );
		exit;
	}

	// A filled honeypot is treated as a successful no-op to avoid teaching bots.
	if ( ! empty( $_POST['website'] ) ) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_contact=sent' ) );
		exit;
	}

	$name         = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
	$email        = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	$subject      = isset( $_POST['subject'] ) ? sanitize_text_field( wp_unslash( $_POST['subject'] ) ) : '';
	$message      = isset( $_POST['message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['message'] ) ) : '';
	$contact_type = isset( $_POST['contact_type'] ) ? sanitize_text_field( wp_unslash( $_POST['contact_type'] ) ) : '';
	$consent      = ! empty( $_POST['consent'] );

	if ( ! $name || ! is_email( $email ) || ! $subject || ! $message || ! $consent ) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_contact=invalid' ) );
		exit;
	}

	$recipient = sanitize_email( get_option( 'admin_email' ) );
	$mail_body = sprintf(
		"Name: %s\nEmail: %s\nType: %s\n\n%s",
		$name,
		$email,
		$contact_type,
		$message
	);
	$headers   = array( 'Reply-To: ' . $name . ' <' . $email . '>' );
	$sent      = wp_mail(
		$recipient,
		sprintf(
			/* translators: %s: contact subject. */
			__( '[HaPantheon contact] %s', 'hapantheon' ),
			$subject
		),
		$mail_body,
		$headers
	);

	wp_safe_redirect( hapantheon_form_return_url( $sent ? 'hapantheon_contact=sent' : 'hapantheon_contact=failed' ) );
	exit;
}
add_action( 'admin_post_hapantheon_contact', 'hapantheon_handle_contact_form' );
add_action( 'admin_post_nopriv_hapantheon_contact', 'hapantheon_handle_contact_form' );

/**
 * Render a newsletter subscription form.
 *
 * @param array $atts Shortcode or block attributes.
 * @return string
 */
function hapantheon_newsletter_shortcode( $atts = array() ) {
	$atts = shortcode_atts(
		hapantheon_newsletter_defaults(),
		(array) $atts,
		'hapantheon_newsletter'
	);
	$atts = hapantheon_sanitize_form_attributes( $atts );

	$atts['source'] = sanitize_key( $atts['source'] );
	$atts['style']  = in_array( $atts['style'], array( 'teal', 'gold' ), true ) ? $atts['style'] : 'teal';

	$status       = isset( $_GET['hapantheon_newsletter'] ) ? sanitize_key( wp_unslash( $_GET['hapantheon_newsletter'] ) ) : '';
	$button_class = 'gold' === $atts['style'] ? 'btn-gold' : 'btn-teal';
	$field_id     = wp_unique_id( 'hapantheon-news-' );
	$honeypot_id  = wp_unique_id( 'hapantheon-news-company-' );

	ob_start();
	?>
	<form class="news-form" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
		<input type="hidden" name="action" value="hapantheon_newsletter">
		<input type="hidden" name="source" value="<?php echo esc_attr( $atts['source'] ); ?>">
		<?php wp_nonce_field( 'hapantheon_newsletter_submit', 'hapantheon_newsletter_nonce' ); ?>
		<div class="hp-field" aria-hidden="true">
			<label for="<?php echo esc_attr( $honeypot_id ); ?>"><?php esc_html_e( 'חברה', 'hapantheon' ); ?></label>
			<input id="<?php echo esc_attr( $honeypot_id ); ?>" name="company" type="text" tabindex="-1" autocomplete="off">
		</div>
		<label class="screen-reader-text" for="<?php echo esc_attr( $field_id ); ?>"><?php echo esc_html( $atts['emailLabel'] ); ?></label>
		<input id="<?php echo esc_attr( $field_id ); ?>" name="email" type="email" dir="ltr" autocomplete="email" placeholder="<?php echo esc_attr( $atts['placeholder'] ); ?>" required>
		<button class="<?php echo esc_attr( $button_class ); ?>" type="submit">
			<?php echo esc_html( $atts['buttonLabel'] ); ?>
			<?php if ( 'teal' === $atts['style'] ) : ?>
				<?php echo hapantheon_icon( 'send' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
			<?php endif; ?>
		</button>
	</form>
	<?php if ( 'subscribed' === $status ) : ?>
		<p class="form-status success" role="status"><?php echo esc_html( $atts['subscribedMessage'] ); ?></p>
	<?php elseif ( 'exists' === $status ) : ?>
		<p class="form-status success" role="status"><?php echo esc_html( $atts['existsMessage'] ); ?></p>
	<?php elseif ( 'invalid' === $status ) : ?>
		<p class="form-status error" role="alert"><?php echo esc_html( $atts['invalidMessage'] ); ?></p>
	<?php endif; ?>
	<?php
	return ob_get_clean();
}
add_shortcode( 'hapantheon_newsletter', 'hapantheon_newsletter_shortcode' );

/**
 * Handle newsletter signup.
 */
function hapantheon_handle_newsletter() {
	if (
		! isset( $_POST['hapantheon_newsletter_nonce'] ) ||
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['hapantheon_newsletter_nonce'] ) ), 'hapantheon_newsletter_submit' )
	) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_newsletter=invalid' ) );
		exit;
	}

	if ( ! empty( $_POST['company'] ) ) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_newsletter=subscribed' ) );
		exit;
	}

	$email  = isset( $_POST['email'] ) ? sanitize_email( wp_unslash( $_POST['email'] ) ) : '';
	$source = isset( $_POST['source'] ) ? sanitize_key( wp_unslash( $_POST['source'] ) ) : 'site';
	if ( ! is_email( $email ) ) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_newsletter=invalid' ) );
		exit;
	}

	$subscribers = get_option( 'hapantheon_newsletter_subscribers', array() );
	if ( ! is_array( $subscribers ) ) {
		$subscribers = array();
	}
	$key = md5( strtolower( $email ) );
	if ( isset( $subscribers[ $key ] ) ) {
		wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_newsletter=exists' ) );
		exit;
	}

	$subscribers[ $key ] = array(
		'email'  => $email,
		'date'   => current_time( 'mysql' ),
		'source' => $source,
	);
	update_option( 'hapantheon_newsletter_subscribers', $subscribers, false );

	wp_mail(
		sanitize_email( get_option( 'admin_email' ) ),
		__( '[HaPantheon] New newsletter subscriber', 'hapantheon' ),
		sprintf( "Email: %s\nSource: %s", $email, $source )
	);

	wp_safe_redirect( hapantheon_form_return_url( 'hapantheon_newsletter=subscribed' ) );
	exit;
}
add_action( 'admin_post_hapantheon_newsletter', 'hapantheon_handle_newsletter' );
add_action( 'admin_post_nopriv_hapantheon_newsletter', 'hapantheon_handle_newsletter' );

/**
 * Export newsletter subscribers as CSV.
 */
function hapantheon_export_subscribers() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'You do not have permission to export subscribers.', 'hapantheon' ) );
	}
	check_admin_referer( 'hapantheon_export_subscribers' );

	$subscribers = get_option( 'hapantheon_newsletter_subscribers', array() );
	nocache_headers();
	header( 'Content-Type: text/csv; charset=utf-8' );
	header( 'Content-Disposition: attachment; filename=hapantheon-subscribers-' . gmdate( 'Y-m-d' ) . '.csv' );

	$output = fopen( 'php://output', 'w' );
	if ( false === $output ) {
		wp_die( esc_html__( 'Could not open the export stream.', 'hapantheon' ) );
	}
	fwrite( $output, "\xEF\xBB\xBF" );
	fputcsv( $output, array( 'email', 'date', 'source' ), ',', '"', '' );
	foreach ( (array) $subscribers as $subscriber ) {
		fputcsv(
			$output,
			array(
				isset( $subscriber['email'] ) ? $subscriber['email'] : '',
				isset( $subscriber['date'] ) ? $subscriber['date'] : '',
				isset( $subscriber['source'] ) ? $subscriber['source'] : '',
			),
			',',
			'"',
			''
		);
	}
	fclose( $output );
	exit;
}
add_action( 'admin_post_hapantheon_export_subscribers', 'hapantheon_export_subscribers' );
