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

if ( ! class_exists( 'SftcyWordaiSupport' ) ) {
	class SftcyWordaiSupport {
		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( 'WA-%1$s-%2$03d', gmdate( 'ymdHis' ), wp_rand( 100, 999 ) );
		}

		public static function get_issue_type_options() {
			return array(
				'general'   => __( 'General', 'wordai-pro' ),
				'content'   => __( 'Content Generation', 'wordai-pro' ),
				'image'     => __( 'Image Generation', 'wordai-pro' ),
				'seo'       => __( 'SEO Fields', 'wordai-pro' ),
				'provider'  => __( 'AI Provider / API', 'wordai-pro' ),
				'embedding' => __( 'Contents Embedding', 'wordai-pro' ),
				'ai_chat'   => __( 'AI Chat Agent', 'wordai-pro' ),
				'streaming' => __( 'Streaming Mode', 'wordai-pro' ),
				'license'   => __( 'License', 'wordai-pro' ),
				'other'     => __( 'Other', 'wordai-pro' ),
			);
		}

		public static function get_delivery_channel_options() {
			return array(
				'email'  => __( 'Email Support', 'wordai-pro' ),
				'office' => __( 'SOFTCOY Support Office', 'wordai-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.', 'wordai-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.', 'wordai-pro' ),
					);
				}

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

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

				$attachments[] = array(
					'name'      => $original_name,
					'url'       => trailingslashit( SFTCY_WORDAI_PLUGIN_URL ) . 'support-request/' . rawurlencode( $stored_name ),
					'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_WORDAI_PLUGIN_DIR ) . 'support-request';

			if ( ! wp_mkdir_p( $directory ) ) {
				return new WP_Error( 'wordai_support_attachment_directory', __( 'The support attachment folder could not be created.', 'wordai-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;
		}

		public static function ensure_storage_ready() {
			global $wpdb;

			static $storage_ready = false;
			if ( $storage_ready ) {
				return;
			}
			$storage_ready = true;

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

			$charset_collate  = $wpdb->get_charset_collate();
			$support_requests = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_support_requests_tbl;
			$support_logs     = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_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 'pro' NOT NULL,
				plugin_version CHAR(50) DEFAULT '' NOT NULL,
				current_provider CHAR(30) DEFAULT 'openai' 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,
				provider CHAR(30) DEFAULT '' NOT NULL,
				object_type CHAR(50) DEFAULT '' NOT NULL,
				object_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 );
		}

		public static function get_support_prefill_data() {
			self::ensure_storage_ready();
			self::sync_office_ticket_updates( 12, false );

			$site_url         = home_url( '/' );
			$site_domain      = wp_parse_url( $site_url, PHP_URL_HOST );
			$current_provider = SftcyWordaiBase::sc_wordai_get_current_ai_provider();

			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_WORDAI_VERSION' ) ? SFTCY_WORDAI_VERSION : '',
				'current_provider'    => $current_provider,
				'provider_label'      => SftcyWordaiBase::sc_wordai_get_provider_label( $current_provider ),
				'wp_version'          => get_bloginfo( 'version' ),
				'php_version'         => PHP_VERSION,
				'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 recent WordAI plugin errors, provider failures, and AI Agent indexing failures. API keys, tokens, and other sensitive values are redacted before sending.', 'wordai-pro' ),
			);
		}

		public static function log_event( $subsystem = 'general', $severity = 'info', $event_code = '', $message = '', $context = array(), $provider = '', $object_type = '', $object_id = 0 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table      = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_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 ),
					'provider'     => sanitize_key( $provider ),
					'object_type'  => sanitize_key( $object_type ),
					'object_id'    => absint( $object_id ),
					'expires_at'   => $expires_at,
				)
			);

			self::prune_logs();
		}

		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.', 'wordai-pro' ) );
			}

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

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

			if ( '' === trim( $subject ) ) {
				$subject = sprintf(
					/* translators: %s: date. */
					__( 'WordAI support - %s', 'wordai-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 . SftcyWordaiBase::$sc_wordai_support_requests_tbl;
			$wpdb->insert(
				$table,
				array(
					'ticket_uuid'         => $ticket_uuid,
					'site_url'            => $payload['site']['url'] ?? '',
					'site_domain'         => $payload['site']['domain'] ?? '',
					'sender_email'        => $sender_email,
					'plugin_variant'      => $payload['plugin']['variant'] ?? 'pro',
					'plugin_version'      => $payload['plugin']['version'] ?? '',
					'current_provider'    => $payload['plugin']['current_provider'] ?? 'openai',
					'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', wp_strip_all_tags( $email_result['message'] ?? 'Support email delivery failed.' ), array( 'ticket_uuid' => $ticket_uuid ), $payload['plugin']['current_provider'] ?? '', 'support_request', $request_id );
				}
			}

			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'] ) && $delivery_results['email']['status'] === 'failed' && count( $delivery_channels ) === 1 ) {
				$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 )
			);

			$is_success = self::has_any_successful_delivery( $delivery_results );
			$message_text = $is_success
				? __( 'Support request sent successfully. Our team can now review your message and WordAI diagnostics.', 'wordai-pro' )
				: self::get_support_mail_failure_message_html();

			return array(
				'status'      => $is_success ? 'success' : 'fail',
				'message'     => $message_text,
				'ticket_uuid' => $ticket_uuid,
				'request_id'  => $request_id,
				'delivery_results' => $delivery_results,
				'overall_status' => $overall_status,
			);
		}

		public static function get_diagnostics_preview_summary() {
			$recent_logs   = self::get_recent_logs( 50 );
			$agent_failures = self::get_recent_agent_failures( 10 );
			$summary       = array(
				'total_logs'      => count( $recent_logs ),
				'provider_errors' => 0,
				'content_errors'  => 0,
				'chat_errors'     => 0,
				'agent_failures'  => count( $agent_failures ),
				'recent_agent_errors' => $agent_failures,
			);

			foreach ( $recent_logs as $log_row ) {
				$subsystem = sanitize_key( $log_row['subsystem'] ?? '' );
				if ( in_array( $subsystem, array( 'provider', 'auth' ), true ) ) {
					$summary['provider_errors']++;
				} elseif ( in_array( $subsystem, array( 'content', 'image', 'seo' ), true ) ) {
					$summary['content_errors']++;
				} elseif ( in_array( $subsystem, array( 'chat', 'rag' ), true ) ) {
					$summary['chat_errors']++;
				}
			}

			return $summary;
		}

		public static function get_recent_logs( $limit = 25 ) {
			global $wpdb;

			self::ensure_storage_ready();

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

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

		public static function get_recent_agent_failures( $limit = 10 ) {
			global $wpdb;

			$table = $wpdb->prefix . 'wordai_agent_sources';
			$limit = max( 1, absint( $limit ) );

			if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
				return array();
			}

			return $wpdb->get_results(
				$wpdb->prepare(
					"SELECT source_type, source_id, title, url, error_msg, updated_at, last_indexed
					FROM $table
					WHERE status = 'failed'
					ORDER BY COALESCE(updated_at, last_indexed, created_at) DESC, id DESC
					LIMIT %d",
					$limit
				),
				ARRAY_A
			);
		}

		public static function get_recent_support_requests( $limit = 10 ) {
			global $wpdb;

			self::ensure_storage_ready();

			$table = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_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 . SftcyWordaiBase::$sc_wordai_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.', 'wordai-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.', 'wordai-pro' ),
				);
			}

			if ( empty( $row['office_ticket_id'] ) ) {
				return array(
					'status'  => 'fail',
					'message' => __( 'This ticket was not delivered to the SOFTCOY office channel.', 'wordai-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.', 'wordai-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(),
				'latest_reply' => isset( $sync_result['latest_reply'] ) && is_array( $sync_result['latest_reply'] ) ? $sync_result['latest_reply'] : array(),
				'replies'      => isset( $sync_result['replies'] ) && is_array( $sync_result['replies'] ) ? $sync_result['replies'] : 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.', 'wordai-pro' ),
				'ticket_uuid'      => $ticket_uuid,
				'delivery_results' => $delivery_results,
				'overall_status'   => sanitize_key( $sync_result['status'] ?? 'in_review' ),
			);
		}

		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'];
			$provider     = $prefill['current_provider'] ?? 'openai';

			$diagnostics = array( 'included' => $include_logs );
			if ( $include_logs ) {
				$diagnostics['recent_logs'] = self::get_recent_logs( 25 );
				$diagnostics['recent_agent_failures'] = self::get_recent_agent_failures( 10 );
			}

			return array(
				'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'],
					'current_provider' => $provider,
					'provider_label'   => $prefill['provider_label'],
				),
				'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,
					'ssl_verify'        => SftcyWordaiBase::sc_wordai_should_verify_ssl(),
				),
				'request'     => array(
					'sender_email'        => sanitize_email( $request['sender_email'] ?? '' ),
					'subject'             => sanitize_text_field( $request['subject'] ?? '' ),
					'issue_type'          => sanitize_key( $request['issue_type'] ?? 'general' ),
					'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() ),
				'wordai'      => array(
					'streaming_enabled' => self::get_streaming_status( $provider ),
					'content_model'     => self::get_provider_model_snapshot( $provider, 'content' ),
					'image_model'       => self::get_provider_model_snapshot( $provider, 'image' ),
					'chat_settings'     => self::get_chat_diagnostics(),
					'agent_status'      => self::get_agent_status_snapshot(),
				),
				'diagnostics' => $diagnostics,
			);
		}

		private static function deliver_support_request_email( $payload = array() ) {
			$recipient    = sanitize_email( self::SUPPORT_EMAIL );
			$sender_email = sanitize_email( $payload['request']['sender_email'] ?? '' );
			$site_domain  = sanitize_text_field( $payload['site']['domain'] ?? '' );
			$ticket_uuid  = sanitize_text_field( $payload['ticket_uuid'] ?? wp_generate_uuid4() );
			$ticket_subject = sanitize_text_field( $payload['request']['subject'] ?? '' );
			$subject        = $ticket_subject !== ''
				? sprintf( '[WordAI Support][%1$s][%2$s] %3$s', strtoupper( (string) ( $payload['plugin']['variant'] ?? 'PRO' ) ), $site_domain, $ticket_subject )
				: sprintf( '[WordAI Support][%1$s][%2$s] %3$s', strtoupper( (string) ( $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.', 'wordai-pro' ) : self::get_support_mail_failure_message_html(),
			);
		}

		private static function build_support_request_email_html( $payload = array() ) {
			$issue_type_label = self::get_issue_type_label( sanitize_key( $payload['request']['issue_type'] ?? 'general' ) );
			$recent_logs      = (array) ( $payload['diagnostics']['recent_logs'] ?? array() );
			$agent_failures   = (array) ( $payload['diagnostics']['recent_agent_failures'] ?? array() );
			$attachments      = (array) ( $payload['attachments'] ?? array() );
			$summary_rows     = array(
				__( 'Ticket ID', 'wordai-pro' )       => $payload['ticket_uuid'] ?? '',
				__( 'Subject', 'wordai-pro' )         => $payload['request']['subject'] ?? '',
				__( 'Issue Type', 'wordai-pro' )      => $issue_type_label,
				__( 'Sender Email', 'wordai-pro' )    => $payload['request']['sender_email'] ?? '',
				__( 'Site Domain', 'wordai-pro' )     => $payload['site']['domain'] ?? '',
				__( 'Plugin Version', 'wordai-pro' )  => $payload['plugin']['version'] ?? '',
				__( 'AI Provider', 'wordai-pro' )     => $payload['plugin']['provider_label'] ?? '',
				__( 'Delivery Channels', 'wordai-pro' ) => implode( ', ', array_map( 'ucfirst', (array) ( $payload['request']['delivery_channels'] ?? array( 'email' ) ) ) ),
			);

			$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:#fff;border:1px solid #dcdcde;border-radius:16px;overflow:hidden;">';
			$html .= '<div style="padding:24px 28px;background:linear-gradient(135deg,#1f6feb 0%,#0e4fb3 100%);color:#fff;"><h1 style="margin:0;font-size:24px;">' . esc_html__( 'WordAI Support Request', 'wordai-pro' ) . '</h1></div>';
			$html .= '<div style="padding:24px 28px;">';
			$html .= self::render_support_email_table( $summary_rows );
			$html .= '<h2 style="margin:22px 0 8px;font-size:16px;">' . esc_html__( 'Issue Details', 'wordai-pro' ) . '</h2>';
			$html .= '<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 .= '<h2 style="margin:22px 0 8px;font-size:16px;">' . esc_html__( 'User Attachments', 'wordai-pro' ) . '</h2>';
			$html .= self::render_support_attachment_links( $attachments );
			$html .= '<h2 style="margin:22px 0 8px;font-size:16px;">' . esc_html__( 'WordAI Snapshot', 'wordai-pro' ) . '</h2>';
			$html .= self::render_support_email_table(
				array(
					__( 'Streaming Enabled', 'wordai-pro' ) => self::format_support_email_value( $payload['wordai']['streaming_enabled'] ?? false ),
					__( 'Content Model', 'wordai-pro' )     => $payload['wordai']['content_model'] ?? '',
					__( 'Image Model', 'wordai-pro' )       => $payload['wordai']['image_model'] ?? '',
					__( 'Chat Provider', 'wordai-pro' )     => $payload['wordai']['chat_settings']['provider_label'] ?? '',
					__( 'Chat Source', 'wordai-pro' )       => $payload['wordai']['chat_settings']['embedding_source_label'] ?? '',
					__( 'Indexed Sources', 'wordai-pro' )   => $payload['wordai']['agent_status']['indexed_count'] ?? 0,
					__( 'Failed Sources', 'wordai-pro' )    => $payload['wordai']['agent_status']['failed_count'] ?? 0,
				)
			);
			$html .= '<h2 style="margin:22px 0 8px;font-size:16px;">' . esc_html__( 'Recent Logs', 'wordai-pro' ) . '</h2>';
			$html .= self::render_support_log_table( $recent_logs );
			$html .= '<h2 style="margin:22px 0 8px;font-size:16px;">' . esc_html__( 'AI Agent Failures', 'wordai-pro' ) . '</h2>';
			$html .= self::render_support_agent_failure_table( $agent_failures );
			$html .= '<p style="margin:22px 0 0;font-size:12px;color:#646970;">' . esc_html__( 'Diagnostics are redacted before sending. Sensitive values such as API keys, tokens, and full prompts are not included.', 'wordai-pro' ) . '</p>';
			$html .= '</div></div></body></html>';

			return $html;
		}

		private static function render_support_email_table( $rows = array() ) {
			if ( empty( $rows ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No data available.', 'wordai-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><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><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></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.', 'wordai-pro' ) . '</p>';
			}

			$rows = array();
			foreach ( (array) $attachments as $attachment ) {
				$name = sanitize_file_name( (string) ( $attachment['name'] ?? __( 'Attachment', 'wordai-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', 'wordai-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.', 'wordai-pro' ) . '</p>';
		}

		private static function render_support_log_table( $logs = array() ) {
			if ( empty( $logs ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No recent WordAI logs were included.', 'wordai-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;"><thead><tr><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Time', 'wordai-pro' ) . '</th><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Subsystem', 'wordai-pro' ) . '</th><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Message', 'wordai-pro' ) . '</th></tr></thead><tbody>';
			foreach ( $logs as $log ) {
				$html .= '<tr><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;vertical-align:top;">' . esc_html( (string) ( $log['created_at'] ?? '' ) ) . '</td><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;vertical-align:top;">' . esc_html( ucfirst( str_replace( '_', ' ', (string) ( $log['subsystem'] ?? '' ) ) ) ) . '</td><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;line-height:1.6;vertical-align:top;">' . esc_html( (string) ( $log['message'] ?? '' ) ) . '</td></tr>';
			}
			$html .= '</tbody></table>';
			return $html;
		}

		private static function render_support_agent_failure_table( $failures = array() ) {
			if ( empty( $failures ) ) {
				return '<p style="margin:0;color:#646970;">' . esc_html__( 'No recent AI Agent failures were included.', 'wordai-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;"><thead><tr><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Source', 'wordai-pro' ) . '</th><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Type', 'wordai-pro' ) . '</th><th style="padding:11px 12px;text-align:left;background:#f8fafc;border-bottom:1px solid #e6e8eb;font-size:12px;">' . esc_html__( 'Error', 'wordai-pro' ) . '</th></tr></thead><tbody>';
			foreach ( $failures as $failure ) {
				$source_label = $failure['title'] ?: ( '#' . absint( $failure['source_id'] ?? 0 ) );
				$html .= '<tr><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;vertical-align:top;">' . esc_html( $source_label ) . '</td><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;vertical-align:top;">' . esc_html( ucfirst( (string) ( $failure['source_type'] ?? '' ) ) ) . '</td><td style="padding:11px 12px;border-bottom:1px solid #eef0f2;font-size:12px;line-height:1.6;vertical-align:top;">' . esc_html( (string) ( $failure['error_msg'] ?? '' ) ) . '</td></tr>';
			}
			$html .= '</tbody></table>';
			return $html;
		}

		private static function format_support_email_value( $value ) {
			if ( is_bool( $value ) ) {
				return $value ? __( 'Yes', 'wordai-pro' ) : __( 'No', 'wordai-pro' );
			}
			if ( is_array( $value ) ) {
				return '<code>' . esc_html( wp_json_encode( self::redact_sensitive_data( $value ) ) ) . '</code>';
			}
			$value = (string) $value;
			return '' !== trim( $value ) ? esc_html( $value ) : '—';
		}

		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 ) );
		}

		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', 'wordai-pro' ) . '</strong></a>';
			return wp_kses_post( wp_sprintf( __( '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.', 'wordai-pro' ), $wordsmtp_install_link ) );
		}

		private static function prepare_delivery_results( $channels ) {
			$results = array();
			foreach ( (array) $channels as $channel ) {
				$results[ $channel ] = array(
					'status'  => 'queued',
					'message' => __( 'Queued for delivery.', 'wordai-pro' ),
				);
			}
			return $results;
		}

		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;
		}

		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';
		}

		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 '';
		}

		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() {
			return defined( 'SFTCY_SOFTCOY_API_BASE' ) ? SFTCY_SOFTCOY_API_BASE : self::SUPPORT_OFFICE_PROD_API_BASE;
		}

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

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

		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_wordai_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() );
			$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'] ?? '' ),
				'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'             => 'wordai',
					'name'             => 'WordAI',
					'variant'          => $plugin_variant,
					'version'          => sanitize_text_field( $payload['plugin']['version'] ?? '' ),
					'current_provider' => sanitize_text_field( $payload['plugin']['current_provider'] ?? '' ),
					'provider_label'   => sanitize_text_field( $payload['plugin']['provider_label'] ?? '' ),
				),
				'environment'  => (array) ( $payload['environment'] ?? array() ),
				'diagnostics'  => (array) ( $payload['diagnostics'] ?? array() ),
				'attachments'  => (array) ( $payload['attachments'] ?? array() ),
				'wordai'       => (array) ( $payload['wordai'] ?? 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'] ?? '' ), $payload['plugin']['current_provider'] ?? '', 'support_request', 0 );

				return array(
					'sent'    => false,
					'status'  => 'failed',
					'message' => __( 'SOFTCOY Support Office could not be reached from this site right now.', 'wordai-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 ), $payload['plugin']['current_provider'] ?? '', 'support_request', 0 );

				return array(
					'sent'    => false,
					'status'  => 'failed',
					'message' => __( 'SOFTCOY Support Office rejected the support request. Please try again shortly.', 'wordai-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.', 'wordai-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, $force = false ) {
			global $wpdb;

			self::ensure_storage_ready();

			$sync_lock = 'sftcy_wordai_support_ticket_sync_lock';
			if ( ! $force && get_transient( $sync_lock ) ) {
				return;
			}
			set_transient( $sync_lock, 1, 5 * MINUTE_IN_SECONDS );

			$table = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_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'   => 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,
						)
					),
				)
			);

			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', 'wordai-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.', 'wordai-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.', 'wordai-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', 'wordai-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;
		}

		private static function get_plugin_variant() {
			if ( defined( 'SFTCY_WORDAI_PLUGIN_FILE' ) ) {
				$basename = strtolower( plugin_basename( SFTCY_WORDAI_PLUGIN_FILE ) );
				if ( strpos( $basename, '-pro/' ) !== false || strpos( $basename, 'pro.php' ) !== false ) {
					return 'pro';
				}
			}

			return 'free';
		}

		private static function prune_logs() {
			global $wpdb;

			$prune_lock = 'sftcy_wordai_support_log_prune_lock';
			if ( get_transient( $prune_lock ) ) {
				return;
			}
			set_transient( $prune_lock, 1, 6 * HOUR_IN_SECONDS );

			$table = $wpdb->prefix . SftcyWordaiBase::$sc_wordai_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 ) );
			}
		}

		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, 'license' ) || false !== strpos( $key_string, 'api_key' ) || false !== strpos( $key_string, 'authorization' ) || false !== strpos( $key_string, 'prompt' ) ) {
						$redacted[ $key ] = '[redacted]';
						continue;
					}
					$redacted[ $key ] = self::redact_sensitive_data( $value );
				}
				return $redacted;
			}
			return $data;
		}

		private static function get_streaming_status( $provider ) {
			switch ( $provider ) {
				case 'google':
					return method_exists( 'SftcyWordaiGoogleGeminiApi', 'sc_gemini_streaming_status' )
						? (bool) SftcyWordaiGoogleGeminiApi::sc_gemini_streaming_status()
						: false;
				case 'anthropic':
					return method_exists( 'SftcyWordaiAnthropicApi', 'sc_anthropic_streaming_status' )
						? (bool) SftcyWordaiAnthropicApi::sc_anthropic_streaming_status()
						: false;
				case 'openai':
				default:
					return method_exists( 'SftcyWordaiOpenai', 'sc_wordai_streaming_status' )
						? (bool) SftcyWordaiOpenai::sc_wordai_streaming_status()
						: false;
			}
		}

		private static function get_provider_model_snapshot( $provider, $type = 'content' ) {
			if ( 'image' === $type && ! SftcyWordaiBase::sc_wordai_provider_supports( 'image', $provider ) ) {
				return __( 'Not supported for this provider', 'wordai-pro' );
			}
			switch ( $provider ) {
				case 'google':
					return 'image' === $type ? (string) get_option( 'sftcy-wordai-google-gemini-image-model-slug', 'gemini-3.1-flash-image' ) : (string) get_option( 'sftcy-wordai-google-gemini-model-slug', 'gemini-3.5-flash' );
				case 'anthropic':
					return 'image' === $type ? __( 'Not supported for this provider', 'wordai-pro' ) : (string) get_option( 'sftcy-wordai-anthropic-model-slug', 'claude-sonnet-5' );
				case 'openai':
				default:
					return 'image' === $type ? (string) get_option( 'sftcy-wordai-openai-image-model-slug', 'gpt-image-1.5' ) : (string) get_option( 'sftcy-wordai-openai-model-slug', 'gpt-4.1-mini' );
			}
		}

		private static function get_chat_diagnostics() {
			$provider = SftcyWordaiBase::sc_wordai_get_current_ai_provider();
			$source   = get_option( 'sc_wordai_chat_embedding_source_' . $provider, $provider );
			return array(
				'provider'               => $provider,
				'provider_label'         => SftcyWordaiBase::sc_wordai_get_provider_label( $provider ),
				'embedding_source'       => sanitize_key( (string) $source ),
				'embedding_source_label' => SftcyWordaiBase::sc_wordai_get_provider_label( $source ),
				'reply_mode'             => sanitize_key( (string) get_option( 'sc_wordai_chat_reply_mode', 'nonstream' ) ),
			);
		}

		private static function get_agent_status_snapshot() {
			global $wpdb;

			$table = $wpdb->prefix . 'wordai_agent_sources';
			if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
				return array( 'indexed_count' => 0, 'failed_count' => 0, 'ready_count' => 0 );
			}

			return array(
				'indexed_count' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status = 'done'" ),
				'failed_count'  => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status = 'failed'" ),
				'ready_count'   => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE status = 'ready'" ),
			);
		}
	}
}
