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

include_once SFTCY_WORDAI_PLUGIN_DIR . 'admin/views/settings-pages-header-template.php';

$support_prefill_data = isset( $support_prefill_data ) && is_array( $support_prefill_data ) ? $support_prefill_data : SftcyWordaiSupport::get_support_prefill_data();
$diagnostics_preview  = isset( $support_prefill_data['diagnostics_preview'] ) && is_array( $support_prefill_data['diagnostics_preview'] ) ? $support_prefill_data['diagnostics_preview'] : array();
$recent_requests      = isset( $support_prefill_data['recent_requests'] ) && is_array( $support_prefill_data['recent_requests'] ) ? $support_prefill_data['recent_requests'] : array();
$default_subject      = sprintf(
	/* translators: %s: date. */
	__( 'WordAI support - %s', 'wordai-pro' ),
	date_i18n( get_option( 'date_format' ) )
);
$support_status_badge = static function ( $status, $office_data = array() ) {
	$status_key  = sanitize_key( (string) $status );
	$latest_reply = array();
	if ( ! empty( $office_data['latest_reply'] ) && is_array( $office_data['latest_reply'] ) ) {
		$latest_reply = $office_data['latest_reply'];
	} elseif ( ! empty( $office_data['replies'] ) && is_array( $office_data['replies'] ) ) {
		$office_replies = $office_data['replies'];
		$latest_reply   = end( $office_replies );
	}
	$latest_role = is_array( $latest_reply ) ? sanitize_key( (string) ( $latest_reply['role'] ?? '' ) ) : '';
	$has_replies = ! empty( $office_data['replies'] ) || ! empty( $office_data['latest_reply'] ) || ! empty( $office_data['resolved_at'] );

	if ( in_array( $status_key, array( 'resolved', 'closed', 'solved' ), true ) ) {
		return array( 'is-resolved', __( 'Solved', 'wordai-pro' ) );
	}

	if ( in_array( $status_key, array( 'failed', 'error', 'rejected' ), true ) ) {
		return array( 'is-error', __( 'Needs attention', 'wordai-pro' ) );
	}

	if ( 'customer_replied' === $status_key || false !== strpos( $latest_role, 'customer' ) ) {
		return array( 'is-waiting', __( 'Waiting for SOFTCOY', 'wordai-pro' ) );
	}

	if ( $has_replies || in_array( $status_key, array( 'answered', 'replied', 'in_review', 'pending_customer', 'waiting_on_customer' ), true ) ) {
		return array( 'is-replied', __( 'SOFTCOY replied', 'wordai-pro' ) );
	}

	return array( 'is-open', __( 'Open', 'wordai-pro' ) );
};
?>
<div class="wrap sc-wordai-support-page-wrapper">
	<div class="sc-wordai-page-header-with-action sc-wordai-support-page-header">
		<div class="sc-wordai-support-page-header-copy">
			<h3><span class="dashicons dashicons-sos"></span><?php esc_html_e( 'WordAI Support', 'wordai-pro' ); ?></h3>
			<p><?php esc_html_e( 'Send a structured support request with your WordAI diagnostics so our team can identify the issue faster.', 'wordai-pro' ); ?></p>
		</div>
	</div>

	<div class="sc-wordai-support-summary-grid">
		<div class="sc-wordai-support-summary-card">
			<span class="sc-wordai-support-summary-label"><?php esc_html_e( 'Site', 'wordai-pro' ); ?></span>
			<strong class="sc-wordai-support-summary-value"><?php echo esc_html( $support_prefill_data['site_domain'] ?? '' ); ?></strong>
		</div>
		<div class="sc-wordai-support-summary-card">
			<span class="sc-wordai-support-summary-label"><?php esc_html_e( 'Plugin Version', 'wordai-pro' ); ?></span>
			<strong class="sc-wordai-support-summary-value"><?php echo esc_html( strtoupper( $support_prefill_data['plugin_variant'] ?? 'pro' ) . ' ' . ( $support_prefill_data['plugin_version'] ?? '' ) ); ?></strong>
		</div>
		<div class="sc-wordai-support-summary-card">
			<span class="sc-wordai-support-summary-label"><?php esc_html_e( 'Recent Logs', 'wordai-pro' ); ?></span>
			<strong class="sc-wordai-support-summary-value"><?php echo esc_html( $diagnostics_preview['total_logs'] ?? 0 ); ?></strong>
		</div>
	</div>

	<div class="sc-wordai-support-layout">
		<div class="sc-wordai-support-form-card">
			<h3><span class="dashicons dashicons-email-alt"></span><?php esc_html_e( 'Open Support Request', 'wordai-pro' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Users can send support requests quickly without exposing API keys or other sensitive values.', 'wordai-pro' ); ?></p>

			<div class="sc-wordai-support-submit-feedback" hidden></div>

			<form id="wordaiSupportRequestForm" class="sc-wordai-support-request-form">
				<div class="sc-wordai-support-attachment-toolbar">
					<button type="button" class="button sc-wordai-support-attach-btn" id="wordaiSupportAttachButton">
						<span class="dashicons dashicons-paperclip" aria-hidden="true"></span>
						<?php esc_html_e( 'Attach', 'wordai-pro' ); ?>
					</button>
					<input type="file" id="wordaiSupportAttachments" name="support_attachments[]" accept="image/jpeg,image/png,image/gif,image/webp,application/pdf" multiple hidden />
					<div class="sc-wordai-support-attachment-list" id="wordaiSupportAttachmentList" aria-live="polite"></div>
				</div>
				<table class="form-table">
					<tbody>
						<tr>
							<th scope="row"><label for="wordaiSupportSenderEmail"><?php esc_html_e( 'Sender Email', 'wordai-pro' ); ?></label></th>
							<td><input type="email" id="wordaiSupportSenderEmail" name="sender_email" class="regular-text" value="<?php echo esc_attr( $support_prefill_data['sender_email'] ?? '' ); ?>" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportSiteUrl"><?php esc_html_e( 'Site URL', 'wordai-pro' ); ?></label></th>
							<td><input type="text" id="wordaiSupportSiteUrl" class="regular-text" value="<?php echo esc_attr( $support_prefill_data['site_url'] ?? '' ); ?>" readonly /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportPluginType"><?php esc_html_e( 'Plugin Type', 'wordai-pro' ); ?></label></th>
							<td><input type="text" id="wordaiSupportPluginType" class="regular-text" value="<?php echo esc_attr( strtoupper( $support_prefill_data['plugin_variant'] ?? 'free' ) ); ?>" readonly /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportProvider"><?php esc_html_e( 'Current AI Provider', 'wordai-pro' ); ?></label></th>
							<td><input type="text" id="wordaiSupportProvider" class="regular-text" value="<?php echo esc_attr( $support_prefill_data['provider_label'] ?? '' ); ?>" readonly /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportSubject"><?php esc_html_e( 'Subject', 'wordai-pro' ); ?></label></th>
							<td>
								<input type="text" id="wordaiSupportSubject" name="subject" class="regular-text" value="<?php echo esc_attr( $default_subject ); ?>" />
								<p class="description"><?php esc_html_e( 'Edit this short subject so the ticket is easy to identify later in both WordPress and SOFTCOY.', 'wordai-pro' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportIssueType"><?php esc_html_e( 'Issue Type', 'wordai-pro' ); ?></label></th>
							<td>
								<select id="wordaiSupportIssueType" name="issue_type">
									<?php foreach ( (array) ( $support_prefill_data['issue_type_options'] ?? array() ) as $issue_key => $issue_label ) : ?>
										<option value="<?php echo esc_attr( $issue_key ); ?>"><?php echo esc_html( $issue_label ); ?></option>
									<?php endforeach; ?>
								</select>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Delivery Channel', 'wordai-pro' ); ?></th>
							<td>
								<div class="sc-wordai-support-delivery-options">
									<label class="sc-wordai-support-delivery-card is-active">
										<input type="checkbox" name="delivery_channels[]" value="email" checked />
										<span class="sc-wordai-support-delivery-title"><?php esc_html_e( 'Email Support', 'wordai-pro' ); ?></span>
										<small><?php echo esc_html( $support_prefill_data['support_email'] ?? '' ); ?></small>
									</label>
									<label class="sc-wordai-support-delivery-card is-active">
										<input type="checkbox" name="delivery_channels[]" value="office" checked />
										<span class="sc-wordai-support-delivery-title"><?php esc_html_e( 'SOFTCOY Support Office', 'wordai-pro' ); ?></span>
										<small><?php esc_html_e( 'Send the ticket to the SOFTCOY office queue so status updates and replies can sync back into this support page.', 'wordai-pro' ); ?></small>
									</label>
								</div>
								<p class="description"><?php esc_html_e( 'Every ticket is saved locally in WordAI first. Select email, office, or both before sending.', 'wordai-pro' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="wordaiSupportMessage"><?php esc_html_e( 'Issue Details', 'wordai-pro' ); ?></label></th>
							<td><textarea id="wordaiSupportMessage" name="message" rows="8" class="large-text" placeholder="<?php esc_attr_e( 'Describe the problem, where it happens, and what you already tried.', 'wordai-pro' ); ?>"></textarea></td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Diagnostics Consent', 'wordai-pro' ); ?></th>
							<td>
								<label class="sc-wordai-support-diagnostics-consent-label">
									<input type="checkbox" id="wordaiSupportIncludeDiagnostics" name="include_diagnostics" value="yes" checked />
									<span><?php esc_html_e( 'Include recent WordAI diagnostics logs to help the support team identify the problem faster.', 'wordai-pro' ); ?></span>
								</label>
								<p class="description"><?php echo esc_html( $support_prefill_data['diagnostics_note'] ?? '' ); ?></p>
							</td>
						</tr>
					</tbody>
				</table>

				<p class="submit sc-wordai-support-submit-actions">
					<button type="submit" class="button button-primary sc-wordai-support-send-btn">
						<span class="dashicons dashicons-email-alt" aria-hidden="true"></span>
						<?php esc_html_e( 'Send Support Request', 'wordai-pro' ); ?>
					</button>
				</p>
			</form>
		</div>

		<div class="sc-wordai-support-diagnostics-card">
			<h3><span class="dashicons dashicons-chart-area"></span><?php esc_html_e( 'Diagnostics Preview', 'wordai-pro' ); ?></h3>
			<ul class="sc-wordai-support-diagnostics-preview-list">
				<li><strong><?php esc_html_e( 'Recent Plugin Logs:', 'wordai-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['total_logs'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Provider Errors:', 'wordai-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['provider_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Content / Image Errors:', 'wordai-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['content_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Chat Errors:', 'wordai-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['chat_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'AI Agent Failures:', 'wordai-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['agent_failures'] ?? 0 ); ?></li>
			</ul>
			<div class="sc-wordai-support-diagnostics-privacy-note">
				<span class="dashicons dashicons-lock"></span>
				<span><?php esc_html_e( 'Diagnostics are limited to WordAI environment, recent plugin failures, and AI Agent failures. Sensitive keys, tokens, and full prompts are redacted.', 'wordai-pro' ); ?></span>
			</div>
		</div>
	</div>

	<div class="sc-wordai-support-history-card">
		<h3><span class="dashicons dashicons-list-view"></span><?php esc_html_e( 'Recent Support Tickets', 'wordai-pro' ); ?></h3>
		<p class="description"><?php esc_html_e( 'This local history is the user-side source of truth. Office ticket statuses and the latest SOFTCOY reply summary sync into this table whenever the page loads.', 'wordai-pro' ); ?></p>
		<?php if ( empty( $recent_requests ) ) : ?>
			<p class="description"><?php esc_html_e( 'No support tickets have been sent from this site yet.', 'wordai-pro' ); ?></p>
		<?php else : ?>
			<div class="sc-wordai-support-history-table-wrap">
				<table class="widefat striped sc-wordai-support-history-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Ticket', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Issue', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Channels', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Overall Status', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Channel Status', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Office Update', 'wordai-pro' ); ?></th>
							<th><?php esc_html_e( 'Updated', 'wordai-pro' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $recent_requests as $request_row ) : ?>
							<?php
							$channels = ! empty( $request_row['delivery_channels'] ) ? array_map( 'ucfirst', (array) $request_row['delivery_channels'] ) : array( 'Email' );
							$email_status = ! empty( $request_row['delivery_results']['email']['status'] ) ? ucfirst( str_replace( '_', ' ', $request_row['delivery_results']['email']['status'] ) ) : '—';
							$office_status = ! empty( $request_row['delivery_results']['office']['status'] ) ? ucfirst( str_replace( '_', ' ', $request_row['delivery_results']['office']['status'] ) ) : '—';
							$office_update = ! empty( $request_row['delivery_results']['office']['message'] ) ? $request_row['delivery_results']['office']['message'] : __( 'Awaiting office update.', 'wordai-pro' );
							$office_data = ! empty( $request_row['delivery_results']['office'] ) && is_array( $request_row['delivery_results']['office'] ) ? $request_row['delivery_results']['office'] : array();
							$office_status_key = ! empty( $request_row['delivery_results']['office']['status'] ) ? sanitize_key( $request_row['delivery_results']['office']['status'] ) : sanitize_key( (string) ( $request_row['overall_status'] ?? 'received' ) );
							$badge = $support_status_badge( $office_status_key, $office_data );
							$ticket_payload = array(
								'ticket_uuid'          => $request_row['ticket_uuid'] ?? '',
								'sender_email'         => $request_row['sender_email'] ?? '',
								'initial_message'      => $request_row['message'] ?? '',
								'initial_author_name'  => __( 'Plugin User', 'wordai-pro' ),
								'initial_created_at'   => $request_row['created_at'] ?? '',
								'issue_type'           => ucfirst( str_replace( '_', ' ', (string) ( $request_row['issue_type'] ?? 'general' ) ) ),
								'channels'             => $channels,
								'overall_status'       => ucfirst( str_replace( '_', ' ', (string) ( $request_row['overall_status'] ?? 'received' ) ) ),
								'email_status'         => $email_status,
								'office_status'        => $office_status,
								'office_status_key'    => $office_status_key,
								'office_status_label'  => $office_data['status_label'] ?? $office_status,
								'status_badge_class'   => $badge[0],
								'status_badge_label'   => $badge[1],
								'office_ticket_id'     => $request_row['office_ticket_id'] ?? '',
								'office_update'        => $office_update,
								'created_at'           => $request_row['created_at'] ?? '',
								'updated_at'           => $request_row['updated_at'] ?? '',
								'office_last_synced_at'=> $request_row['office_last_synced_at'] ?? '',
								'resolved_at'          => $office_data['resolved_at'] ?? '',
								'timings'              => ! empty( $office_data['timings'] ) && is_array( $office_data['timings'] ) ? $office_data['timings'] : array(),
								'replies'              => ! empty( $office_data['replies'] ) && is_array( $office_data['replies'] ) ? $office_data['replies'] : array(),
							);
							?>
							<tr>
								<td>
									<button type="button" class="button-link sc-wordai-support-ticket-trigger" data-ticket="<?php echo esc_attr( base64_encode( wp_json_encode( $ticket_payload ) ) ); ?>">
										<strong><?php echo esc_html( $request_row['ticket_uuid'] ?? '' ); ?></strong>
									</button>
								</td>
								<td><?php echo esc_html( ucfirst( str_replace( '_', ' ', (string) ( $request_row['issue_type'] ?? 'general' ) ) ) ); ?></td>
								<td><?php echo esc_html( implode( ', ', $channels ) ); ?></td>
								<td>
									<span class="sc-wordai-support-status-badge <?php echo esc_attr( $badge[0] ); ?>"><?php echo esc_html( $badge[1] ); ?></span>
								</td>
								<td>
									<span class="sc-wordai-support-channel-stack">
										<span><?php echo esc_html( sprintf( __( 'Email: %s', 'wordai-pro' ), $email_status ) ); ?></span>
										<span><?php echo esc_html( sprintf( __( 'Office: %s', 'wordai-pro' ), $office_status ) ); ?></span>
									</span>
								</td>
								<td><?php echo esc_html( $office_update ); ?></td>
								<td><?php echo esc_html( $request_row['updated_at'] ?? $request_row['created_at'] ?? '' ); ?></td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			</div>
		<?php endif; ?>
	</div>

	<div id="wordaiSupportTicketModal" class="sc-wordai-support-modal" hidden>
		<div class="sc-wordai-support-modal-backdrop"></div>
		<div class="sc-wordai-support-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="wordaiSupportTicketModalTitle">
			<div class="sc-wordai-support-modal-header">
				<div>
					<h3 id="wordaiSupportTicketModalTitle"><?php esc_html_e( 'Support ticket', 'wordai-pro' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Review the latest SOFTCOY office status and reply thread for this ticket.', 'wordai-pro' ); ?></p>
				</div>
				<button type="button" class="button-link sc-wordai-support-modal-close"><?php esc_html_e( 'Close', 'wordai-pro' ); ?></button>
			</div>
			<div class="sc-wordai-support-modal-body"></div>
		</div>
	</div>
	<input type="hidden" id="wordaiSupportTicketReplySenderEmail" value="<?php echo esc_attr( $support_prefill_data['sender_email'] ?? '' ); ?>" />
</div>
