<?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 sitestaffr-wrap">';
	echo '<h1>' . esc_html__( 'Conversation Details', 'sitestaffr' ) . '</h1>';
	echo '<div class="notice notice-error"><p>' . esc_html__( 'Invalid conversation 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 sitestaffr-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' );
}

// Channel label — shared taxonomy (same vocabulary as the list's Channel column).
$channel_label = SiteStaffr_Call_Manager::get_channel_label( isset( $call->service_type ) ? (string) $call->service_type : '' );
if ( '' === $channel_label ) {
	$channel_label = __( 'Voice · Widget', 'sitestaffr' ); // Legacy rows predate service_type detail.
}

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

// Captured lead data (structured fields are the source of truth).
$lead_is_captured = SiteStaffr_Leads::is_captured( $call );
$lead_fields = array(
	'name'  => isset( $call->lead_name ) ? trim( (string) $call->lead_name ) : '',
	'phone' => isset( $call->lead_phone ) ? trim( (string) $call->lead_phone ) : '',
	'email' => isset( $call->lead_email ) ? trim( (string) $call->lead_email ) : '',
);
$lead_interest = isset( $call->lead_interest ) ? trim( (string) $call->lead_interest ) : '';

// Conversation source page (blank for rows saved before the field existed).
$source_page_url   = isset( $call->source_page_url ) ? trim( (string) $call->source_page_url ) : '';
$source_page_title = isset( $call->source_page_title ) ? trim( (string) $call->source_page_title ) : '';

// Prev/next navigation, scoped to the originating tab (ctx=leads keeps the
// walk inside qualified leads). Read-only routing param.
$detail_ctx = isset( $_GET['ctx'] ) ? sanitize_key( wp_unslash( $_GET['ctx'] ) ) : 'all'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only navigation scope; page nonce verified above.
$detail_ctx = ( 'leads' === $detail_ctx ) ? 'leads' : 'all';
$prev_call_id = $sitestaffr_admin_view_query_service->get_adjacent_call_id( $call, 'prev', 'leads' === $detail_ctx );
$next_call_id = $sitestaffr_admin_view_query_service->get_adjacent_call_id( $call, 'next', 'leads' === $detail_ctx );

/**
 * Build a nonce-carrying detail URL preserving the navigation scope.
 *
 * @param int    $target_id Conversation id.
 * @param string $ctx       Navigation scope (all|leads).
 * @return string
 */
function sitestaffr_call_detail_url( $target_id, $ctx ) {
	return wp_nonce_url(
		add_query_arg(
			array(
				'page'    => 'sitestaffr',
				'action'  => 'view',
				'call_id' => $target_id,
				'ctx'     => $ctx,
			),
			admin_url( 'admin.php' )
		),
		'sitestaffr_view_call'
	);
}

$detail_back_url = 'leads' === $detail_ctx
	? wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=leads' ), 'sitestaffr_view' )
	: wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=all' ), 'sitestaffr_view' );

?>

<div class="wrap sitestaffr-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>

	<!-- Prev/next navigation within the originating tab -->
	<div class="sitestaffr-detail-nav">
		<a href="<?php echo esc_url( $detail_back_url ); ?>" class="sitestaffr-detail-nav-back">
			<span class="dashicons dashicons-arrow-left-alt" aria-hidden="true"></span>
			<?php echo 'leads' === $detail_ctx ? esc_html__( 'Qualified Leads', 'sitestaffr' ) : esc_html__( 'All Conversations', 'sitestaffr' ); ?>
		</a>
		<div class="sitestaffr-detail-nav-arrows">
			<?php if ( $next_call_id ) : ?>
				<a href="<?php echo esc_url( sitestaffr_call_detail_url( $next_call_id, $detail_ctx ) ); ?>" class="button sitestaffr-detail-nav-btn">
					<span class="dashicons dashicons-arrow-left-alt2" aria-hidden="true"></span>
					<?php esc_html_e( 'Newer', 'sitestaffr' ); ?>
				</a>
			<?php else : ?>
				<span class="button sitestaffr-detail-nav-btn" aria-disabled="true" aria-hidden="true"><span class="dashicons dashicons-arrow-left-alt2"></span><?php esc_html_e( 'Newer', 'sitestaffr' ); ?></span>
			<?php endif; ?>
			<?php if ( $prev_call_id ) : ?>
				<a href="<?php echo esc_url( sitestaffr_call_detail_url( $prev_call_id, $detail_ctx ) ); ?>" class="button sitestaffr-detail-nav-btn">
					<?php esc_html_e( 'Older', 'sitestaffr' ); ?>
					<span class="dashicons dashicons-arrow-right-alt2" aria-hidden="true"></span>
				</a>
			<?php else : ?>
				<span class="button sitestaffr-detail-nav-btn" aria-disabled="true" aria-hidden="true"><?php esc_html_e( 'Older', 'sitestaffr' ); ?><span class="dashicons dashicons-arrow-right-alt2"></span></span>
			<?php endif; ?>
		</div>
	</div>

	<div class="sitestaffr-detail">
		<div class="sitestaffr-detail-layout">
			<div class="sitestaffr-detail-main">
				<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">
							<?php if ( ! empty( $call->ai_summary ) ) : ?>
								<button type="button" class="button button-small sitestaffr-copy-recap-btn" title="<?php esc_attr_e( 'Copy the recap as text', 'sitestaffr' ); ?>">
									<span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
									<?php esc_html_e( 'Copy Recap', 'sitestaffr' ); ?>
								</button>
							<?php endif; ?>
							<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">
							<?php if ( ! empty( $transcripts ) ) : ?>
								<?php if ( count( $transcripts ) > 12 ) : ?>
									<button type="button" class="button button-small sitestaffr-jump-latest-btn" title="<?php esc_attr_e( 'Jump to the latest message', 'sitestaffr' ); ?>">
										<span class="dashicons dashicons-arrow-down-alt" aria-hidden="true"></span>
										<?php esc_html_e( 'Latest', 'sitestaffr' ); ?>
									</button>
								<?php endif; ?>
							<?php endif; ?>
							<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">
										<?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 ) ); ?>
												<?php
												if ( ! $is_visitor && ! empty( $transcript->source_chunks ) ) {
													echo wp_kses_post( sitestaffr_render_source_chunks( $transcript->source_chunks ) );
												}
												?>
											</div>
										</div>
									</div>
								<?php endforeach; ?>
								<?php
								// Chat-ended indicator: allowlisted values only; legacy/ambiguous rows render nothing.
								$ended_by_labels = array(
									'ai_ended'     => __( 'AI wrapped up', 'sitestaffr' ),
									'visitor_left' => __( 'Visitor left', 'sitestaffr' ),
									'timed_out'    => __( 'Timed out (inactivity)', 'sitestaffr' ),
									'link_clicked' => __( 'Visitor clicked a link', 'sitestaffr' ),
								);
								$call_ended_by = isset( $call->ended_by ) ? $call->ended_by : '';
								if ( isset( $ended_by_labels[ $call_ended_by ] ) ) :
									?>
									<p class="sitestaffr-transcript-ended-by">
										<?php
										echo esc_html( sprintf(
											/* translators: %s: how the conversation ended (e.g. "visitor left"). */
											__( '— Conversation ended: %s —', 'sitestaffr' ),
											$ended_by_labels[ $call_ended_by ]
										) );
										?>
									</p>
								<?php endif; ?>
							</div>
						<?php endif; ?>
					</div>
				</div>

			</div><!-- .sitestaffr-detail-main -->

			<div class="sitestaffr-detail-sidebar">

				<!-- Captured Lead — the reason the owner opened this page comes first -->
				<div class="sitestaffr-detail-side-card sitestaffr-lead-card <?php echo esc_attr( $lead_is_captured ? 'has-lead' : 'no-lead' ); ?>">
					<div class="sitestaffr-detail-side-header">
						<span class="dashicons dashicons-id-alt"></span>
						<h3><?php esc_html_e( 'Captured Lead', 'sitestaffr' ); ?></h3>
					</div>
					<div class="sitestaffr-detail-side-content">
						<?php if ( $lead_is_captured ) : ?>
							<?php
							$lead_field_labels = array(
								'name'  => __( 'Name', 'sitestaffr' ),
								'phone' => __( 'Phone', 'sitestaffr' ),
								'email' => __( 'Email', 'sitestaffr' ),
							);
							foreach ( $lead_field_labels as $lead_key => $lead_label ) :
								if ( '' === $lead_fields[ $lead_key ] ) {
									continue;
								}
								?>
								<div class="sitestaffr-info-field">
									<label><?php echo esc_html( $lead_label ); ?></label>
									<p>
										<button type="button" class="sitestaffr-lead-copy" data-copy="<?php echo esc_attr( $lead_fields[ $lead_key ] ); ?>" title="<?php esc_attr_e( 'Click to copy', 'sitestaffr' ); ?>">
											<?php echo esc_html( $lead_fields[ $lead_key ] ); ?>
											<span class="dashicons dashicons-clipboard" aria-hidden="true"></span>
										</button>
									</p>
								</div>
							<?php endforeach; ?>
							<?php if ( '' !== $lead_interest ) : ?>
								<div class="sitestaffr-info-field">
									<label><?php esc_html_e( 'Interested in', 'sitestaffr' ); ?></label>
									<p><?php echo esc_html( $lead_interest ); ?></p>
								</div>
							<?php endif; ?>
							<?php
							$sf_sync   = isset( $call->salesforce_sync ) ? sanitize_key( $call->salesforce_sync ) : '';
							$sf_states = array(
								'synced' => array( __( 'Synced', 'sitestaffr' ) . ' ✓', '#10b981' ),
								'queued' => array( __( 'Queued — will retry', 'sitestaffr' ), '#b26a00' ),
								'failed' => array( __( 'Failed to sync', 'sitestaffr' ), '#b32d2e' ),
							);
							if ( isset( $sf_states[ $sf_sync ] ) ) :
								?>
							<div class="sitestaffr-info-field">
								<label><?php esc_html_e( 'Salesforce', 'sitestaffr' ); ?></label>
								<p><span style="font-weight:600;color:<?php echo esc_attr( $sf_states[ $sf_sync ][1] ); ?>;"><?php echo esc_html( $sf_states[ $sf_sync ][0] ); ?></span></p>
							</div>
							<?php endif; ?>
							<p class="sitestaffr-lead-card-link">
								<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=leads' ), 'sitestaffr_view' ) ); ?>">
									<?php esc_html_e( 'View all Qualified Leads', 'sitestaffr' ); ?> &rarr;
								</a>
							</p>
						<?php else : ?>
							<p class="sitestaffr-empty-value"><?php esc_html_e( 'No contact captured in this conversation.', 'sitestaffr' ); ?></p>
						<?php endif; ?>
					</div>
				</div>

				<div class="sitestaffr-detail-side-card sitestaffr-session-details-card">
					<div class="sitestaffr-detail-side-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="sitestaffr-detail-side-content">
						<div class="sitestaffr-info-field sitestaffr-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="sitestaffr-info-field sitestaffr-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-banned"><?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="sitestaffr-info-field sitestaffr-info-field--channel">
							<label><?php echo esc_html__( 'Channel', 'sitestaffr' ); ?></label>
							<p>
								<?php echo esc_html( $channel_label ); ?>
							</p>
						</div>

						<?php if ( '' !== $source_page_title || '' !== $source_page_url ) : ?>
							<div class="sitestaffr-info-field sitestaffr-info-field--source-page">
								<label><?php echo esc_html__( 'Started on page', 'sitestaffr' ); ?></label>
								<p>
									<?php if ( '' !== $source_page_url ) : ?>
										<a href="<?php echo esc_url( $source_page_url ); ?>" target="_blank" rel="noopener">
											<?php echo esc_html( '' !== $source_page_title ? $source_page_title : $source_page_url ); ?>
										</a>
									<?php else : ?>
										<?php echo esc_html( $source_page_title ); ?>
									<?php endif; ?>
								</p>
							</div>
						<?php endif; ?>

						<?php if ( $call->recording_url ) : ?>
							<div class="sitestaffr-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="sitestaffr-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="sitestaffr-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="sitestaffr-detail-side-card sitestaffr-quick-actions-card">
					<div class="sitestaffr-detail-side-header">
						<span class="dashicons dashicons-admin-tools"></span>
						<h3><?php esc_html_e( 'Quick Actions', 'sitestaffr' ); ?></h3>
					</div>
					<div class="sitestaffr-detail-side-content">
						<div class="sitestaffr-quick-action">
							<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=sitestaffr&view=all' ), 'sitestaffr_view' ) ); ?>" class="sitestaffr-action-link sitestaffr-action-back">
								<span class="dashicons dashicons-arrow-left-alt"></span>
								<?php esc_html_e( 'All Conversations', 'sitestaffr' ); ?>
							</a>
						</div>
						<div class="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-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="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-action-email-conversation" data-sitestaffr-email="conversation" data-id="<?php echo esc_attr( $call_id ); ?>">
								<span class="dashicons dashicons-email-alt"></span>
								<?php esc_html_e( 'Email Conversation', 'sitestaffr' ); ?>
							</button>
						</div>
						<?php
						// The tokenized transcript view IS the branded record: Print / Download
						// prints that page (rendered offscreen), and Copy share link hands the same
						// page to someone without a WordPress login.
						$transcript_share_url = class_exists( 'SiteStaffr_Magic_Link' ) ? SiteStaffr_Magic_Link::generate_transcript_url( $call_id, 14 * DAY_IN_SECONDS ) : '';
						if ( '' !== $transcript_share_url ) :
							?>
						<div class="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-print-page" data-print-url="<?php echo esc_attr( $transcript_share_url ); ?>">
								<span class="dashicons dashicons-printer"></span>
								<?php esc_html_e( 'Print / Download', 'sitestaffr' ); ?>
							</button>
						</div>
						<div class="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-action-share" data-share-url="<?php echo esc_attr( $transcript_share_url ); ?>">
								<span class="dashicons dashicons-share"></span>
								<?php esc_html_e( 'Copy share link', 'sitestaffr' ); ?>
							</button>
						</div>
						<?php endif; ?>
						<div class="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-action-delete" data-call-id="<?php echo esc_attr( $call_id ); ?>">
								<span class="dashicons dashicons-trash"></span>
								<?php esc_html_e( 'Move to Trash', 'sitestaffr' ); ?>
							</button>
						</div>
						<div class="sitestaffr-quick-action">
							<button type="button" class="sitestaffr-action-link sitestaffr-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><!-- .sitestaffr-detail-sidebar -->
		</div><!-- .sitestaffr-detail-layout -->
	</div><!-- .sitestaffr-detail -->

</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 class="sitestaffr-form-field sitestaffr-report-issue-consent">
				<label for="sitestaffr-report-issue-include-link">
					<input type="checkbox" id="sitestaffr-report-issue-include-link" checked="checked" />
					<?php esc_html_e( 'Include a secure link to this conversation so SiteStaffr support can review it (expires in 14 days)', 'sitestaffr' ); ?>
				</label>
			</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 ?>
