<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class DC_V2_Feature_Request {

	private static function option_label( $group, $value ) {
		$options = DC_V2_I18n::feature_request_options();
		if ( empty( $options[ $group ] ) ) {
			return $value;
		}
		foreach ( $options[ $group ] as $item ) {
			if ( ( $item['value'] ?? '' ) === $value ) {
				return $item['label'] ?? $value;
			}
		}
		return $value;
	}

	private static function valid_values( $group ) {
		$options = DC_V2_I18n::feature_request_options();
		if ( empty( $options[ $group ] ) ) {
			return array();
		}
		return array_column( $options[ $group ], 'value' );
	}

	public static function send( WP_REST_Request $request ) {
		$body     = $request->get_json_params();
		$type     = sanitize_key( $body['type'] ?? '' );
		$area     = sanitize_key( $body['area'] ?? '' );
		$priority = sanitize_key( $body['priority'] ?? 'whenever' );
		$message  = sanitize_textarea_field( $body['message'] ?? '' );
		$page_url = esc_url_raw( $body['page_url'] ?? '' );

		if ( ! in_array( $type, self::valid_values( 'types' ), true ) ) {
			return new WP_Error( 'invalid_type', __( 'Select a request type.', 'order-from-dm' ), array( 'status' => 400 ) );
		}
		if ( ! in_array( $area, self::valid_values( 'areas' ), true ) ) {
			return new WP_Error( 'invalid_area', __( 'Select an area.', 'order-from-dm' ), array( 'status' => 400 ) );
		}
		if ( ! in_array( $priority, self::valid_values( 'priorities' ), true ) ) {
			$priority = 'whenever';
		}
		if ( strlen( trim( $message ) ) < 10 ) {
			return new WP_Error( 'missing_message', __( 'Describe your request (at least 10 characters).', 'order-from-dm' ), array( 'status' => 400 ) );
		}

		$user = wp_get_current_user();
		if ( ! $user || ! $user->ID ) {
			return new WP_Error( 'unauthorized', __( 'Invalid session.', 'order-from-dm' ), array( 'status' => 401 ) );
		}

		if ( ! $page_url ) {
			$page_url = admin_url( 'admin.php?page=' . DC_V2_PLUGIN_SLUG );
		}

		$site_name = get_bloginfo( 'name' );
		$site_url  = home_url( '/' );
		$to        = dc_v2_features_email();
		$subject   = sprintf(
			'[%s] %s — %s',
			dc_v2_plugin_name(),
			self::option_label( 'types', $type ),
			$site_name
		);

		$rows = array(
			__( 'Type', 'order-from-dm' )            => self::option_label( 'types', $type ),
			__( 'Area', 'order-from-dm' )            => self::option_label( 'areas', $area ),
			__( 'Priority', 'order-from-dm' )        => self::option_label( 'priorities', $priority ),
			__( 'Site', 'order-from-dm' )            => $site_name,
			__( 'Site URL', 'order-from-dm' )        => $site_url,
			__( 'Admin page', 'order-from-dm' )      => $page_url,
			__( 'Admin', 'order-from-dm' )           => $user->display_name,
			__( 'Admin email', 'order-from-dm' )     => $user->user_email,
			__( 'Plugin version', 'order-from-dm' )  => DC_V2_VERSION,
		);

		$html = self::build_html_email( $rows, $message );
		$headers = array(
			'Content-Type: text/html; charset=UTF-8',
			'Reply-To: ' . $user->display_name . ' <' . $user->user_email . '>',
		);

		$sent = wp_mail( $to, $subject, $html, $headers );
		if ( ! $sent ) {
			return new WP_Error( 'mail_failed', __( 'Could not send email. Try again later.', 'order-from-dm' ), array( 'status' => 500 ) );
		}

		return rest_ensure_response( array( 'sent' => true ) );
	}

	private static function build_html_email( $rows, $message ) {
		$primary = '#7c3aed';
		$rows_html = '';
		foreach ( $rows as $label => $value ) {
			$rows_html .= sprintf(
				'<tr><td style="padding:10px 14px;border-bottom:1px solid #eee;color:#666;font-size:13px;width:140px;vertical-align:top;">%s</td><td style="padding:10px 14px;border-bottom:1px solid #eee;font-size:14px;color:#1e1b24;">%s</td></tr>',
				esc_html( $label ),
				esc_html( (string) $value )
			);
		}
		$message_html = nl2br( esc_html( $message ) );

		return '<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body style="margin:0;padding:0;background:#f4f0fa;font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,sans-serif;">'
			. '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f4f0fa;padding:32px 16px;"><tr><td align="center">'
			. '<table role="presentation" width="560" cellpadding="0" cellspacing="0" style="background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(30,27,36,0.08);">'
			. '<tr><td style="background:' . esc_attr( $primary ) . ';padding:28px 32px;">'
			. '<p style="margin:0;font-size:12px;color:rgba(255,255,255,0.85);letter-spacing:0.04em;text-transform:uppercase;">' . esc_html( __( 'Improvement request', 'order-from-dm' ) ) . '</p>'
			. '<h1 style="margin:8px 0 0;font-size:22px;color:#fff;font-weight:600;">' . esc_html( dc_v2_plugin_name() ) . '</h1>'
			. '</td></tr>'
			. '<tr><td style="padding:28px 32px 8px;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #eee;border-radius:8px;overflow:hidden;">'
			. $rows_html
			. '</table></td></tr>'
			. '<tr><td style="padding:16px 32px 32px;">'
			. '<p style="margin:0 0 8px;font-size:12px;color:#666;text-transform:uppercase;letter-spacing:0.04em;">' . esc_html( __( 'Description', 'order-from-dm' ) ) . '</p>'
			. '<div style="background:#faf8fc;border:1px solid #e8e4f0;border-radius:8px;padding:16px;font-size:15px;line-height:1.55;color:#1e1b24;">'
			. $message_html
			. '</div></td></tr>'
			. '<tr><td style="padding:0 32px 28px;"><p style="margin:0;font-size:12px;color:#999;">' . esc_html( sprintf( __( 'Sent from WordPress · %s UTC', 'order-from-dm' ), gmdate( 'Y-m-d H:i:s' ) ) ) . '</p></td></tr>'
			. '</table></td></tr></table></body></html>';
	}
}
