<?php
/**
 * Call detail view.
 *
 * Displays detailed information about a single call including
 * metadata, transcript, and API usage statistics.
 *
 * @link       https://github.com/sitestaffr/sitestaffr-plugin
 * @since      1.0.0
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 */

// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
	die;
}

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Check user capability
if ( ! current_user_can( 'manage_options' ) ) {
	wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'sitestaffr' ) );
}

// Verify nonce for call detail navigation.
if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ), 'sitestaffr_view_call' ) ) {
	wp_die( esc_html__( 'This link has expired. Please navigate from the conversation list.', 'sitestaffr' ) );
}

if ( ! isset( $sitestaffr_admin_view_query_service ) || ! ( $sitestaffr_admin_view_query_service instanceof SiteStaffr_Admin_View_Query_Service ) ) {
	$sitestaffr_admin_view_query_service = new SiteStaffr_Admin_View_Query_Service();
}

// Shared recap formatter (also used by public transcript viewer).
require_once SITESTAFFR_PLUGIN_DIR . 'includes/sitestaffr-format-recap.php';

// Get and validate call_id (nonce verified above).
$call_id = isset( $_GET['call_id'] ) ? absint( wp_unslash( $_GET['call_id'] ) ) : 0;

if ( ! $call_id ) {
	echo '<div class="wrap">';
	echo '<h1>' . esc_html__( 'Conversation Details', 'sitestaffr' ) . '</h1>';
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Invalid call ID.', 'sitestaffr' ) . '</p></div>';
	echo '<p><a href="' . esc_url( admin_url( 'admin.php?page=sitestaffr' ) ) . '" class="button button-primary">' . esc_html__( 'Back to Conversations', 'sitestaffr' ) . '</a></p>';
	echo '</div>';
	return;
}

// Load call data
$call = SiteStaffr_Call_Manager::get_call_by_id( $call_id );

if ( ! $call ) {
	echo '<div class="wrap">';
	echo '<h1>' . esc_html__( 'Conversation Details', 'sitestaffr' ) . '</h1>';
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Conversation not found.', 'sitestaffr' ) . '</p></div>';
	echo '<p><a href="' . esc_url( admin_url( 'admin.php?page=sitestaffr' ) ) . '" class="button button-primary">' . esc_html__( 'Back to Conversations', 'sitestaffr' ) . '</a></p>';
	echo '</div>';
	return;
}

// Block access to trashed conversations — redirect to list with message
if ( ! empty( $call->deleted_at ) ) {
	wp_safe_redirect( add_query_arg( 'message', 'trashed', wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=trash' ), 'sitestaffr_view' ) ) );
	exit;
}

// Mark call as read when detail page is viewed
if ( ! $call->is_read ) {
	SiteStaffr_Call_Manager::mark_as_read( array( $call_id ) );
	$call->is_read = 1;
}

// Load transcript data
$transcripts = $sitestaffr_admin_view_query_service->get_call_transcripts( $call_id );

// Detect if this call used fallback voicemail mode
$is_fallback_voicemail = false;
if ( ! empty( $transcripts ) ) {
	foreach ( $transcripts as $transcript ) {
		if ( $transcript->speaker === 'assistant' && stripos( $transcript->message_text, 'technical difficulties' ) !== false ) {
			$is_fallback_voicemail = true;
			break;
		}
	}
}

$visitor_ip = isset( $call->visitor_ip ) ? sanitize_text_field( $call->visitor_ip ) : '';
$can_ban_ip = ! empty( $visitor_ip ) && filter_var( $visitor_ip, FILTER_VALIDATE_IP );
$is_ip_banned = false;
if ( $can_ban_ip && class_exists( 'SiteStaffr_Ban_Manager' ) ) {
	$is_ip_banned = SiteStaffr_Ban_Manager::is_banned( 'ip', $visitor_ip );
}

// Format date/time in Eastern Time (America/New_York)
$eastern_tz = new DateTimeZone( 'America/New_York' );
$formatted_date = '';
if ( $call->started_at && $call->started_at > 0 ) {
	// started_at is BIGINT (Unix timestamp in milliseconds for WebRTC, seconds for phone)
	$ts = $call->started_at;
	if ( $ts > 9999999999 ) {
		$ts = floor( $ts / 1000 );
	}
	$dt = new DateTime( '@' . $ts );
	$dt->setTimezone( $eastern_tz );
	$formatted_date = $dt->format( 'F j, Y g:i a' );
} elseif ( $call->created_at ) {
	$dt = new DateTime( $call->created_at, new DateTimeZone( 'UTC' ) );
	$dt->setTimezone( $eastern_tz );
	$formatted_date = $dt->format( 'F j, Y g:i a' );
}

// Determine channel label
$service_type_key = isset( $call->service_type ) ? sanitize_key( $call->service_type ) : '';
$channel_labels = array(
	'webrtc_button' => __( 'Button', 'sitestaffr' ),
	'webrtc_widget' => __( 'Widget', 'sitestaffr' ),
	'chat_button'   => __( 'Chat Button', 'sitestaffr' ),
	'chat_widget'   => __( 'Chat Widget', 'sitestaffr' ),
);
$channel_label = isset( $channel_labels[ $service_type_key ] ) ? $channel_labels[ $service_type_key ] : __( 'Widget', 'sitestaffr' );

// Format duration
$formatted_duration = __( 'N/A', 'sitestaffr' );
if ( $call->call_duration > 0 ) {
	$minutes = floor( $call->call_duration / 60 );
	$seconds = $call->call_duration % 60;
	$formatted_duration = sprintf( '%d:%02d', $minutes, $seconds );
}

?>

<div class="wrap sitestaffr-call-detail">
	<?php
	$sitestaffr_page_title = __( 'Conversation Details', 'sitestaffr' );
	include SITESTAFFR_PLUGIN_DIR . 'admin/partials/sitestaffr-header.php';
	?>
	<div id="sitestaffr-call-detail-notice-anchor"></div>

	<div class="pe-ai-training">
		<div class="pe-knowledge-layout">
			<div class="pe-main-content">
				<div class="postbox sitestaffr-detail-card sitestaffr-summary-card">
					<div class="postbox-header sitestaffr-detail-card-header">
						<h2 class="hndle"><span class="dashicons dashicons-feedback"></span><?php echo esc_html__( 'Conversation Recap', 'sitestaffr' ); ?></h2>
						<div class="sitestaffr-summary-meta">
							<span class="dashicons dashicons-calendar-alt sitestaffr-summary-meta-icon"></span>
							<span class="sitestaffr-summary-meta-value"><?php echo esc_html( $formatted_date ); ?></span>
						</div>
					</div>
						<div class="inside">
							<?php if ( ! empty( $call->ai_summary ) ) : ?>
								<div class="sitestaffr-summary-block is-summary">
									<div class="sitestaffr-summary-body">
										<?php echo wp_kses_post( sitestaffr_format_recap_html( $call->ai_summary ) ); ?>
									</div>
								</div>
							<?php endif; ?>

							<?php if ( empty( $call->ai_summary ) ) : ?>
								<p class="sitestaffr-empty-copy">
									<?php echo esc_html__( 'Conversation recap not yet generated.', 'sitestaffr' ); ?>
								</p>
						<?php endif; ?>
					</div>
				</div>

					<div class="postbox sitestaffr-detail-card sitestaffr-transcript-card">
					<div class="postbox-header sitestaffr-detail-card-header">
						<h2 class="hndle"><span class="dashicons dashicons-testimonial"></span><?php echo esc_html__( 'Conversation Transcript', 'sitestaffr' ); ?></h2>
						<button type="button" class="sitestaffr-mobile-toggle" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle transcript', 'sitestaffr' ); ?>">
							<span class="dashicons dashicons-arrow-down-alt2"></span>
						</button>
						<div class="sitestaffr-transcript-meta">
							<span class="dashicons dashicons-clock sitestaffr-transcript-meta-icon"></span>
							<span class="sitestaffr-transcript-meta-value"><?php echo esc_html( $formatted_duration ); ?></span>
						</div>
					</div>
					<div class="inside">
						<?php if ( empty( $transcripts ) ) : ?>
							<p class="sitestaffr-empty-copy"><?php echo esc_html__( 'No transcript available for this conversation.', 'sitestaffr' ); ?></p>
						<?php else : ?>
							<div class="sitestaffr-transcript">
								<?php foreach ( $transcripts as $transcript ) : ?>
									<?php
									$is_visitor = ( $transcript->speaker === 'caller' );
									$speaker_label = $is_visitor ? __( 'Visitor', 'sitestaffr' ) : __( 'AI', 'sitestaffr' );
									$msg_dt = new DateTime( $transcript->timestamp, new DateTimeZone( 'UTC' ) );
									$msg_dt->setTimezone( $eastern_tz );
									$timestamp = $msg_dt->format( 'g:i:s a' );
									?>
									<div class="sitestaffr-transcript-item <?php echo $is_visitor ? 'is-visitor' : 'is-ai'; ?>">
										<div class="sitestaffr-transcript-avatar">
											<span class="dashicons <?php echo $is_visitor ? 'dashicons-admin-users' : 'dashicons-format-status'; ?>"></span>
										</div>
										<div class="sitestaffr-transcript-bubble">
											<div class="sitestaffr-transcript-item-head">
												<strong class="sitestaffr-transcript-speaker"><?php echo esc_html( $speaker_label ); ?></strong>
												<span class="sitestaffr-transcript-time"><?php echo esc_html( $timestamp ); ?></span>
												<?php if ( $is_visitor && $transcript->confidence_score ) : ?>
													<span class="sitestaffr-transcript-confidence">
t										<?php // translators: %d: confidence percentage. ?>
														<?php echo sprintf( esc_html__( 'Confidence: %d%%', 'sitestaffr' ), intval( $transcript->confidence_score * 100 ) ); ?>
													</span>
												<?php endif; ?>
											</div>
											<div class="sitestaffr-transcript-item-body">
												<?php echo esc_html( stripslashes( $transcript->message_text ) ); ?>
											</div>
										</div>
									</div>
								<?php endforeach; ?>
							</div>
						<?php endif; ?>
					</div>
				</div>

			</div><!-- .pe-main-content -->

			<div class="pe-knowledge-sidebar">
				<div class="pe-business-info-card pe-session-details-card">
					<div class="pe-source-header">
						<span class="dashicons dashicons-info-outline"></span>
						<h3><?php esc_html_e( 'Session Details', 'sitestaffr' ); ?></h3>
						<button type="button" class="sitestaffr-mobile-toggle" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle session details', 'sitestaffr' ); ?>">
							<span class="dashicons dashicons-arrow-down-alt2"></span>
						</button>
					</div>
					<div class="pe-source-content">
						<div class="pe-info-field pe-info-field--session-id">
							<label><?php echo esc_html__( 'Session ID', 'sitestaffr' ); ?></label>
							<p>
								<?php if ( ! empty( $call->session_id ) ) : ?>
									<code class="sitestaffr-call-sid-code" title="<?php esc_attr_e( 'Click to copy', 'sitestaffr' ); ?>"><?php echo esc_html( $call->session_id ); ?></code>
								<?php else : ?>
									<span class="sitestaffr-empty-value"><?php echo esc_html__( 'Not available', 'sitestaffr' ); ?></span>
								<?php endif; ?>
							</p>
						</div>

						<div class="pe-info-field pe-info-field--visitor-ip">
							<label><?php echo esc_html__( 'Visitor IP Address', 'sitestaffr' ); ?></label>
							<?php if ( $can_ban_ip ) : ?>
								<p><?php echo esc_html( $visitor_ip ); ?></p>
								<?php if ( $is_ip_banned ) : ?>
									<p class="sitestaffr-ip-action-row">
										<span class="sitestaffr-status-badge sitestaffr-status-new"><?php echo esc_html__( 'Banned', 'sitestaffr' ); ?></span>
									</p>
								<?php else : ?>
									<p class="sitestaffr-ip-action-row">
										<button
											type="button"
											class="sitestaffr-detail-action-btn sitestaffr-detail-action-btn--danger sitestaffr-ban-ip-btn"
											data-identifier="<?php echo esc_attr( $visitor_ip ); ?>"
											data-call-id="<?php echo esc_attr( $call_id ); ?>"
										>
											<?php echo esc_html__( 'Ban IP Address', 'sitestaffr' ); ?>
										</button>
									</p>
								<?php endif; ?>
							<?php else : ?>
								<p><span class="sitestaffr-empty-value"><?php echo esc_html__( 'Not captured for this conversation', 'sitestaffr' ); ?></span></p>
							<?php endif; ?>
						</div>

						<div class="pe-info-field pe-info-field--channel">
							<label><?php echo esc_html__( 'Channel', 'sitestaffr' ); ?></label>
							<p>
								<?php echo esc_html( $channel_label ); ?>
							</p>
						</div>

						<?php if ( $call->recording_url ) : ?>
							<div class="pe-info-field">
								<label><?php echo esc_html__( 'Voicemail Recording', 'sitestaffr' ); ?></label>
								<audio controls class="sitestaffr-recording-player">
									<source src="<?php echo esc_url( $call->recording_url ); ?>" type="audio/mpeg">
									<?php echo esc_html__( 'Your browser does not support the audio element.', 'sitestaffr' ); ?>
								</audio>
								<a href="<?php echo esc_url( $call->recording_url ); ?>" download class="button button-small sitestaffr-recording-download">
									<span class="dashicons dashicons-download"></span>
									<?php echo esc_html__( 'Download Recording', 'sitestaffr' ); ?>
								</a>
								<?php if ( $is_fallback_voicemail ) : ?>
									<p class="sitestaffr-meta-note">
										<?php echo esc_html__( 'This voicemail was left during a system outage. AI service has been restored.', 'sitestaffr' ); ?>
									</p>
								<?php endif; ?>
							</div>
						<?php elseif ( $is_fallback_voicemail ) : ?>
							<div class="pe-info-field">
								<label><?php echo esc_html__( 'Voicemail Recording', 'sitestaffr' ); ?></label>
								<div class="notice notice-warning inline sitestaffr-inline-warning">
									<p>
										<span class="dashicons dashicons-warning"></span>
										<strong><?php echo esc_html__( 'Recording Not Available', 'sitestaffr' ); ?></strong>
									</p>
									<p>
										<?php echo esc_html__( 'A voicemail was expected for this conversation, but the recording is not accessible. This may indicate a technical issue with the recording callback. Check error logs for details.', 'sitestaffr' ); ?>
									</p>
									<p class="sitestaffr-inline-warning-sid">
										<strong><?php echo esc_html__( 'Session ID:', 'sitestaffr' ); ?></strong>
										<code><?php echo esc_html( $call->session_id ); ?></code>
									</p>
								</div>
							</div>
						<?php endif; ?>

						<?php if ( ! empty( $call->ai_model ) ) : ?>
							<div class="pe-info-field">
								<label><?php echo esc_html__( 'AI Model', 'sitestaffr' ); ?></label>
								<p><code class="sitestaffr-inline-code"><?php echo esc_html( $call->ai_model ); ?></code></p>
							</div>
						<?php endif; ?>
					</div>
				</div>
				<div class="pe-business-info-card pe-quick-actions-card">
					<div class="pe-source-header">
						<span class="dashicons dashicons-admin-tools"></span>
						<h3><?php esc_html_e( 'Quick Actions', 'sitestaffr' ); ?></h3>
					</div>
					<div class="pe-source-content">
						<div class="pe-quick-action">
							<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=all' ), 'sitestaffr_view' ) ); ?>" class="pe-action-link pe-action-back">
								<span class="dashicons dashicons-arrow-left-alt"></span>
								<?php esc_html_e( 'All Conversations', 'sitestaffr' ); ?>
							</a>
						</div>
						<div class="pe-quick-action">
							<button type="button" class="pe-action-link pe-action-unread" data-call-id="<?php echo esc_attr( $call_id ); ?>">
								<span class="dashicons dashicons-marker"></span>
								<?php esc_html_e( 'Mark as Unread', 'sitestaffr' ); ?>
							</button>
						</div>
						<div class="pe-quick-action">
							<button type="button" class="pe-action-link pe-action-delete" data-call-id="<?php echo esc_attr( $call_id ); ?>">
								<span class="dashicons dashicons-trash"></span>
								<?php esc_html_e( 'Delete Conversation', 'sitestaffr' ); ?>
							</button>
						</div>
						<div class="pe-quick-action">
							<button type="button" class="pe-action-link pe-action-report" data-call-id="<?php echo esc_attr( $call_id ); ?>">
								<span class="dashicons dashicons-flag"></span>
								<?php esc_html_e( 'Report Issue', 'sitestaffr' ); ?>
							</button>
						</div>
					</div>
				</div>
			</div><!-- .pe-knowledge-sidebar -->
		</div><!-- .pe-knowledge-layout -->
	</div><!-- .pe-ai-training -->

</div><!-- .wrap -->

<!-- Report Issue Modal -->
<div class="sitestaffr-modal-overlay" id="sitestaffr-report-issue-modal" role="dialog" aria-modal="true" aria-labelledby="sitestaffr-report-issue-title" aria-hidden="true" style="display:none;">
	<div class="sitestaffr-modal" role="document">
		<div class="sitestaffr-modal-header">
			<h2 id="sitestaffr-report-issue-title"><?php esc_html_e( 'Report Issue', 'sitestaffr' ); ?></h2>
			<button type="button" class="sitestaffr-modal-close" aria-label="<?php esc_attr_e( 'Close', 'sitestaffr' ); ?>">
				<span class="dashicons dashicons-no-alt"></span>
			</button>
		</div>
		<div class="sitestaffr-modal-body">
			<div class="sitestaffr-report-issue-error" style="display:none;"></div>
			<div class="sitestaffr-form-field">
				<label for="sitestaffr-report-issue-type"><?php esc_html_e( 'Issue Type', 'sitestaffr' ); ?></label>
				<select id="sitestaffr-report-issue-type">
					<option value=""><?php esc_html_e( 'Select an issue type...', 'sitestaffr' ); ?></option>
					<option value="incorrect_information"><?php esc_html_e( 'Incorrect information', 'sitestaffr' ); ?></option>
					<option value="inappropriate_response"><?php esc_html_e( 'Inappropriate response', 'sitestaffr' ); ?></option>
					<option value="cut_off_early"><?php esc_html_e( 'Cut off early', 'sitestaffr' ); ?></option>
					<option value="lost_context"><?php esc_html_e( 'Lost context', 'sitestaffr' ); ?></option>
					<option value="other"><?php esc_html_e( 'Other', 'sitestaffr' ); ?></option>
				</select>
			</div>
			<div class="sitestaffr-form-field">
				<label for="sitestaffr-report-issue-note"><?php esc_html_e( 'Note (optional)', 'sitestaffr' ); ?></label>
				<textarea id="sitestaffr-report-issue-note" rows="3" maxlength="1000" placeholder="<?php esc_attr_e( 'Describe what went wrong...', 'sitestaffr' ); ?>"></textarea>
			</div>
		</div>
		<div class="sitestaffr-modal-footer">
			<button type="button" class="button sitestaffr-modal-cancel"><?php esc_html_e( 'Cancel', 'sitestaffr' ); ?></button>
			<button type="button" class="button button-primary sitestaffr-report-issue-submit"><?php esc_html_e( 'Submit Report', 'sitestaffr' ); ?></button>
		</div>
	</div>
</div>

<!-- Call detail JS enqueued via class-sitestaffr-admin.php (sitestaffr-call-detail.js) -->
<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
