<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

if ( ! class_exists( 'SftcyWordformSupport' ) ) {
	class SftcyWordformSupport {
		const SUPPORT_EMAIL = 'support@softcoy.com';
		const SUPPORT_OFFICE_PROD_API_BASE = 'https://softcoy.com/api/v1';
		const LOG_RETENTION_DAYS = 14;
		const LOG_ROW_LIMIT = 500;
		const SUPPORT_ATTACHMENT_MAX_FILES = 3;
		const SUPPORT_ATTACHMENT_MAX_BYTES = 5242880;

		private static function generate_support_ticket_id() {
			return sprintf( 'WF-%1$s-%2$03d', gmdate( 'ymdHis' ), wp_rand( 100, 999 ) );
		}

		/**
		 * Get support issue options.
		 *
		 * @return array
		 */
		public static function get_issue_type_options() {
			return array(
				'general'    => __( 'General', 'wordform-pro' ),
				'builder'    => __( 'Builder', 'wordform-pro' ),
				'frontend'   => __( 'Frontend Form', 'wordform-pro' ),
				'payment'    => __( 'Payment', 'wordform-pro' ),
				'captcha'    => __( 'Captcha', 'wordform-pro' ),
				'upload'     => __( 'Upload', 'wordform-pro' ),
				'connection' => __( 'Connection', 'wordform-pro' ),
				'license'    => __( 'License', 'wordform-pro' ),
				'export'     => __( 'Export', 'wordform-pro' ),
				'other'      => __( 'Other', 'wordform-pro' ),
			);
		}

		/**
		 * Get available support delivery channels.
		 *
		 * @return array
		 */
		public static function get_delivery_channel_options() {
			return array(
				'email'  => __( 'Email Support', 'wordform-pro' ),
				'office' => __( 'SOFTCOY Support Office', 'wordform-pro' ),
			);
		}

		public static function handle_support_request_attachments( $files = array() ) {
			$attachments = array();
			$normalized  = self::normalize_uploaded_attachment_files( $files );

			if ( empty( $normalized ) ) {
				return array(
					'status'      => 'success',
					'attachments' => $attachments,
				);
			}

			if ( count( $normalized ) > self::SUPPORT_ATTACHMENT_MAX_FILES ) {
				return array(
					'status'  => 'fail',
					'message' => sprintf(
						/* translators: %d: attachment limit. */
						__( 'Please attach no more than %d files.', 'wordform-pro' ),
						self::SUPPORT_ATTACHMENT_MAX_FILES
					),
				);
			}

			$directory = self::prepare_support_attachment_directory();
			if ( is_wp_error( $directory ) ) {
				return array(
					'status'  => 'fail',
					'message' => $directory->get_error_message(),
				);
			}

			$allowed_mimes = self::get_allowed_support_attachment_mimes();

			foreach ( $normalized as $file ) {
				if ( UPLOAD_ERR_OK !== (int) $file['error'] ) {
					return array(
						'status'  => 'fail',
						'message' => __( 'One attachment could not be uploaded. Please remove it and try again.', 'wordform-pro' ),
					);
				}

				if ( (int) $file['size'] > self::SUPPORT_ATTACHMENT_MAX_BYTES ) {
					return array(
						'status'  => 'fail',
						'message' => __( 'Each support attachment must be 5 MB or smaller.', 'wordform-pro' ),
					);
				}

				$original_name = sanitize_file_name( $file['name'] );
				$filetype      = wp_check_filetype_and_ext( $file['tmp_name'], $original_name, $allowed_mimes );
				$extension     = isset( $filetype['ext'] ) ? strtolower( (string) $filetype['ext'] ) : '';
				$mime_type     = isset( $filetype['type'] ) ? (string) $filetype['type'] : '';

				if ( '' === $extension || ! in_array( $mime_type, $allowed_mimes, true ) ) {
					return array(
						'status'  => 'fail',
						'message' => __( 'Only JPG, PNG, GIF, WebP, and PDF support attachments are allowed.', 'wordform-pro' ),
					);
				}

				if ( ! is_uploaded_file( $file['tmp_name'] ) ) {
					return array(
						'status'  => 'fail',
						'message' => __( 'The attachment upload could not be verified. Please try again.', 'wordform-pro' ),
					);
				}

				$stored_name = gmdate( 'Ymd-His' ) . '-' . self::generate_support_attachment_token() . '.' . $extension;
				$stored_path = trailingslashit( $directory ) . $stored_name;

				if ( ! move_uploaded_file( $file['tmp_name'], $stored_path ) ) {
					return array(
						'status'  => 'fail',
						'message' => __( 'The support attachment could not be saved. Please try again.', 'wordform-pro' ),
					);
				}

				$attachments[] = array(
					'name'      => $original_name,
					'url'       => plugins_url( 'support-request/' . rawurlencode( $stored_name ), SFTCY_WORDFORM_PLUGIN_FILE ),
					'type'      => $mime_type,
					'size'      => (int) filesize( $stored_path ),
					'stored_at' => gmdate( 'c' ),
				);
			}

			return array(
				'status'      => 'success',
				'attachments' => $attachments,
			);
		}

		private static function normalize_uploaded_attachment_files( $files = array() ) {
			if ( empty( $files ) || empty( $files['name'] ) ) {
				return array();
			}

			$normalized = array();
			$names      = is_array( $files['name'] ) ? $files['name'] : array( $files['name'] );
			$tmp_names  = is_array( $files['tmp_name'] ) ? $files['tmp_name'] : array( $files['tmp_name'] ?? '' );
			$types      = is_array( $files['type'] ) ? $files['type'] : array( $files['type'] ?? '' );
			$sizes      = is_array( $files['size'] ) ? $files['size'] : array( $files['size'] ?? 0 );
			$errors     = is_array( $files['error'] ) ? $files['error'] : array( $files['error'] ?? UPLOAD_ERR_NO_FILE );

			foreach ( $names as $index => $name ) {
				if ( '' === (string) $name && UPLOAD_ERR_NO_FILE === (int) ( $errors[ $index ] ?? UPLOAD_ERR_NO_FILE ) ) {
					continue;
				}

				$normalized[] = array(
					'name'     => (string) $name,
					'type'     => (string) ( $types[ $index ] ?? '' ),
					'tmp_name' => (string) ( $tmp_names[ $index ] ?? '' ),
					'error'    => (int) ( $errors[ $index ] ?? UPLOAD_ERR_NO_FILE ),
					'size'     => (int) ( $sizes[ $index ] ?? 0 ),
				);
			}

			return $normalized;
		}

		private static function prepare_support_attachment_directory() {
			$directory = trailingslashit( SFTCY_WORDFORM_PLUGIN_DIR ) . 'support-request';

			if ( ! wp_mkdir_p( $directory ) ) {
				return new WP_Error( 'wordform_support_attachment_directory', __( 'The support attachment folder could not be created.', 'wordform-pro' ) );
			}

			$index_file = trailingslashit( $directory ) . 'index.html';
			if ( ! file_exists( $index_file ) ) {
				file_put_contents( $index_file, '' );
			}

			$htaccess_file = trailingslashit( $directory ) . '.htaccess';
			if ( ! file_exists( $htaccess_file ) ) {
				file_put_contents(
					$htaccess_file,
					"Options -Indexes\n<FilesMatch \"\\.(php|phtml|phar|cgi|pl|asp|aspx|jsp|sh)$\">\nRequire all denied\n</FilesMatch>\n"
				);
			}

			return $directory;
		}

		private static function get_allowed_support_attachment_mimes() {
			return array(
				'jpg|jpeg' => 'image/jpeg',
				'png'      => 'image/png',
				'gif'      => 'image/gif',
				'webp'     => 'image/webp',
				'pdf'      => 'application/pdf',
			);
		}

		private static function generate_support_attachment_token() {
			if ( function_exists( 'random_bytes' ) ) {
				try {
					return bin2hex( random_bytes( 18 ) );
				} catch ( Exception $exception ) {
					return wp_generate_password( 36, false, false );
				}
			}

			return wp_generate_password( 36, false, false );
		}

		private static function normalize_support_attachments_for_payload( $attachments = array() ) {
			$normalized = array();
			foreach ( (array) $attachments as $attachment ) {
				if ( ! is_array( $attachment ) || empty( $attachment['url'] ) ) {
					continue;
				}

				$normalized[] = array(
					'name'      => sanitize_file_name( (string) ( $attachment['name'] ?? '' ) ),
					'url'       => esc_url_raw( (string) $attachment['url'] ),
					'type'      => sanitize_text_field( (string) ( $attachment['type'] ?? '' ) ),
					'size'      => absint( $attachment['size'] ?? 0 ),
					'stored_at' => sanitize_text_field( (string) ( $attachment['stored_at'] ?? '' ) ),
				);
			}

			return $normalized;
		}

		/**
		 * Ensure support storage exists for upgraded sites.
		 *
		 * @return void
		 */
		public static function ensure_storage_ready() {
			global $wpdb;

			require_once ABSPATH . 'wp-admin/includes/upgrade.php';

			$charset_collate     = $wpdb->get_charset_collate();
			$support_requests    = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_requests_tbl;
			$support_logs        = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_logs_tbl;

			$requests_sql = "CREATE TABLE $support_requests (
				id BIGINT NOT NULL AUTO_INCREMENT,
				ticket_uuid CHAR(36) DEFAULT '' NOT NULL,
				site_url TEXT DEFAULT NULL,
				site_domain CHAR(190) DEFAULT '' NOT NULL,
				sender_email CHAR(190) DEFAULT '' NOT NULL,
				plugin_variant CHAR(20) DEFAULT 'free' NOT NULL,
				plugin_version CHAR(50) DEFAULT '' NOT NULL,
				issue_type CHAR(50) DEFAULT 'general' NOT NULL,
				include_diagnostics CHAR(3) DEFAULT 'yes' NOT NULL,
				delivery_channels LONGTEXT DEFAULT NULL,
				delivery_results LONGTEXT DEFAULT NULL,
				overall_status CHAR(30) DEFAULT 'received' NOT NULL,
				office_ticket_id CHAR(100) DEFAULT '' NOT NULL,
				office_status CHAR(30) DEFAULT '' NOT NULL,
				office_last_synced_at DATETIME DEFAULT NULL,
				request_payload LONGTEXT DEFAULT NULL,
				delivery_channel CHAR(50) DEFAULT 'email' NOT NULL,
				delivery_status CHAR(20) DEFAULT 'pending' NOT NULL,
				delivery_message TEXT DEFAULT NULL,
				created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
				updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
				PRIMARY KEY (id)
			) $charset_collate;";

			$logs_sql = "CREATE TABLE $support_logs (
				id BIGINT NOT NULL AUTO_INCREMENT,
				severity CHAR(20) DEFAULT 'info' NOT NULL,
				subsystem CHAR(50) DEFAULT 'general' NOT NULL,
				event_code CHAR(100) DEFAULT '' NOT NULL,
				message TEXT DEFAULT NULL,
				context_json LONGTEXT DEFAULT NULL,
				form_id CHAR(100) DEFAULT '' NOT NULL,
				submission_id BIGINT DEFAULT 0 NOT NULL,
				created_at DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
				expires_at DATETIME DEFAULT NULL,
				PRIMARY KEY (id)
			) $charset_collate;";

			dbDelta( $requests_sql );
			dbDelta( $logs_sql );
		}

		/**
		 * Return prefilled support page data.
		 *
		 * @return array
		 */
		public static function get_support_prefill_data() {
			self::ensure_storage_ready();

			$site_url       = home_url( '/' );
			$site_domain    = wp_parse_url( $site_url, PHP_URL_HOST );
			$license_data   = get_option( 'wordform_pro_license_data', array() );
			$license_status = 'inactive';

			if ( ! empty( $license_data['isLicenseExpired'] ) ) {
				$license_status = 'expired';
			} elseif ( ! empty( get_option( 'softcoy_wordform_pro_license_key', '' ) ) ) {
				$license_status = 'active';
			}

			return array(
				'sender_email'          => sanitize_email( get_option( 'admin_email', '' ) ),
				'site_url'              => esc_url_raw( $site_url ),
				'site_domain'           => sanitize_text_field( $site_domain ),
				'plugin_variant'        => self::get_plugin_variant(),
				'plugin_version'        => defined( 'SFTCY_WORDFORM_VERSION' ) ? SFTCY_WORDFORM_VERSION : '',
				'wp_version'            => get_bloginfo( 'version' ),
				'php_version'           => PHP_VERSION,
				'license_status'        => $license_status,
				'support_email'         => self::SUPPORT_EMAIL,
				'issue_type_options'    => self::get_issue_type_options(),
				'delivery_channels'     => self::get_delivery_channel_options(),
				'diagnostics_preview'   => self::get_diagnostics_preview_summary(),
				'recent_requests'       => self::get_recent_support_requests( 12 ),
				'diagnostics_note'      => __( 'Diagnostics include plugin environment and recent WordForm failures only. Submission contents, payment card data, API secrets, and full license keys are not included.', 'wordform-pro' ),
			);
		}

		/**
		 * Log a bounded support diagnostic event.
		 *
		 * @param string $subsystem
		 * @param string $severity
		 * @param string $event_code
		 * @param string $message
		 * @param array  $context
		 * @param string $form_id
		 * @param int    $submission_id
		 * @return void
		 */
		public static function log_event( $subsystem = 'general', $severity = 'info', $event_code = '', $message = '', $context = array(), $form_id = '', $submission_id = 0 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_logs_tbl;
			$severity = in_array( $severity, array( 'info', 'warning', 'error' ), true ) ? $severity : 'info';
			$context  = self::redact_sensitive_data( is_array( $context ) ? $context : array() );
			$expires_at = gmdate( 'Y-m-d H:i:s', strtotime( '+' . self::LOG_RETENTION_DAYS . ' days' ) );

			$wpdb->insert(
				$table,
				array(
					'severity'      => sanitize_key( $severity ),
					'subsystem'     => sanitize_key( $subsystem ),
					'event_code'    => sanitize_key( $event_code ),
					'message'       => sanitize_textarea_field( $message ),
					'context_json'  => wp_json_encode( $context ),
					'form_id'       => sanitize_text_field( $form_id ),
					'submission_id' => absint( $submission_id ),
					'expires_at'    => $expires_at,
				)
			);

			self::prune_logs();
		}

		/**
		 * Build and store a support request, then deliver it.
		 *
		 * @param array $request_data
		 * @return array
		 */
		public static function create_support_request( $request_data = array() ) {
			global $wpdb;

			self::ensure_storage_ready();

			$prefill             = self::get_support_prefill_data();
			$sender_email        = isset( $request_data['sender_email'] ) ? sanitize_email( $request_data['sender_email'] ) : $prefill['sender_email'];
			$subject             = isset( $request_data['subject'] ) ? sanitize_text_field( $request_data['subject'] ) : '';
			$issue_type          = isset( $request_data['issue_type'] ) ? sanitize_key( $request_data['issue_type'] ) : 'general';
			$message             = isset( $request_data['message'] ) ? sanitize_textarea_field( $request_data['message'] ) : '';
			$include_diagnostics = isset( $request_data['include_diagnostics'] ) && 'yes' === sanitize_text_field( $request_data['include_diagnostics'] ) ? 'yes' : 'no';
			$delivery_channels   = isset( $request_data['delivery_channels'] ) && is_array( $request_data['delivery_channels'] ) ? array_map( 'sanitize_key', $request_data['delivery_channels'] ) : array();
			$delivery_channels   = array_values( array_intersect( $delivery_channels, array_keys( self::get_delivery_channel_options() ) ) );

			if ( ! is_email( $sender_email ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'A valid sender email is required.', 'wordform-pro' ),
				);
			}

			if ( '' === trim( $message ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'Please describe the issue before sending a support request.', 'wordform-pro' ),
				);
			}

			if ( empty( $delivery_channels ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'Select at least one support delivery channel before sending the request.', 'wordform-pro' ),
				);
			}

			if ( '' === trim( $subject ) ) {
				$subject = sprintf(
					/* translators: %s: date. */
					__( 'WordForm support - %s', 'wordform-pro' ),
					date_i18n( get_option( 'date_format' ) )
				);
			}

			$ticket_uuid = self::generate_support_ticket_id();
			$payload     = self::build_support_request_payload(
				array(
					'ticket_uuid'          => $ticket_uuid,
					'sender_email'         => $sender_email,
					'subject'              => $subject,
					'issue_type'           => $issue_type,
					'message'              => $message,
					'include_diagnostics'  => $include_diagnostics,
					'delivery_channels'    => $delivery_channels,
					'attachments'          => isset( $request_data['attachments'] ) ? $request_data['attachments'] : array(),
				)
			);
			$delivery_results = self::prepare_delivery_results( $delivery_channels );
			$overall_status   = 'received';

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_requests_tbl;
			$wpdb->insert(
				$table,
				array(
					'ticket_uuid'         => $ticket_uuid,
					'site_url'            => isset( $payload['site']['url'] ) ? $payload['site']['url'] : '',
					'site_domain'         => isset( $payload['site']['domain'] ) ? $payload['site']['domain'] : '',
					'sender_email'        => $sender_email,
					'plugin_variant'      => isset( $payload['plugin']['variant'] ) ? $payload['plugin']['variant'] : 'pro',
					'plugin_version'      => isset( $payload['plugin']['version'] ) ? $payload['plugin']['version'] : '',
					'issue_type'          => $issue_type,
					'include_diagnostics' => $include_diagnostics,
					'delivery_channels'   => wp_json_encode( $delivery_channels ),
					'delivery_results'    => wp_json_encode( $delivery_results ),
					'overall_status'      => $overall_status,
					'request_payload'     => wp_json_encode( $payload ),
					'delivery_channel'    => implode( ',', $delivery_channels ),
					'delivery_status'     => 'pending',
					'delivery_message'    => '',
				)
			);

			$request_id      = (int) $wpdb->insert_id;
			if ( in_array( 'email', $delivery_channels, true ) ) {
				$email_result = self::deliver_support_request_email( $payload );
				$delivery_results['email'] = array(
					'status'  => ! empty( $email_result['sent'] ) ? 'sent' : 'failed',
					'message' => isset( $email_result['message'] ) ? sanitize_textarea_field( wp_strip_all_tags( $email_result['message'] ) ) : '',
				);
				if ( empty( $email_result['sent'] ) ) {
					self::log_event(
						'support',
						'error',
						'support_email_delivery_failed',
						isset( $email_result['message'] ) ? wp_strip_all_tags( $email_result['message'] ) : 'Support email delivery failed.',
						array( 'ticket_uuid' => $ticket_uuid )
					);
				}
			}

			if ( in_array( 'office', $delivery_channels, true ) ) {
				$office_result = self::deliver_support_request_office( $payload );
				$delivery_results['office'] = array(
					'ticket_id'    => sanitize_text_field( $office_result['ticket_id'] ?? '' ),
					'status'       => ! empty( $office_result['sent'] ) ? sanitize_key( $office_result['status'] ?? 'open' ) : 'failed',
					'status_label' => sanitize_text_field( $office_result['status_label'] ?? 'Open' ),
					'message'      => isset( $office_result['message'] ) ? sanitize_textarea_field( wp_strip_all_tags( $office_result['message'] ) ) : '',
					'updated_at'   => sanitize_text_field( $office_result['updated_at'] ?? '' ),
					'resolved_at'  => sanitize_text_field( $office_result['resolved_at'] ?? '' ),
					'timings'      => isset( $office_result['timings'] ) && is_array( $office_result['timings'] ) ? $office_result['timings'] : array(),
					'latest_reply' => isset( $office_result['latest_reply'] ) && is_array( $office_result['latest_reply'] ) ? $office_result['latest_reply'] : array(),
					'replies'      => isset( $office_result['replies'] ) && is_array( $office_result['replies'] ) ? $office_result['replies'] : array(),
				);

				if ( ! empty( $office_result['ticket_id'] ) ) {
					$wpdb->update(
						$table,
						array(
							'office_ticket_id'      => sanitize_text_field( $office_result['ticket_id'] ),
							'office_status'         => sanitize_key( $office_result['status'] ?? 'open' ),
							'office_last_synced_at' => current_time( 'mysql', 1 ),
						),
						array( 'id' => $request_id )
					);
				}
			}

			if ( isset( $delivery_results['email']['status'] ) && 'failed' === $delivery_results['email']['status'] && 1 === count( $delivery_channels ) ) {
				$overall_status = 'delivery_failed';
			}

			if ( ! empty( $delivery_results['office']['status'] ) && 'failed' !== $delivery_results['office']['status'] ) {
				$overall_status = sanitize_key( $delivery_results['office']['status'] );
			}

			$wpdb->update(
				$table,
				array(
					'delivery_results' => wp_json_encode( $delivery_results ),
					'overall_status'   => $overall_status,
					'delivery_status'  => self::flatten_primary_delivery_status( $delivery_results ),
					'delivery_message' => self::flatten_primary_delivery_message( $delivery_results ),
				),
				array( 'id' => $request_id )
			);

			return array(
				'status'      => self::has_any_successful_delivery( $delivery_results ) ? 'success' : 'fail',
				'message'     => self::has_any_successful_delivery( $delivery_results )
					? __( 'Support request sent successfully. Our team can now review your message and diagnostics.', 'wordform-pro' )
					: self::get_support_mail_failure_message_html(),
				'ticket_uuid' => $ticket_uuid,
				'request_id'  => $request_id,
				'delivery_results' => $delivery_results,
				'overall_status' => $overall_status,
			);
		}

		/**
		 * Collect a support diagnostics preview for the UI.
		 *
		 * @return array
		 */
		public static function get_diagnostics_preview_summary() {
			$recent_logs        = self::get_recent_logs( 50 );
			$connection_failures = self::get_recent_failed_connection_events( 10 );
			$summary            = array(
				'total_logs'          => count( $recent_logs ),
				'payment_errors'      => 0,
				'captcha_errors'      => 0,
				'upload_errors'       => 0,
				'connection_failures' => count( $connection_failures ),
			);

			foreach ( $recent_logs as $log_row ) {
				$subsystem = isset( $log_row['subsystem'] ) ? sanitize_key( $log_row['subsystem'] ) : '';
				if ( 'payment' === $subsystem ) {
					$summary['payment_errors']++;
				} elseif ( 'captcha' === $subsystem ) {
					$summary['captcha_errors']++;
				} elseif ( 'upload' === $subsystem ) {
					$summary['upload_errors']++;
				}
			}

			return $summary;
		}

		/**
		 * Fetch recent support logs.
		 *
		 * @param int $limit
		 * @return array
		 */
		public static function get_recent_logs( $limit = 25 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_logs_tbl;
			$limit = max( 1, absint( $limit ) );

			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT severity, subsystem, event_code, message, context_json, form_id, submission_id, created_at
					FROM $table
					ORDER BY id DESC
					LIMIT %d",
					$limit
				),
				ARRAY_A
			);
		}

		/**
		 * Fetch recent failed connection send events from existing connection logs.
		 *
		 * @param int $limit
		 * @return array
		 */
		public static function get_recent_failed_connection_events( $limit = 10 ) {
			global $wpdb;

			$created_forms_table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_tbl;
			$submission_table    = $wpdb->prefix . SftcyWordformBase::$sc_wordform_submission_tbl;
			$limit               = max( 1, absint( $limit ) );
			$submission_rows     = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT wcf.form_name, wst.form_id, wst.data_send_info, wst.created_at
					FROM $submission_table AS wst
					INNER JOIN $created_forms_table AS wcf ON wcf.form_id = wst.form_id
					WHERE wst.data_send_info IS NOT NULL AND wst.data_send_info != ''
					ORDER BY wst.id DESC
					LIMIT %d",
					$limit * 4
				),
				ARRAY_A
			);

			$failures = array();
			foreach ( $submission_rows as $row ) {
				if ( empty( $row['data_send_info'] ) ) {
					continue;
				}

				$send_info = json_decode( $row['data_send_info'], true );
				if ( ! is_array( $send_info ) ) {
					continue;
				}

				foreach ( $send_info as $app_slug => $app_info ) {
					if ( ! is_array( $app_info ) || 'success' === ( $app_info['status'] ?? '' ) ) {
						continue;
					}

					$failures[] = array(
						'form_id'    => isset( $row['form_id'] ) ? sanitize_text_field( $row['form_id'] ) : '',
						'form_name'  => isset( $row['form_name'] ) ? sanitize_text_field( $row['form_name'] ) : '',
						'app_slug'   => sanitize_key( $app_slug ),
						'reason'     => isset( $app_info['reason'] ) ? sanitize_textarea_field( $app_info['reason'] ) : '',
						'comment'    => isset( $app_info['comment'] ) ? sanitize_textarea_field( $app_info['comment'] ) : '',
						'created_at' => isset( $row['created_at'] ) ? sanitize_text_field( $row['created_at'] ) : '',
					);

					if ( count( $failures ) >= $limit ) {
						break 2;
					}
				}
			}

			return $failures;
		}

		/**
		 * Fetch recent support requests for local history.
		 *
		 * @param int $limit
		 * @return array
		 */
		public static function get_recent_support_requests( $limit = 10 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_requests_tbl;
			$limit = max( 1, absint( $limit ) );
			$rows  = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, ticket_uuid, sender_email, issue_type, delivery_channels, delivery_results, overall_status, office_ticket_id, office_status, office_last_synced_at, request_payload, created_at, updated_at
					FROM $table
					ORDER BY id DESC
					LIMIT %d",
					$limit
				),
				ARRAY_A
			);

			foreach ( $rows as &$row ) {
				$row['delivery_channels'] = self::decode_json_field( $row['delivery_channels'] ?? '' );
				$row['delivery_results']  = self::decode_json_field( $row['delivery_results'] ?? '' );
				$request_payload          = self::decode_json_field( $row['request_payload'] ?? '' );
				$row['message']           = is_array( $request_payload ) && isset( $request_payload['request']['message'] ) ? sanitize_textarea_field( (string) $request_payload['request']['message'] ) : '';
				unset( $row['request_payload'] );
			}

			return $rows;
		}

		public static function reply_to_support_request( $ticket_uuid = '', $message = '', $sender_email = '' ) {
			global $wpdb;

			self::ensure_storage_ready();

			$ticket_uuid   = sanitize_text_field( (string) $ticket_uuid );
			$message       = sanitize_textarea_field( (string) $message );
			$sender_email  = sanitize_email( (string) $sender_email );
			$table         = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_requests_tbl;

			if ( '' === $ticket_uuid || '' === $message || ! is_email( $sender_email ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'Ticket id, sender email, and reply message are required.', 'wordform-pro' ),
				);
			}

			$row = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT id, ticket_uuid, sender_email, office_ticket_id, delivery_results
					FROM $table
					WHERE ticket_uuid = %s
					LIMIT 1",
					$ticket_uuid
				),
				ARRAY_A
			);

			if ( empty( $row ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'Support ticket could not be found locally.', 'wordform-pro' ),
				);
			}

			if ( empty( $row['office_ticket_id'] ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'This ticket was not delivered to the SOFTCOY office channel.', 'wordform-pro' ),
				);
			}

			$sync_result = self::send_office_ticket_reply( $row['office_ticket_id'], $sender_email, $message );
			if ( empty( $sync_result['success'] ) ) {
				return array(
					'status'  => 'fail',
					'message' => $sync_result['message'] ?? __( 'Reply could not be sent to the SOFTCOY office.', 'wordform-pro' ),
				);
			}

			$delivery_results = self::decode_json_field( $row['delivery_results'] ?? '' );
			$delivery_results['office'] = array(
				'ticket_id'    => sanitize_text_field( $row['office_ticket_id'] ?? '' ),
				'status'       => sanitize_key( $sync_result['status'] ?? 'in_review' ),
				'status_label' => sanitize_text_field( $sync_result['status_label'] ?? 'In Review' ),
				'message'      => sanitize_textarea_field( $sync_result['message'] ?? '' ),
				'updated_at'   => sanitize_text_field( $sync_result['updated_at'] ?? '' ),
				'resolved_at'  => sanitize_text_field( $sync_result['resolved_at'] ?? '' ),
				'timings'      => isset( $sync_result['timings'] ) && is_array( $sync_result['timings'] ) ? $sync_result['timings'] : array(),
				'replies'      => isset( $sync_result['replies'] ) && is_array( $sync_result['replies'] ) ? $sync_result['replies'] : array(),
				'latest_reply' => isset( $sync_result['latest_reply'] ) && is_array( $sync_result['latest_reply'] ) ? $sync_result['latest_reply'] : array(),
			);

			$wpdb->update(
				$table,
				array(
					'delivery_results'      => wp_json_encode( $delivery_results ),
					'overall_status'        => sanitize_key( $sync_result['status'] ?? 'in_review' ),
					'office_status'         => sanitize_key( $sync_result['status'] ?? 'in_review' ),
					'office_last_synced_at' => current_time( 'mysql', 1 ),
					'delivery_status'       => self::flatten_primary_delivery_status( $delivery_results ),
					'delivery_message'      => self::flatten_primary_delivery_message( $delivery_results ),
				),
				array( 'id' => absint( $row['id'] ) )
			);

			return array(
				'status'          => 'success',
				'message'         => __( 'Reply sent to the SOFTCOY Support Office.', 'wordform-pro' ),
				'ticket_uuid'     => $ticket_uuid,
				'delivery_results'=> $delivery_results,
				'overall_status'  => sanitize_key( $sync_result['status'] ?? 'in_review' ),
			);
		}

		/**
		 * Build a support payload ready for local storage and delivery.
		 *
		 * @param array $request
		 * @return array
		 */
		private static function build_support_request_payload( $request = array() ) {
			$prefill       = self::get_support_prefill_data();
			$include_logs  = isset( $request['include_diagnostics'] ) && 'yes' === $request['include_diagnostics'];
			$diagnostics   = array(
				'included' => $include_logs,
			);

			if ( $include_logs ) {
				$diagnostics['recent_logs']               = self::get_recent_logs( 25 );
				$diagnostics['recent_connection_failures'] = self::get_recent_failed_connection_events( 10 );
			}

			return array(
				'ticket_uuid' => isset( $request['ticket_uuid'] ) ? sanitize_text_field( $request['ticket_uuid'] ) : wp_generate_uuid4(),
				'site'        => array(
					'url'    => $prefill['site_url'],
					'domain' => $prefill['site_domain'],
				),
				'plugin'      => array(
					'variant'        => $prefill['plugin_variant'],
					'version'        => $prefill['plugin_version'],
					'license_status' => $prefill['license_status'],
				),
				'environment' => array(
					'wordpress_version' => $prefill['wp_version'],
					'php_version'       => $prefill['php_version'],
					'locale'            => get_locale(),
					'theme'             => wp_get_theme()->get( 'Name' ),
					'memory_limit'      => wp_convert_hr_to_bytes( WP_MEMORY_LIMIT ),
					'wp_debug'          => defined( 'WP_DEBUG' ) ? (bool) WP_DEBUG : false,
					'wp_debug_log'      => defined( 'WP_DEBUG_LOG' ) ? (bool) WP_DEBUG_LOG : false,
				),
				'request'     => array(
					'sender_email'        => isset( $request['sender_email'] ) ? sanitize_email( $request['sender_email'] ) : '',
					'subject'             => isset( $request['subject'] ) ? sanitize_text_field( $request['subject'] ) : '',
					'issue_type'          => isset( $request['issue_type'] ) ? sanitize_key( $request['issue_type'] ) : 'general',
					'message'             => isset( $request['message'] ) ? sanitize_textarea_field( $request['message'] ) : '',
					'include_diagnostics' => $include_logs ? 'yes' : 'no',
					'delivery_channels'   => isset( $request['delivery_channels'] ) && is_array( $request['delivery_channels'] ) ? array_values( array_map( 'sanitize_key', $request['delivery_channels'] ) ) : array( 'email' ),
				),
				'attachments' => self::normalize_support_attachments_for_payload( $request['attachments'] ?? array() ),
				'diagnostics' => $diagnostics,
			);
		}

		/**
		 * Deliver the support request via email.
		 *
		 * @param array $payload
		 * @return array
		 */
		private static function deliver_support_request_email( $payload = array() ) {
			$recipient    = sanitize_email( self::SUPPORT_EMAIL );
			$sender_email = isset( $payload['request']['sender_email'] ) ? sanitize_email( $payload['request']['sender_email'] ) : '';
			$site_domain  = isset( $payload['site']['domain'] ) ? sanitize_text_field( $payload['site']['domain'] ) : '';
			$issue_type   = isset( $payload['request']['issue_type'] ) ? sanitize_key( $payload['request']['issue_type'] ) : 'general';
			$ticket_uuid  = isset( $payload['ticket_uuid'] ) ? sanitize_text_field( $payload['ticket_uuid'] ) : wp_generate_uuid4();
			$ticket_subject = isset( $payload['request']['subject'] ) ? sanitize_text_field( $payload['request']['subject'] ) : '';
			$subject        = $ticket_subject !== ''
				? sprintf( '[WordForm Support][%1$s][%2$s] %3$s', strtoupper( $payload['plugin']['variant'] ?? 'PRO' ), $site_domain, $ticket_subject )
				: sprintf( '[WordForm Support][%1$s][%2$s] %3$s', strtoupper( $payload['plugin']['variant'] ?? 'PRO' ), $site_domain, $ticket_uuid );
			$body         = self::build_support_request_email_html( $payload );
			$headers      = array( 'Content-Type: text/html; charset=UTF-8' );
			if ( is_email( $sender_email ) ) {
				$headers[] = 'Reply-To: ' . $sender_email;
			}

			$sent = wp_mail(
				$recipient,
				$subject,
				$body,
				$headers,
				array()
			);

			return array(
				'sent'    => (bool) $sent,
				'message' => $sent ? __( 'Support email sent.', 'wordform-pro' ) : self::get_support_mail_failure_message_html(),
			);
		}

		/**
		 * Build a structured HTML support email.
		 *
		 * @param array $payload
		 * @return string
		 */
		private static function build_support_request_email_html( $payload = array() ) {
			$issue_type       = isset( $payload['request']['issue_type'] ) ? sanitize_key( $payload['request']['issue_type'] ) : 'general';
			$issue_type_label = self::get_issue_type_label( $issue_type );
			$environment      = isset( $payload['environment'] ) && is_array( $payload['environment'] ) ? $payload['environment'] : array();
			$diagnostics      = isset( $payload['diagnostics'] ) && is_array( $payload['diagnostics'] ) ? $payload['diagnostics'] : array();
			$recent_logs      = isset( $diagnostics['recent_logs'] ) && is_array( $diagnostics['recent_logs'] ) ? $diagnostics['recent_logs'] : array();
			$connection_logs  = isset( $diagnostics['recent_connection_failures'] ) && is_array( $diagnostics['recent_connection_failures'] ) ? $diagnostics['recent_connection_failures'] : array();
			$attachments      = isset( $payload['attachments'] ) && is_array( $payload['attachments'] ) ? $payload['attachments'] : array();
			$summary_rows     = array(
				__( 'Ticket ID', 'wordform-pro' )      => $payload['ticket_uuid'] ?? '',
				__( 'Subject', 'wordform-pro' )        => $payload['request']['subject'] ?? '',
				__( 'Issue Type', 'wordform-pro' )     => $issue_type_label,
				__( 'Sender Email', 'wordform-pro' )   => $payload['request']['sender_email'] ?? '',
				__( 'Site Domain', 'wordform-pro' )    => $payload['site']['domain'] ?? '',
				__( 'Site URL', 'wordform-pro' )       => $payload['site']['url'] ?? '',
				__( 'Plugin User', 'wordform-pro' )    => strtoupper( (string) ( $payload['plugin']['variant'] ?? 'pro' ) ),
				__( 'Plugin Version', 'wordform-pro' ) => $payload['plugin']['version'] ?? '',
				__( 'License Status', 'wordform-pro' ) => ucfirst( (string) ( $payload['plugin']['license_status'] ?? 'inactive' ) ),
				__( 'Delivery Channels', 'wordform-pro' ) => implode( ', ', array_map( 'ucfirst', (array) ( $payload['request']['delivery_channels'] ?? array( 'email' ) ) ) ),
			);
			$environment_rows = array(
				__( 'WordPress Version', 'wordform-pro' ) => $environment['wordpress_version'] ?? '',
				__( 'PHP Version', 'wordform-pro' )       => $environment['php_version'] ?? '',
				__( 'Locale', 'wordform-pro' )            => $environment['locale'] ?? '',
				__( 'Theme', 'wordform-pro' )             => $environment['theme'] ?? '',
				__( 'Memory Limit', 'wordform-pro' )      => self::format_support_email_value( $environment['memory_limit'] ?? '' ),
				__( 'WP_DEBUG', 'wordform-pro' )          => self::format_support_email_value( $environment['wp_debug'] ?? false ),
				__( 'WP_DEBUG_LOG', 'wordform-pro' )      => self::format_support_email_value( $environment['wp_debug_log'] ?? false ),
			);
			$diagnostics_rows = array(
				__( 'Diagnostics Included', 'wordform-pro' ) => ! empty( $diagnostics['included'] ) ? __( 'Yes', 'wordform-pro' ) : __( 'No', 'wordform-pro' ),
				__( 'Recent Plugin Logs', 'wordform-pro' )   => count( $recent_logs ),
				__( 'Connection Failures', 'wordform-pro' )  => count( $connection_logs ),
			);

			$html  = '<!doctype html><html><head><meta charset="UTF-8"></head><body style="margin:0;padding:24px;background:#f5f7fb;font-family:Arial,Helvetica,sans-serif;color:#1d2327;">';
			$html .= '<div style="max-width:880px;margin:0 auto;background:#ffffff;border:1px solid #dcdcde;border-radius:16px;overflow:hidden;">';
			$html .= '<div style="padding:24px 28px;background:linear-gradient(135deg,#2271b1 0%,#135e96 100%);color:#ffffff;">';
			$html .= '<div style="font-size:12px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;opacity:0.92;">' . esc_html__( 'WordForm Support', 'wordform-pro' ) . '</div>';
			$html .= '<h1 style="margin:10px 0 4px;font-size:24px;line-height:1.3;color:#ffffff;">' . esc_html__( 'New Support Request', 'wordform-pro' ) . '</h1>';
			$html .= '<p style="margin:0;font-size:14px;line-height:1.55;color:rgba(255,255,255,0.92);">' . esc_html__( 'Support request details and diagnostics were submitted from a WordForm site.', 'wordform-pro' ) . '</p>';
			$html .= '</div>';
			$html .= '<div style="padding:24px 28px;">';
			$html .= self::render_support_email_section(
				__( 'Request Summary', 'wordform-pro' ),
				self::render_support_email_table( $summary_rows )
			);
			$html .= self::render_support_email_section(
				__( 'Issue Details', 'wordform-pro' ),
				'<div style="padding:16px 18px;border:1px solid #e6e8eb;border-radius:12px;background:#fafbfd;white-space:pre-wrap;line-height:1.65;">' . nl2br( esc_html( (string) ( $payload['request']['message'] ?? '' ) ) ) . '</div>'
			);
			$html .= self::render_support_email_section(
				__( 'User Attachments', 'wordform-pro' ),
				self::render_support_attachment_links( $attachments )
			);
			$html .= self::render_support_email_section(
				__( 'Environment', 'wordform-pro' ),
				self::render_support_email_table( $environment_rows )
			);
			$html .= self::render_support_email_section(
				__( 'Diagnostics Overview', 'wordform-pro' ),
				self::render_support_email_table( $diagnostics_rows )
			);

			if ( ! empty( $diagnostics['included'] ) ) {
				$html .= self::render_support_email_section(
					__( 'Recent Plugin Logs', 'wordform-pro' ),
					self::render_support_log_table( $recent_logs )
				);
				$html .= self::render_support_email_section(
					__( 'Recent Connection Failures', 'wordform-pro' ),
					self::render_support_connection_failure_table( $connection_logs )
				);
			}

			$html .= '<p style="margin:24px 0 0;font-size:12px;line-height:1.6;color:#646970;">' . esc_html__( 'Diagnostics are redacted before sending. Sensitive values such as payment card data, API secrets, and full license keys are not included.', 'wordform-pro' ) . '</p>';
			$html .= '</div></div></body></html>';

			return $html;
		}

		/**
		 * Render a support email section wrapper.
		 *
		 * @param string $title
		 * @param string $content
		 * @return string
		 */
		private static function render_support_email_section( $title = '', $content = '' ) {
			return '<div style="margin-bottom:22px;">'
				. '<h2 style="margin:0 0 10px;font-size:16px;line-height:1.4;color:#1d2327;">' . esc_html( $title ) . '</h2>'
				. $content
				. '</div>';
		}

		/**
		 * Render a key/value table for support emails.
		 *
		 * @param array $rows
		 * @return string
		 */
		private static function render_support_email_table( $rows = array() ) {
			if ( empty( $rows ) || ! is_array( $rows ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No data available.', 'wordform-pro' ) . '</p>';
			}

			$html = '<table cellpadding="0" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;border:1px solid #e6e8eb;border-radius:12px;overflow:hidden;background:#ffffff;">';
			$row_index = 0;
			$row_total = count( $rows );
			foreach ( $rows as $label => $value ) {
				$border_style = ( $row_index === $row_total - 1 ) ? 'border-bottom:none;' : 'border-bottom:1px solid #e6e8eb;';
				$html .= '<tr>';
				$html .= '<th scope="row" style="width:220px;padding:12px 14px;text-align:left;vertical-align:top;' . $border_style . 'background:#f8fafc;font-size:13px;font-weight:600;color:#1d2327;">' . esc_html( $label ) . '</th>';
				$html .= '<td style="padding:12px 14px;vertical-align:top;' . $border_style . 'font-size:13px;line-height:1.6;color:#1d2327;">' . wp_kses_post( self::format_support_email_value( $value ) ) . '</td>';
				$html .= '</tr>';
				$row_index++;
			}
			$html .= '</table>';

			return $html;
		}

		private static function render_support_attachment_links( $attachments = array() ) {
			if ( empty( $attachments ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No screenshots or PDF files were attached.', 'wordform-pro' ) . '</p>';
			}

			$rows = array();
			foreach ( (array) $attachments as $attachment ) {
				$name = sanitize_file_name( (string) ( $attachment['name'] ?? __( 'Attachment', 'wordform-pro' ) ) );
				$url  = esc_url( (string) ( $attachment['url'] ?? '' ) );
				if ( '' === $url ) {
					continue;
				}

				$size_label = ! empty( $attachment['size'] ) ? size_format( (int) $attachment['size'] ) : '';
				$type_label = sanitize_text_field( (string) ( $attachment['type'] ?? '' ) );
				$meta       = trim( implode( ' / ', array_filter( array( $type_label, $size_label ) ) ) );
				$rows[ $name ] = '<a href="' . $url . '" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Open attachment', 'wordform-pro' ) . '</a>' . ( '' !== $meta ? '<br><small style="color:#646970;">' . esc_html( $meta ) . '</small>' : '' );
			}

			return ! empty( $rows ) ? self::render_support_email_table( $rows ) : '<p style="margin:0;color:#646970;">' . esc_html__( 'No screenshots or PDF files were attached.', 'wordform-pro' ) . '</p>';
		}

		/**
		 * Render recent support logs as an HTML table.
		 *
		 * @param array $logs
		 * @return string
		 */
		private static function render_support_log_table( $logs = array() ) {
			if ( empty( $logs ) || ! is_array( $logs ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No recent plugin logs were included.', 'wordform-pro' ) . '</p>';
			}

			$html = '<table cellpadding="0" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;border:1px solid #e6e8eb;border-radius:12px;overflow:hidden;background:#ffffff;">';
			$html .= '<thead><tr>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Time', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Area', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Event', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Details', 'wordform-pro' ) . '</th>'
				. '</tr></thead><tbody>';

			foreach ( $logs as $log ) {
				$context_summary = '';
				if ( ! empty( $log['context_json'] ) ) {
					$decoded_context = json_decode( $log['context_json'], true );
					if ( is_array( $decoded_context ) ) {
						$context_summary = self::format_support_context_summary( $decoded_context );
					}
				}

				$details = sanitize_textarea_field( $log['message'] ?? '' );
				if ( '' !== $context_summary ) {
					$details .= '<div style="margin-top:6px;color:#646970;"><strong>' . esc_html__( 'Context:', 'wordform-pro' ) . '</strong> ' . esc_html( $context_summary ) . '</div>';
				}

				$html .= '<tr>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( $log['created_at'] ?? '' ) . '</td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( ucfirst( (string) ( $log['subsystem'] ?? '' ) ) ) . '<br><span style="color:#646970;">' . esc_html( strtoupper( (string) ( $log['severity'] ?? '' ) ) ) . '</span></td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( $log['event_code'] ?? '' ) . '</td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.6;">' . wp_kses_post( $details ) . '</td>';
				$html .= '</tr>';
			}

			$html .= '</tbody></table>';

			return $html;
		}

		/**
		 * Render connection failures as an HTML table.
		 *
		 * @param array $failures
		 * @return string
		 */
		private static function render_support_connection_failure_table( $failures = array() ) {
			if ( empty( $failures ) || ! is_array( $failures ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No recent connection failures were included.', 'wordform-pro' ) . '</p>';
			}

			$html = '<table cellpadding="0" cellspacing="0" border="0" style="width:100%;border-collapse:collapse;border:1px solid #e6e8eb;border-radius:12px;overflow:hidden;background:#ffffff;">';
			$html .= '<thead><tr>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Time', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Form', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Application', 'wordform-pro' ) . '</th>'
				. '<th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Reason', 'wordform-pro' ) . '</th>'
				. '</tr></thead><tbody>';

			foreach ( $failures as $failure ) {
				$reason = sanitize_textarea_field( $failure['reason'] ?? '' );
				$comment = sanitize_textarea_field( $failure['comment'] ?? '' );
				if ( '' !== $comment ) {
					$reason .= '<div style="margin-top:6px;color:#646970;"><strong>' . esc_html__( 'Comment:', 'wordform-pro' ) . '</strong> ' . esc_html( $comment ) . '</div>';
				}

				$html .= '<tr>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( $failure['created_at'] ?? '' ) . '</td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( $failure['form_name'] ?? '' ) . '<br><span style="color:#646970;">' . esc_html( $failure['form_id'] ?? '' ) . '</span></td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.5;">' . esc_html( ucfirst( (string) ( $failure['app_slug'] ?? '' ) ) ) . '</td>';
				$html .= '<td style="padding:11px 12px;vertical-align:top;border-bottom:1px solid #e6e8eb;font-size:12px;line-height:1.6;">' . wp_kses_post( $reason ) . '</td>';
				$html .= '</tr>';
			}

			$html .= '</tbody></table>';

			return $html;
		}

		/**
		 * Format support email values consistently.
		 *
		 * @param mixed $value
		 * @return string
		 */
		private static function format_support_email_value( $value ) {
			if ( is_bool( $value ) ) {
				return $value ? esc_html__( 'Enabled', 'wordform-pro' ) : esc_html__( 'Disabled', 'wordform-pro' );
			}

			if ( is_numeric( $value ) && (int) $value > 1048576 ) {
				return esc_html( size_format( (int) $value ) );
			}

			if ( is_array( $value ) ) {
				return esc_html( wp_json_encode( $value, JSON_UNESCAPED_SLASHES ) );
			}

			return esc_html( (string) $value );
		}

		/**
		 * Build a concise one-line context summary for support emails.
		 *
		 * @param array $context
		 * @return string
		 */
		private static function format_support_context_summary( $context = array() ) {
			$parts = array();
			foreach ( $context as $key => $value ) {
				if ( is_array( $value ) ) {
					$value = wp_json_encode( $value, JSON_UNESCAPED_SLASHES );
				} elseif ( is_bool( $value ) ) {
					$value = $value ? 'true' : 'false';
				}

				$parts[] = sanitize_key( (string) $key ) . ': ' . sanitize_text_field( (string) $value );
			}

			return implode( ' | ', array_slice( $parts, 0, 6 ) );
		}

		/**
		 * Get the readable issue type label.
		 *
		 * @param string $issue_type
		 * @return string
		 */
		private static function get_issue_type_label( $issue_type = 'general' ) {
			$options = self::get_issue_type_options();

			return isset( $options[ $issue_type ] ) ? $options[ $issue_type ] : ucfirst( sanitize_text_field( $issue_type ) );
		}

		/**
		 * Get the HTML support mail failure message with WordSMTP recommendation.
		 *
		 * @return string
		 */
		private static function get_support_mail_failure_message_html() {
			$wordsmtp_install_link = '<a href="' . esc_url( admin_url( 'plugin-install.php?s=wordsmtp&tab=search&type=term' ) ) . '"><strong>' . __( 'WordSMTP', 'wordform-pro' ) . '</strong></a>';

			return wp_kses_post(
				wp_sprintf(
					/* translators: %s: WordSMTP install link */
					__( 'Support request was saved locally, but this WordPress site could not send the support email right now. This is usually a WordPress mail delivery configuration issue. Please check your WordPress mail setup or install %s for a faster and more reliable email delivery setup.', 'wordform-pro' ),
					$wordsmtp_install_link
				)
			);
		}

		/**
		 * Prepare default delivery results for the requested channels.
		 *
		 * @param array $channels
		 * @return array
		 */
		private static function prepare_delivery_results( $channels ) {
			$results = array();
			foreach ( (array) $channels as $channel ) {
				$results[ $channel ] = array(
					'status'  => 'queued',
					'message' => __( 'Queued for delivery.', 'wordform-pro' ),
				);
			}
			return $results;
		}

		/**
		 * Check if any delivery channel completed successfully.
		 *
		 * @param array $results
		 * @return bool
		 */
		private static function has_any_successful_delivery( $results ) {
			foreach ( (array) $results as $result ) {
				if ( in_array( ( $result['status'] ?? '' ), array( 'sent', 'open', 'in_review', 'waiting_on_customer', 'resolved', 'closed' ), true ) ) {
					return true;
				}
			}
			return false;
		}

		/**
		 * Flatten the primary delivery status for backward-compatible columns.
		 *
		 * @param array $results
		 * @return string
		 */
		private static function flatten_primary_delivery_status( $results ) {
			if ( isset( $results['email']['status'] ) ) {
				return sanitize_key( $results['email']['status'] );
			}
			foreach ( (array) $results as $result ) {
				if ( ! empty( $result['status'] ) ) {
					return sanitize_key( $result['status'] );
				}
			}
			return 'pending';
		}

		/**
		 * Flatten the primary delivery message for backward-compatible columns.
		 *
		 * @param array $results
		 * @return string
		 */
		private static function flatten_primary_delivery_message( $results ) {
			if ( isset( $results['email']['message'] ) ) {
				return sanitize_textarea_field( $results['email']['message'] );
			}
			foreach ( (array) $results as $result ) {
				if ( ! empty( $result['message'] ) ) {
					return sanitize_textarea_field( $result['message'] );
				}
			}
			return '';
		}

		/**
		 * Decode a JSON field into an array.
		 *
		 * @param mixed $value
		 * @return array
		 */
		private static function decode_json_field( $value ) {
			if ( is_array( $value ) ) {
				return $value;
			}
			$decoded = json_decode( (string) $value, true );
			return is_array( $decoded ) ? $decoded : array();
		}

		private static function get_support_office_api_base() {
			if ( defined( 'SFTCY_SOFTCOY_API_BASE' ) && '' !== SFTCY_SOFTCOY_API_BASE ) {
				return SFTCY_SOFTCOY_API_BASE;
			}

			return self::SUPPORT_OFFICE_PROD_API_BASE;
		}

		public static function get_support_office_status_endpoint() {
			return self::get_support_office_status_url();
		}

		private static function get_support_office_request_url() {
			return trailingslashit( self::get_support_office_api_base() ) . 'support/request';
		}

		private static function get_support_office_status_url() {
			return trailingslashit( self::get_support_office_api_base() ) . 'support/tickets/status';
		}

		private static function should_verify_remote_ssl( $url ) {
			$host = wp_parse_url( $url, PHP_URL_HOST );
			$host = is_string( $host ) ? strtolower( $host ) : '';

			return ! in_array( $host, array( 'localhost', '127.0.0.1' ), true );
		}

		private static function get_license_key() {
			return sanitize_text_field( (string) get_option( 'softcoy_wordform_pro_license_key', '' ) );
		}

		private static function deliver_support_request_office( $payload = array() ) {
			$request_url = self::get_support_office_request_url();
			$plugin_variant = sanitize_text_field( $payload['plugin']['variant'] ?? self::get_plugin_variant() );
			$plugin_slug    = 'pro' === $plugin_variant ? 'wordform-pro' : 'wordform';
			$plugin_name    = 'pro' === $plugin_variant ? 'WordForm Pro' : 'WordForm';
			$license_key    = 'pro' === $plugin_variant ? self::get_license_key() : '';

			$body = array(
				'name'        => sanitize_text_field( wp_get_current_user()->display_name ?: get_bloginfo( 'name' ) ),
				'sender_email'=> sanitize_email( $payload['request']['sender_email'] ?? '' ),
				'subject'     => sanitize_text_field( $payload['request']['subject'] ?? '' ),
				'issue_type'  => sanitize_key( $payload['request']['issue_type'] ?? 'general' ),
				'message'     => sanitize_textarea_field( $payload['request']['message'] ?? '' ),
				'ticket_uuid' => sanitize_text_field( $payload['ticket_uuid'] ?? '' ),
				'license_key' => $license_key,
				'delivery_channels' => array_values( (array) ( $payload['request']['delivery_channels'] ?? array() ) ),
				'site'        => (array) ( $payload['site'] ?? array() ),
				'plugin'      => array(
					'slug'           => $plugin_slug,
					'name'           => $plugin_name,
					'variant'        => $plugin_variant,
					'version'        => sanitize_text_field( $payload['plugin']['version'] ?? '' ),
					'license_status' => sanitize_text_field( $payload['plugin']['license_status'] ?? '' ),
				),
				'environment' => (array) ( $payload['environment'] ?? array() ),
				'diagnostics' => (array) ( $payload['diagnostics'] ?? array() ),
				'attachments' => (array) ( $payload['attachments'] ?? array() ),
			);

			$response = wp_remote_post(
				$request_url,
				array(
					'timeout'   => 20,
					'sslverify' => self::should_verify_remote_ssl( $request_url ),
					'headers'   => array(
						'Accept'       => 'application/json',
						'Content-Type' => 'application/json',
					),
					'body'      => wp_json_encode( $body ),
				)
			);

			if ( is_wp_error( $response ) ) {
				self::log_event( 'support', 'error', 'support_office_delivery_failed', $response->get_error_message(), array( 'ticket_uuid' => $payload['ticket_uuid'] ?? '' ) );

				return array(
					'sent'    => false,
					'status'  => 'failed',
					'message' => __( 'SOFTCOY Support Office could not be reached from this site right now.', 'wordform-pro' ),
				);
			}

			$response_code = (int) wp_remote_retrieve_response_code( $response );
			$response_body = self::decode_json_field( wp_remote_retrieve_body( $response ) );

			if ( $response_code < 200 || $response_code >= 300 || empty( $response_body['ticket_id'] ) ) {
				self::log_event( 'support', 'error', 'support_office_delivery_rejected', 'SOFTCOY Support Office rejected the request.', array( 'ticket_uuid' => $payload['ticket_uuid'] ?? '', 'response_code' => $response_code ) );

				return array(
					'sent'    => false,
					'status'  => 'failed',
					'message' => __( 'SOFTCOY Support Office rejected the support request. Please try again shortly.', 'wordform-pro' ),
				);
			}

			return array(
				'sent'      => true,
				'ticket_id' => sanitize_text_field( $response_body['ticket_id'] ?? '' ),
				'status'    => sanitize_key( $response_body['status'] ?? 'open' ),
				'status_label' => sanitize_text_field( str_replace( '_', ' ', ucwords( $response_body['status'] ?? 'open' ) ) ),
				'message'   => __( 'Ticket delivered to the SOFTCOY Support Office.', 'wordform-pro' ),
				'updated_at' => current_time( 'mysql', 1 ),
				'resolved_at' => '',
				'timings' => array(),
				'latest_reply' => array(),
				'replies'   => array(),
			);
		}

		private static function sync_office_ticket_updates( $limit = 12 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_requests_tbl;
			$rows  = $wpdb->get_results(
				$wpdb->prepare(
					"SELECT id, sender_email, delivery_results, office_ticket_id
					FROM $table
					WHERE office_ticket_id != ''
					ORDER BY updated_at DESC
					LIMIT %d",
					max( 1, absint( $limit ) )
				),
				ARRAY_A
			);

			foreach ( $rows as $row ) {
				$sync_result = self::fetch_office_ticket_status( $row['office_ticket_id'], $row['sender_email'] );

				if ( empty( $sync_result['success'] ) ) {
					continue;
				}

				$delivery_results = self::decode_json_field( $row['delivery_results'] ?? '' );
				$delivery_results['office'] = array(
					'ticket_id'    => sanitize_text_field( $row['office_ticket_id'] ?? '' ),
					'status'       => sanitize_key( $sync_result['status'] ?? 'open' ),
					'status_label' => sanitize_text_field( $sync_result['status_label'] ?? 'Open' ),
					'message'      => sanitize_textarea_field( $sync_result['message'] ?? '' ),
					'updated_at'   => sanitize_text_field( $sync_result['updated_at'] ?? '' ),
					'resolved_at'  => sanitize_text_field( $sync_result['resolved_at'] ?? '' ),
					'timings'      => isset( $sync_result['timings'] ) && is_array( $sync_result['timings'] ) ? $sync_result['timings'] : array(),
					'replies'      => isset( $sync_result['replies'] ) && is_array( $sync_result['replies'] ) ? $sync_result['replies'] : array(),
					'latest_reply' => isset( $sync_result['latest_reply'] ) && is_array( $sync_result['latest_reply'] ) ? $sync_result['latest_reply'] : array(),
				);

				$wpdb->update(
					$table,
					array(
						'delivery_results'    => wp_json_encode( $delivery_results ),
						'overall_status'      => sanitize_key( $sync_result['status'] ?? 'open' ),
						'office_status'       => sanitize_key( $sync_result['status'] ?? 'open' ),
						'office_last_synced_at' => current_time( 'mysql', 1 ),
						'delivery_status'     => self::flatten_primary_delivery_status( $delivery_results ),
						'delivery_message'    => self::flatten_primary_delivery_message( $delivery_results ),
					),
					array( 'id' => absint( $row['id'] ) )
				);
			}
		}

		private static function fetch_office_ticket_status( $ticket_id = '', $email = '' ) {
			$ticket_id = sanitize_text_field( (string) $ticket_id );
			$email     = sanitize_email( (string) $email );

			if ( '' === $ticket_id || ! is_email( $email ) ) {
				return array( 'success' => false );
			}

			$request_url = self::get_support_office_status_url();
			$response    = wp_remote_post(
				$request_url,
				array(
					'timeout'   => 5,
					'sslverify' => self::should_verify_remote_ssl( $request_url ),
					'headers'   => array(
						'Accept'       => 'application/json',
						'Content-Type' => 'application/json',
					),
					'body'      => wp_json_encode(
						array(
							'email'     => $email,
							'ticket_id' => $ticket_id,
						)
					),
				)
			);

			if ( is_wp_error( $response ) ) {
				return array( 'success' => false );
			}

			$response_body = self::decode_json_field( wp_remote_retrieve_body( $response ) );
			$ticket        = isset( $response_body['tickets'][0] ) && is_array( $response_body['tickets'][0] ) ? $response_body['tickets'][0] : array();

			if ( empty( $ticket ) ) {
				return array( 'success' => false );
			}

			$latest_reply = isset( $ticket['latest_reply'] ) && is_array( $ticket['latest_reply'] ) ? $ticket['latest_reply'] : array();
			$reply_message = isset( $latest_reply['message'] ) ? sanitize_textarea_field( wp_strip_all_tags( $latest_reply['message'] ) ) : '';
			$reply_excerpt = '' !== $reply_message ? self::truncate_support_text( $reply_message ) : sprintf( __( 'Office status: %s', 'wordform-pro' ), sanitize_text_field( $ticket['status_label'] ?? 'Open' ) );

			return array(
				'success'      => true,
				'status'       => sanitize_key( $ticket['status'] ?? 'open' ),
				'status_label' => sanitize_text_field( $ticket['status_label'] ?? 'Open' ),
				'message'      => $reply_excerpt,
				'updated_at'   => sanitize_text_field( $ticket['updated_at'] ?? '' ),
				'resolved_at'  => sanitize_text_field( $ticket['resolved_at'] ?? '' ),
				'timings'      => isset( $ticket['timings'] ) && is_array( $ticket['timings'] ) ? $ticket['timings'] : array(),
				'latest_reply' => isset( $ticket['latest_reply'] ) && is_array( $ticket['latest_reply'] ) ? $ticket['latest_reply'] : array(),
				'replies'      => isset( $ticket['replies'] ) && is_array( $ticket['replies'] ) ? $ticket['replies'] : array(),
			);
		}

		private static function send_office_ticket_reply( $ticket_id = '', $email = '', $message = '' ) {
			$ticket_id = sanitize_text_field( (string) $ticket_id );
			$email     = sanitize_email( (string) $email );
			$message   = sanitize_textarea_field( (string) $message );

			if ( '' === $ticket_id || ! is_email( $email ) || '' === $message ) {
				return array( 'success' => false, 'message' => __( 'Reply data is incomplete.', 'wordform-pro' ) );
			}

			$request_url = self::get_support_office_status_url();
			$response    = wp_remote_post(
				$request_url,
				array(
					'timeout'   => 20,
					'sslverify' => self::should_verify_remote_ssl( $request_url ),
					'headers'   => array(
						'Accept'       => 'application/json',
						'Content-Type' => 'application/json',
					),
					'body'      => wp_json_encode(
						array(
							'email'         => $email,
							'ticket_id'     => $ticket_id,
							'name'          => wp_get_current_user()->display_name ?: get_bloginfo( 'name' ),
							'reply_message' => $message,
						)
					),
				)
			);

			if ( is_wp_error( $response ) ) {
				return array( 'success' => false, 'message' => $response->get_error_message() );
			}

			$response_body = self::decode_json_field( wp_remote_retrieve_body( $response ) );
			$ticket        = isset( $response_body['tickets'][0] ) && is_array( $response_body['tickets'][0] ) ? $response_body['tickets'][0] : array();

			if ( empty( $ticket ) ) {
				return array( 'success' => false, 'message' => __( 'SOFTCOY Support Office did not return the updated ticket thread.', 'wordform-pro' ) );
			}

			$latest_reply = isset( $ticket['latest_reply'] ) && is_array( $ticket['latest_reply'] ) ? $ticket['latest_reply'] : array();
			$reply_message = isset( $latest_reply['message'] ) ? sanitize_textarea_field( wp_strip_all_tags( $latest_reply['message'] ) ) : '';
			$reply_excerpt = '' !== $reply_message ? self::truncate_support_text( $reply_message ) : sprintf( __( 'Office status: %s', 'wordform-pro' ), sanitize_text_field( $ticket['status_label'] ?? 'In Review' ) );

			return array(
				'success'      => true,
				'status'       => sanitize_key( $ticket['status'] ?? 'in_review' ),
				'status_label' => sanitize_text_field( $ticket['status_label'] ?? 'In Review' ),
				'message'      => $reply_excerpt,
				'updated_at'   => sanitize_text_field( $ticket['updated_at'] ?? '' ),
				'resolved_at'  => sanitize_text_field( $ticket['resolved_at'] ?? '' ),
				'timings'      => isset( $ticket['timings'] ) && is_array( $ticket['timings'] ) ? $ticket['timings'] : array(),
				'latest_reply' => $latest_reply,
				'replies'      => isset( $ticket['replies'] ) && is_array( $ticket['replies'] ) ? $ticket['replies'] : array(),
			);
		}

		private static function truncate_support_text( $text = '' ) {
			$text = trim( wp_strip_all_tags( (string) $text ) );

			if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) {
				return mb_strlen( $text ) > 140 ? mb_substr( $text, 0, 137 ) . '...' : $text;
			}

			return strlen( $text ) > 140 ? substr( $text, 0, 137 ) . '...' : $text;
		}

		/**
		 * Prune old or excessive support logs.
		 *
		 * @return void
		 */
		private static function prune_logs() {
			global $wpdb;

			$table = $wpdb->prefix . SftcyWordformBase::$sc_wordform_support_logs_tbl;
			$wpdb->query(
				$wpdb->prepare(
					"DELETE FROM $table WHERE expires_at IS NOT NULL AND expires_at < %s",
					gmdate( 'Y-m-d H:i:s' )
				)
			);

			$total_rows = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table" );
			if ( $total_rows > self::LOG_ROW_LIMIT ) {
				$offset = $total_rows - self::LOG_ROW_LIMIT;
				$wpdb->query(
					$wpdb->prepare(
						"DELETE FROM $table ORDER BY id ASC LIMIT %d",
						$offset
					)
				);
			}
		}

		/**
		 * Redact sensitive values from support diagnostics.
		 *
		 * @param mixed $data
		 * @return mixed
		 */
		private static function redact_sensitive_data( $data ) {
			if ( is_array( $data ) ) {
				$redacted = array();
				foreach ( $data as $key => $value ) {
					$key_string = strtolower( (string) $key );
					if (
						false !== strpos( $key_string, 'secret' ) ||
						false !== strpos( $key_string, 'token' ) ||
						false !== strpos( $key_string, 'password' ) ||
						false !== strpos( $key_string, 'cvv' ) ||
						false !== strpos( $key_string, 'card' ) ||
						false !== strpos( $key_string, 'license' ) ||
						false !== strpos( $key_string, 'api_key' ) ||
						false !== strpos( $key_string, 'transaction_key' )
					) {
						$redacted[ $key ] = '[redacted]';
						continue;
					}

					if ( 'sender_email' !== $key_string && is_string( $value ) && is_email( $value ) ) {
						$redacted[ $key ] = self::mask_email( $value );
						continue;
					}

					$redacted[ $key ] = self::redact_sensitive_data( $value );
				}

				return $redacted;
			}

			return $data;
		}

		/**
		 * Get plugin variant identifier.
		 *
		 * @return string
		 */
		private static function get_plugin_variant() {
			if ( defined( 'SFTCY_WORDFORM_PLUGIN_FILE' ) ) {
				$basename = strtolower( plugin_basename( SFTCY_WORDFORM_PLUGIN_FILE ) );
				if ( strpos( $basename, '-pro/' ) !== false || strpos( $basename, 'pro.php' ) !== false ) {
					return 'pro';
				}
			}

			return 'free';
		}

		/**
		 * Mask email addresses in diagnostics logs.
		 *
		 * @param string $email
		 * @return string
		 */
		private static function mask_email( $email ) {
			$email = sanitize_email( $email );
			if ( ! is_email( $email ) ) {
				return $email;
			}

			list( $name, $domain ) = explode( '@', $email, 2 );
			$name = strlen( $name ) > 2 ? substr( $name, 0, 2 ) . str_repeat( '*', max( 1, strlen( $name ) - 2 ) ) : str_repeat( '*', strlen( $name ) );

			return $name . '@' . $domain;
		}
	}
}
