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

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

$support_prefill_data = isset( $support_prefill_data ) && is_array( $support_prefill_data ) ? $support_prefill_data : SftcyWordformSupport::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. */
	__( 'WordForm support - %s', 'wordform-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', 'wordform-pro' ) );
	}

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

	if ( 'customer_replied' === $status_key || false !== strpos( $latest_role, 'customer' ) ) {
		return array( 'is-waiting', __( 'Waiting for SOFTCOY', 'wordform-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', 'wordform-pro' ) );
	}

	return array( 'is-open', __( 'Open', 'wordform-pro' ) );
};
?>
<div class="wrap wordform-support-page-wrapper" style="margin: 1%;">
	<div class="wordform-page-header-with-action wordform-support-page-header">
		<div class="wordform-support-page-header-copy">
			<h3><i class="dashicons dashicons-sos dashicon-custom-color"></i>&nbsp;<?php esc_html_e( 'WordForm Support', 'wordform-pro' ); ?></h3>
			<p><?php esc_html_e( 'Send a structured support request with your site and WordForm diagnostics so our team can identify the issue faster.', 'wordform-pro' ); ?></p>
		</div>
	</div>

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

	<div class="wordform-support-layout">
		<div class="wordform-support-form-card">
			<h3><i class="dashicons dashicons-email-alt"></i> <?php esc_html_e( 'Open Support Request', 'wordform-pro' ); ?></h3>
			<p class="description"><?php esc_html_e( 'Most fields are pre-filled so users can send a support request quickly without exposing sensitive business data.', 'wordform-pro' ); ?></p>

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

			<form id="wordformSupportRequestForm" class="wordform-support-request-form">
				<div class="wordform-support-attachment-toolbar">
					<button type="button" class="button wordform-support-attach-btn" id="wordformSupportAttachButton">
						<span class="dashicons dashicons-paperclip" aria-hidden="true"></span>
						<?php esc_html_e( 'Attach', 'wordform-pro' ); ?>
					</button>
					<input type="file" id="wordformSupportAttachments" name="support_attachments[]" accept="image/jpeg,image/png,image/gif,image/webp,application/pdf" multiple hidden />
					<div class="wordform-support-attachment-list" id="wordformSupportAttachmentList" aria-live="polite"></div>
				</div>
				<table class="form-table">
					<tbody>
						<tr>
							<th scope="row"><label for="wordformSupportSenderEmail"><?php esc_html_e( 'Sender Email', 'wordform-pro' ); ?></label></th>
							<td><input type="email" id="wordformSupportSenderEmail" name="sender_email" class="regular-text" value="<?php echo esc_attr( $support_prefill_data['sender_email'] ?? '' ); ?>" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordformSupportSiteUrl"><?php esc_html_e( 'Site URL', 'wordform-pro' ); ?></label></th>
							<td><input type="text" id="wordformSupportSiteUrl" class="regular-text" value="<?php echo esc_attr( $support_prefill_data['site_url'] ?? '' ); ?>" readonly /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordformSupportPluginType"><?php esc_html_e( 'Plugin Type', 'wordform-pro' ); ?></label></th>
							<td><input type="text" id="wordformSupportPluginType" class="regular-text" value="<?php echo esc_attr( strtoupper( $support_prefill_data['plugin_variant'] ?? 'free' ) ); ?>" readonly /></td>
						</tr>
						<tr>
							<th scope="row"><label for="wordformSupportSubject"><?php esc_html_e( 'Subject', 'wordform-pro' ); ?></label></th>
							<td>
								<input type="text" id="wordformSupportSubject" 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.', 'wordform-pro' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="wordformSupportIssueType"><?php esc_html_e( 'Issue Type', 'wordform-pro' ); ?></label></th>
							<td>
								<select id="wordformSupportIssueType" 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', 'wordform-pro' ); ?></th>
							<td>
								<div class="wordform-support-delivery-options">
									<label class="wordform-support-delivery-card is-active">
										<input type="checkbox" name="delivery_channels[]" value="email" checked />
										<span class="wordform-support-delivery-title"><?php esc_html_e( 'Email Support', 'wordform-pro' ); ?></span>
										<small><?php echo esc_html( $support_prefill_data['support_email'] ?? '' ); ?></small>
									</label>
									<label class="wordform-support-delivery-card is-active">
										<input type="checkbox" name="delivery_channels[]" value="office" checked />
										<span class="wordform-support-delivery-title"><?php esc_html_e( 'SOFTCOY Support Office', 'wordform-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.', 'wordform-pro' ); ?></small>
									</label>
								</div>
								<p class="description"><?php esc_html_e( 'Every ticket is saved locally in WordForm first. Select email, office, or both before sending.', 'wordform-pro' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="wordformSupportMessage"><?php esc_html_e( 'Issue Details', 'wordform-pro' ); ?></label></th>
							<td>
								<textarea id="wordformSupportMessage" name="message" rows="8" class="large-text" placeholder="<?php esc_attr_e( 'Describe the problem, where it happens, and what you already tried.', 'wordform-pro' ); ?>"></textarea>
							</td>
						</tr>
						<tr>
							<th scope="row"><?php esc_html_e( 'Diagnostics Consent', 'wordform-pro' ); ?></th>
							<td>
								<label class="wordform-support-diagnostics-consent-label">
									<input type="checkbox" id="wordformSupportIncludeDiagnostics" name="include_diagnostics" value="yes" checked />
									<span><?php esc_html_e( 'Include recent WordForm diagnostics logs to help the WordForm Team identify the problem faster.', 'wordform-pro' ); ?></span>
								</label>
								<p class="description"><?php echo esc_html( $support_prefill_data['diagnostics_note'] ?? '' ); ?></p>
							</td>
						</tr>
					</tbody>
				</table>

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

		<div class="wordform-support-diagnostics-card">
			<h3><i class="dashicons dashicons-chart-area"></i> <?php esc_html_e( 'Diagnostics Preview', 'wordform-pro' ); ?></h3>
			<ul class="wordform-support-diagnostics-preview-list">
				<li><strong><?php esc_html_e( 'Recent Plugin Logs:', 'wordform-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['total_logs'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Payment Errors:', 'wordform-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['payment_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Captcha Errors:', 'wordform-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['captcha_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Upload Errors:', 'wordform-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['upload_errors'] ?? 0 ); ?></li>
				<li><strong><?php esc_html_e( 'Connection Failures:', 'wordform-pro' ); ?></strong> <?php echo esc_html( $diagnostics_preview['connection_failures'] ?? 0 ); ?></li>
			</ul>
			<div class="wordform-support-diagnostics-privacy-note">
				<i class="dashicons dashicons-lock"></i>
				<span><?php esc_html_e( 'Diagnostics are limited to plugin environment and recent WordForm failures. Sensitive keys, card data, and full license values are redacted.', 'wordform-pro' ); ?></span>
			</div>
		</div>
	</div>

	<div class="wordform-support-history-card">
		<h3><i class="dashicons dashicons-list-view"></i> <?php esc_html_e( 'Recent Support Tickets', 'wordform-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.', 'wordform-pro' ); ?></p>
		<?php if ( empty( $recent_requests ) ) : ?>
			<p class="description"><?php esc_html_e( 'No support tickets have been sent from this site yet.', 'wordform-pro' ); ?></p>
		<?php else : ?>
			<div class="wordform-support-history-table-wrap">
				<table class="widefat striped wordform-support-history-table">
					<thead>
						<tr>
							<th><?php esc_html_e( 'Ticket', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Issue', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Channels', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Overall Status', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Channel Status', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Office Update', 'wordform-pro' ); ?></th>
							<th><?php esc_html_e( 'Updated', 'wordform-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.', 'wordform-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', 'wordform-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 wordform-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="wordform-support-status-badge <?php echo esc_attr( $badge[0] ); ?>"><?php echo esc_html( $badge[1] ); ?></span>
								</td>
								<td>
									<span class="wordform-support-channel-stack">
										<span><?php echo esc_html( sprintf( __( 'Email: %s', 'wordform-pro' ), $email_status ) ); ?></span>
										<span><?php echo esc_html( sprintf( __( 'Office: %s', 'wordform-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="wordformSupportTicketModal" class="wordform-support-modal" hidden>
		<div class="wordform-support-modal-backdrop"></div>
		<div class="wordform-support-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="wordformSupportTicketModalTitle">
			<div class="wordform-support-modal-header">
				<div>
					<h3 id="wordformSupportTicketModalTitle"><?php esc_html_e( 'Support ticket', 'wordform-pro' ); ?></h3>
					<p class="description"><?php esc_html_e( 'Review the latest SOFTCOY office status and reply thread for this ticket.', 'wordform-pro' ); ?></p>
				</div>
				<button type="button" class="button-link wordform-support-modal-close"><?php esc_html_e( 'Close', 'wordform-pro' ); ?></button>
			</div>
			<div class="wordform-support-modal-body"></div>
		</div>
	</div>
	<input type="hidden" id="wordformSupportTicketReplySenderEmail" value="<?php echo esc_attr( $support_prefill_data['sender_email'] ?? '' ); ?>" />
</div>
