<?php
/** Secure B2B RFQ handling. @package Fragrance_Trade */

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

function fragrance_trade_post_value( $key ) {
	if ( ! isset( $_POST[ $key ] ) || ! is_scalar( $_POST[ $key ] ) ) {
		return '';
	}
	return (string) wp_unslash( $_POST[ $key ] );
}

function fragrance_trade_limit_text( $value, $length ) {
	return function_exists( 'mb_substr' ) ? mb_substr( $value, 0, $length ) : substr( $value, 0, $length );
}

function fragrance_trade_form_redirect_url() {
	$fallback = home_url( '/' );
	$referer  = wp_get_referer();
	return wp_validate_redirect( $referer ? $referer : $fallback, $fallback );
}

function fragrance_trade_redirect_notice( $notice ) {
	$url = remove_query_arg( 'fragrance_notice', fragrance_trade_form_redirect_url() );
	$url = add_query_arg( 'fragrance_notice', sanitize_key( $notice ), $url );
	wp_safe_redirect( $url . '#rfq' );
	exit;
}

function fragrance_trade_is_rate_limited( $action ) {
	$address = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
	$key     = 'fragrance_' . sanitize_key( $action ) . '_' . substr( hash( 'sha256', $address . wp_salt( 'nonce' ) ), 0, 32 );
	if ( get_transient( $key ) ) {
		return true;
	}
	set_transient( $key, 1, MINUTE_IN_SECONDS );
	return false;
}

function fragrance_trade_honeypot_filled() {
	return '' !== trim( fragrance_trade_post_value( 'fragrance_website' ) );
}

function fragrance_trade_handle_rfq() {
	check_admin_referer( 'fragrance_rfq', 'fragrance_rfq_nonce' );
	if ( fragrance_trade_honeypot_filled() ) {
		fragrance_trade_redirect_notice( 'invalid' );
	}
	if ( fragrance_trade_is_rate_limited( 'rfq' ) ) {
		fragrance_trade_redirect_notice( 'rate_limited' );
	}

	$fields = array(
		'name'         => fragrance_trade_limit_text( sanitize_text_field( fragrance_trade_post_value( 'name' ) ), 100 ),
		'email'        => fragrance_trade_limit_text( sanitize_email( fragrance_trade_post_value( 'email' ) ), 190 ),
		'company'      => fragrance_trade_limit_text( sanitize_text_field( fragrance_trade_post_value( 'company' ) ), 150 ),
		'whatsapp'     => fragrance_trade_limit_text( sanitize_text_field( fragrance_trade_post_value( 'whatsapp' ) ), 100 ),
		'product_type' => fragrance_trade_limit_text( sanitize_text_field( fragrance_trade_post_value( 'product_type' ) ), 150 ),
		'message'      => fragrance_trade_limit_text( sanitize_textarea_field( fragrance_trade_post_value( 'message' ) ), 2000 ),
	);
	if ( ! $fields['name'] || ! is_email( $fields['email'] ) || ! $fields['product_type'] || ! $fields['message'] ) {
		fragrance_trade_redirect_notice( 'invalid' );
	}

	$labels = array(
		'name' => __( '姓名', 'fragrance-trade' ), 'email' => __( '企业邮箱', 'fragrance-trade' ),
		'company' => __( '公司名称', 'fragrance-trade' ), 'whatsapp' => __( 'WhatsApp 或电话', 'fragrance-trade' ),
		'product_type' => __( '需求产品或服务', 'fragrance-trade' ), 'message' => __( '简要需求描述', 'fragrance-trade' ),
	);
	$body_lines = array();
	foreach ( $labels as $key => $label ) {
		$body_lines[] = $label . ': ' . ( $fields[ $key ] ? $fields[ $key ] : __( '未提供', 'fragrance-trade' ) );
	}

	$site_name  = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
	$safe_name  = str_replace( array( "\r", "\n" ), ' ', $fields['name'] );
	$safe_email = str_replace( array( "\r", "\n" ), '', $fields['email'] );
	$context    = $fields['company'] ? $fields['company'] : $fields['product_type'];
	$subject    = sprintf( '[%s] %s - %s', $site_name, __( '汽车贴膜项目询价', 'fragrance-trade' ), $context );
	$headers    = array( 'Content-Type: text/plain; charset=UTF-8', 'Reply-To: ' . $safe_name . ' <' . $safe_email . '>' );
	$sent       = wp_mail( fragrance_trade_inquiry_email(), $subject, implode( "\n\n", $body_lines ), $headers );
	fragrance_trade_redirect_notice( $sent ? 'success' : 'mail_failed' );
}
add_action( 'admin_post_fragrance_rfq', 'fragrance_trade_handle_rfq' );
add_action( 'admin_post_nopriv_fragrance_rfq', 'fragrance_trade_handle_rfq' );
