<?php
/**
 * AI Knowledge — shared hub-level section (embedded by admin-my-agent.php).
 *
 * Lets business owners select pages/posts for AI learning, sync knowledge,
 * and view indexing stats. All agents answer/write from this knowledge.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/views
 * @since      1.7.0
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

$settings = get_option( 'sitestaffr_settings', array() ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template variable scoped to this view file.

// "What your agent knows" — the three live sources, in one place. Owners were
// reading the Business Identity paragraph as everything the AI knows, because
// nothing in the product connected it to the synced pages it also searches.
$sitestaffr_kb_stats = class_exists( 'SiteStaffr_Knowledge_Manager' )
	? SiteStaffr_Knowledge_Manager::get_stats()
	: array( 'total_chunks' => 0, 'total_posts' => 0, 'last_synced' => '' );

$sitestaffr_identity = (string) get_option( 'sitestaffr_business_description', '' );
if ( '' === $sitestaffr_identity && ! empty( $settings['business_context'] ) ) {
	$sitestaffr_identity = (string) $settings['business_context'];
}
$sitestaffr_identity      = trim( wp_strip_all_tags( $sitestaffr_identity ) );
$sitestaffr_has_identity  = ( '' !== $sitestaffr_identity );
$sitestaffr_identity_snip = $sitestaffr_has_identity
	? wp_trim_words( $sitestaffr_identity, 22, '…' )
	: '';

$sitestaffr_manual_count = class_exists( 'SiteStaffr_Knowledge_Manager' ) && method_exists( 'SiteStaffr_Knowledge_Manager', 'count_manual_chunks' )
	? (int) SiteStaffr_Knowledge_Manager::count_manual_chunks()
	: 0;

$sitestaffr_pages    = (int) $sitestaffr_kb_stats['total_posts'];
$sitestaffr_sections = (int) $sitestaffr_kb_stats['total_chunks'];
$sitestaffr_settings_url = admin_url( 'admin.php?page=sitestaffr-settings' );
?>

	<!-- What your agent knows — the map; the editors below and in Settings are the territory -->
	<section class="sitestaffr-knows" aria-labelledby="sitestaffr-knows-title">
		<div class="sitestaffr-knows-head">
			<h2 id="sitestaffr-knows-title">
				<span class="dashicons dashicons-lightbulb" aria-hidden="true"></span>
				<?php esc_html_e( 'What your agent knows', 'sitestaffr' ); ?>
			</h2>
			<p><?php esc_html_e( 'Your agent answers from these sources. All of them are live in every conversation.', 'sitestaffr' ); ?></p>
		</div>

		<ol class="sitestaffr-knows-list">
			<li class="sitestaffr-knows-source<?php echo $sitestaffr_has_identity ? '' : ' is-empty'; ?>">
				<div class="sitestaffr-knows-source-main">
					<h3>
						<?php esc_html_e( 'Business identity', 'sitestaffr' ); ?>
						<span class="sitestaffr-knows-dot" aria-hidden="true"></span>
						<span class="sitestaffr-knows-state">
							<?php echo $sitestaffr_has_identity ? esc_html__( 'Set', 'sitestaffr' ) : esc_html__( 'Not set', 'sitestaffr' ); ?>
						</span>
					</h3>
					<?php if ( $sitestaffr_has_identity ) : ?>
						<p class="sitestaffr-knows-desc"><?php esc_html_e( 'The short summary your agent keeps in mind at all times.', 'sitestaffr' ); ?></p>
						<p class="sitestaffr-knows-snippet">&ldquo;<?php echo esc_html( $sitestaffr_identity_snip ); ?>&rdquo;</p>
					<?php else : ?>
						<p class="sitestaffr-knows-desc"><?php esc_html_e( 'Your agent does not know what your business does yet.', 'sitestaffr' ); ?></p>
					<?php endif; ?>
				</div>
				<a class="button" href="<?php echo esc_url( $sitestaffr_settings_url ); ?>">
					<?php echo $sitestaffr_has_identity ? esc_html__( 'Edit identity', 'sitestaffr' ) : esc_html__( 'Write identity', 'sitestaffr' ); ?>
				</a>
			</li>

			<li class="sitestaffr-knows-source<?php echo $sitestaffr_pages > 0 ? '' : ' is-empty'; ?>">
				<div class="sitestaffr-knows-source-main">
					<h3>
						<?php esc_html_e( 'Your website content', 'sitestaffr' ); ?>
						<span class="sitestaffr-knows-dot" aria-hidden="true"></span>
						<span class="sitestaffr-knows-state">
							<?php
							if ( $sitestaffr_pages > 0 ) {
								echo esc_html( sprintf(
									/* translators: 1: page count, 2: section count. */
									_n( '%1$d page · %2$d sections', '%1$d pages · %2$d sections', $sitestaffr_pages, 'sitestaffr' ),
									$sitestaffr_pages,
									$sitestaffr_sections
								) );
							} else {
								esc_html_e( 'Nothing synced', 'sitestaffr' );
							}
							?>
						</span>
					</h3>
					<?php if ( $sitestaffr_pages > 0 ) : ?>
						<p class="sitestaffr-knows-desc"><?php esc_html_e( 'Searched in full whenever a visitor asks something specific. This is where the details live — services, prices, policies.', 'sitestaffr' ); ?></p>
					<?php else : ?>
						<p class="sitestaffr-knows-desc"><?php esc_html_e( 'Without synced pages your agent can only answer from its identity — it will not know your services, prices or policies.', 'sitestaffr' ); ?></p>
					<?php endif; ?>
				</div>
				<button type="button" class="button" id="sitestaffr-knows-manage"><?php esc_html_e( 'Manage pages', 'sitestaffr' ); ?></button>
			</li>

			<li class="sitestaffr-knows-source<?php echo $sitestaffr_manual_count > 0 ? '' : ' is-optional'; ?>">
				<div class="sitestaffr-knows-source-main">
					<h3>
						<?php esc_html_e( 'Facts you add by hand', 'sitestaffr' ); ?>
						<span class="sitestaffr-knows-dot" aria-hidden="true"></span>
						<span class="sitestaffr-knows-state">
							<?php
							if ( $sitestaffr_manual_count > 0 ) {
								echo esc_html( sprintf(
									/* translators: %d: number of manually added knowledge entries. */
									_n( '%d entry', '%d entries', $sitestaffr_manual_count, 'sitestaffr' ),
									$sitestaffr_manual_count
								) );
							} else {
								esc_html_e( 'Optional', 'sitestaffr' );
							}
							?>
						</span>
					</h3>
					<p class="sitestaffr-knows-desc"><?php esc_html_e( 'Anything that is not on your website — holiday hours, a new promotion, a policy you never published.', 'sitestaffr' ); ?></p>
				</div>
				<button type="button" class="button" id="sitestaffr-knows-add"><?php esc_html_e( 'Add knowledge', 'sitestaffr' ); ?></button>
			</li>
		</ol>

		<details class="sitestaffr-knows-how">
			<summary><?php esc_html_e( 'How your agent answers a question', 'sitestaffr' ); ?></summary>
			<ol>
				<li><?php esc_html_e( 'It reads your business identity, so it always knows who you are.', 'sitestaffr' ); ?></li>
				<li><?php esc_html_e( 'It searches your synced pages and hand-added facts for the specific answer.', 'sitestaffr' ); ?></li>
				<li><?php esc_html_e( 'If neither has it, it says so and offers to take a message — it does not guess.', 'sitestaffr' ); ?></li>
			</ol>
			<p class="description"><?php esc_html_e( 'Your hours, greeting and custom instructions shape how it answers — those live on the Voice & Text Agent tab.', 'sitestaffr' ); ?></p>
		</details>
	</section>

	<!-- First-sync hero (JS shows it while nothing is synced yet) -->
	<div class="sitestaffr-knowledge-hero" id="knowledge-hero" style="display: none;">
		<span class="dashicons dashicons-welcome-learn-more" aria-hidden="true"></span>
		<h3><?php esc_html_e( 'Teach your AI about your business', 'sitestaffr' ); ?></h3>
		<p><?php esc_html_e( 'Pick the pages that describe what you do, then sync them. Your AI answers visitor questions from this content — the more it knows, the better it helps.', 'sitestaffr' ); ?></p>
		<button type="button" class="button button-primary" id="knowledge-hero-cta">
			<?php esc_html_e( 'Choose pages to sync', 'sitestaffr' ); ?>
		</button>
	</div>

	<!-- Knowledge Mode -->
	<div class="sitestaffr-knowledge-mode">
		<h2 class="sitestaffr-knowledge-mode-title"><?php esc_html_e( 'Knowledge Mode', 'sitestaffr' ); ?> <span id="knowledge-mode-status" class="sitestaffr-knowledge-mode-status"></span></h2>
		<p class="description"><?php esc_html_e( 'Choose how your AI uses synced knowledge during conversations.', 'sitestaffr' ); ?></p>
		<?php $knowledge_mode = isset( $settings['knowledge_mode'] ) ? $settings['knowledge_mode'] : 'search'; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
		<fieldset>
			<label class="sitestaffr-knowledge-mode-option">
				<input type="radio" name="sitestaffr_knowledge_mode" value="search" <?php checked( $knowledge_mode, 'search' ); ?>>
				<span><strong><?php esc_html_e( 'Search Mode', 'sitestaffr' ); ?></strong><span class="sitestaffr-mode-reco" id="knowledge-reco-search" hidden><?php esc_html_e( 'Recommended for your site', 'sitestaffr' ); ?></span>
				&mdash; <?php esc_html_e( 'Your AI can search across all synced pages to answer visitor questions. Best for sites with a few content pages.', 'sitestaffr' ); ?></span>
			</label>
			<label class="sitestaffr-knowledge-mode-option">
				<input type="radio" name="sitestaffr_knowledge_mode" value="page_scoped" <?php checked( $knowledge_mode, 'page_scoped' ); ?>>
				<span><strong><?php esc_html_e( 'Page Expert Mode', 'sitestaffr' ); ?></strong><span class="sitestaffr-mode-reco" id="knowledge-reco-page" hidden><?php esc_html_e( 'Recommended for your site', 'sitestaffr' ); ?></span>
				&mdash; <?php esc_html_e( 'Your AI becomes a specialist on each page the visitor is on. Best for sites with many detailed pages (procedures, products, services).', 'sitestaffr' ); ?></span>
			</label>
		</fieldset>
	</div>

	<!-- Stats + most-used knowledge -->
	<div class="sitestaffr-knowledge-overview">
		<div class="sitestaffr-knowledge-stats">
			<div class="sitestaffr-knowledge-stat">
				<span class="sitestaffr-knowledge-stat-value" id="stat-chunks">&mdash;</span>
				<span class="sitestaffr-knowledge-stat-label"><?php esc_html_e( 'Sections Indexed', 'sitestaffr' ); ?></span>
			</div>
			<div class="sitestaffr-knowledge-stat">
				<span class="sitestaffr-knowledge-stat-value" id="stat-posts">&mdash;</span>
				<span class="sitestaffr-knowledge-stat-label"><?php esc_html_e( 'Pages Synced', 'sitestaffr' ); ?></span>
			</div>
			<div class="sitestaffr-knowledge-stat">
				<span class="sitestaffr-knowledge-stat-value" id="stat-last-sync">&mdash;</span>
				<span class="sitestaffr-knowledge-stat-label"><?php esc_html_e( 'Last Sync', 'sitestaffr' ); ?></span>
			</div>
		</div>
		<div class="sitestaffr-knowledge-top-chunks" id="knowledge-top-chunks" style="display: none;">
			<h4><?php esc_html_e( 'Most-used knowledge', 'sitestaffr' ); ?>
				<span class="sitestaffr-tooltip-trigger" tabindex="0" role="button" aria-label="<?php esc_attr_e( 'Help', 'sitestaffr' ); ?>" data-tooltip="<?php esc_attr_e( 'The knowledge sections your AI reaches for most when answering visitors. A high count means visitors keep asking about this topic.', 'sitestaffr' ); ?>">
					<span class="dashicons dashicons-info" aria-hidden="true"></span>
				</span>
			</h4>
			<ol id="knowledge-top-chunks-list"></ol>
		</div>
	</div>

	<!-- Status legend -->
	<div class="sitestaffr-knowledge-legend" aria-hidden="true">
		<span><span class="sitestaffr-sync-dot synced"></span> <?php esc_html_e( 'Synced', 'sitestaffr' ); ?></span>
		<span><span class="sitestaffr-sync-dot stale"></span> <?php esc_html_e( 'Changed since sync', 'sitestaffr' ); ?></span>
		<span><span class="sitestaffr-sync-dot unsynced"></span> <?php esc_html_e( 'Not synced', 'sitestaffr' ); ?></span>
	</div>

	<!-- Changed-since-sync alert (shown when synced pages were edited after their last sync) -->
	<div class="sitestaffr-knowledge-stale-alert" id="knowledge-stale-alert" style="display: none;" role="status">
		<span class="dashicons dashicons-warning" aria-hidden="true"></span>
		<span id="knowledge-stale-text"></span>
		<button type="button" class="button button-secondary" id="resync-changed-btn">
			<?php esc_html_e( 'Re-sync changed pages', 'sitestaffr' ); ?>
		</button>
	</div>

	<!-- Sync Controls -->
	<div class="sitestaffr-knowledge-controls">
		<button type="button" class="button button-primary" id="sync-knowledge-btn" disabled>
			<?php esc_html_e( 'Sync Knowledge', 'sitestaffr' ); ?>
		</button>
		<button type="button" class="button sitestaffr-knowledge-unsync-btn" id="unsync-knowledge-btn" disabled>
			<?php esc_html_e( 'Unsync Selected', 'sitestaffr' ); ?>
		</button>
		<button type="button" class="button sitestaffr-add-manual-knowledge" id="sitestaffr-add-standalone-knowledge">
			<span class="dashicons dashicons-plus-alt2" aria-hidden="true"></span>
			<?php esc_html_e( 'Add Knowledge', 'sitestaffr' ); ?>
		</button>
		<span class="sync-status" id="sync-status"></span>
	</div>

	<!-- Manual Knowledge Form -->
	<div id="sitestaffr-manual-knowledge-form" style="display:none;" class="sitestaffr-manual-knowledge-form">
		<h4><?php esc_html_e( 'Add Manual Knowledge', 'sitestaffr' ); ?></h4>
		<p class="description"><?php esc_html_e( 'Add information that isn\'t on your website but your AI should know.', 'sitestaffr' ); ?></p>
		<label for="sitestaffr-manual-title"><?php esc_html_e( 'Title', 'sitestaffr' ); ?></label>
		<input type="text" id="sitestaffr-manual-title" class="regular-text" placeholder="<?php esc_attr_e( 'e.g., Holiday Hours', 'sitestaffr' ); ?>" />
		<label for="sitestaffr-manual-text"><?php esc_html_e( 'Knowledge', 'sitestaffr' ); ?></label>
		<textarea id="sitestaffr-manual-text" rows="4" class="large-text" placeholder="<?php esc_attr_e( 'e.g., We are closed Dec 24-Jan 1 for the holidays. Normal hours resume Jan 2.', 'sitestaffr' ); ?>"></textarea>
		<div class="sitestaffr-manual-knowledge-actions">
			<button type="button" class="button button-primary" id="sitestaffr-save-manual-knowledge">
				<?php esc_html_e( 'Save', 'sitestaffr' ); ?>
			</button>
			<button type="button" class="button" id="sitestaffr-cancel-manual-knowledge">
				<?php esc_html_e( 'Cancel', 'sitestaffr' ); ?>
			</button>
		</div>
	</div>

	<!-- Progress Bar -->
	<div class="sitestaffr-knowledge-progress" id="sync-progress" style="display: none;">
		<div class="progress-bar">
			<div class="progress-fill" id="progress-fill"></div>
		</div>
		<span class="progress-text" id="progress-text"></span>
	</div>

	<!-- Content filters -->
	<div class="sitestaffr-knowledge-filters" id="knowledge-filters" style="display: none;">
		<input type="search" id="knowledge-filter-text" class="regular-text" placeholder="<?php esc_attr_e( 'Filter by title…', 'sitestaffr' ); ?>" aria-label="<?php esc_attr_e( 'Filter content by title', 'sitestaffr' ); ?>" />
		<select id="knowledge-filter-status" aria-label="<?php esc_attr_e( 'Filter content by sync status', 'sitestaffr' ); ?>">
			<option value=""><?php esc_html_e( 'All statuses', 'sitestaffr' ); ?></option>
			<option value="synced"><?php esc_html_e( 'Synced', 'sitestaffr' ); ?></option>
			<option value="stale"><?php esc_html_e( 'Changed since sync', 'sitestaffr' ); ?></option>
			<option value="unsynced"><?php esc_html_e( 'Not synced', 'sitestaffr' ); ?></option>
		</select>
	</div>

	<!-- Content lists rendered dynamically by admin-knowledge.js -->
	<div id="knowledge-content-sections">
		<div class="sitestaffr-knowledge-skeleton" aria-hidden="true">
			<span class="sitestaffr-skeleton-line" style="width: 42%;"></span>
			<span class="sitestaffr-skeleton-line" style="width: 68%;"></span>
			<span class="sitestaffr-skeleton-line" style="width: 55%;"></span>
		</div>
		<span class="screen-reader-text"><?php esc_html_e( 'Loading your site content…', 'sitestaffr' ); ?></span>
	</div>
