<?php
/**
 * Livada SEO — AI Bots Access view
 *
 * Per-bot allow/block toggles + live diagnostic that curl-tests each bot
 * against the home URL to show what the edge layer actually does.
 *
 * @package Livada_SEO
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Livada_SEO_AI_Bots' ) ) {
	echo '<div class="wrap"><h1>' . esc_html__( 'AI Bots Access', 'livada-seo' ) . '</h1>';
	echo '<p>' . esc_html__( 'AI Bots module is not loaded.', 'livada-seo' ) . '</p></div>';
	return;
}

$registry   = Livada_SEO_AI_Bots::registry();
$categories = Livada_SEO_AI_Bots::categories();
$allow_map  = Livada_SEO_AI_Bots::get_allow_map();
$hard_block = (bool) Livada_SEO_Loader::get_setting( 'ai_bots_hard_block', true );

// Build the contextual help-AI URL. We pass:
//   - page = 'ai-bots' so the assistant knows which screen the user is on
//   - site = home URL (allows the assistant to tailor responses)
//   - license = current license key (anonymised by Livada when not active)
// All three are optional on the server side — assistant degrades gracefully.
$ls_help_ai_url = add_query_arg(
	[
		'page'    => 'ai-bots',
		'site'    => rawurlencode( home_url() ),
		'license' => rawurlencode( (string) get_option( 'livada_seo_license_key', '' ) ),
	],
	'https://livada.io/help-ai'
);

// Group bots by category for the UI.
$grouped = [];
foreach ( $registry as $key => $bot ) {
	$grouped[ $bot['category'] ][ $key ] = $bot;
}

?>
<div class="wrap livada-seo-wrap has-ls-hero">
	<?php include LIVADA_SEO_PATH . 'includes/admin/views/_partials/header.php'; ?>

	<?php if ( isset( $_GET['updated'] ) ) : ?>
		<div class="notice notice-success is-dismissible">
			<p><strong><?php esc_html_e( 'AI Bots access settings saved.', 'livada-seo' ); ?></strong></p>
		</div>
	<?php endif; ?>

	<div class="ls-section">
		<h2><?php esc_html_e( 'Access control for AI crawlers', 'livada-seo' ); ?></h2>
		<p class="description">
			<?php esc_html_e( 'Decide which AI crawlers are allowed to read your site. Settings here are written into robots.txt with explicit per-bot Allow/Disallow blocks — so the directive is unambiguous even when an upstream layer (Cloudflare, host WAF) tries to interpret robots heuristics.', 'livada-seo' ); ?>
		</p>
		<p class="description">
			<strong><?php esc_html_e( 'Note:', 'livada-seo' ); ?></strong>
			<?php esc_html_e( 'robots.txt is a directive, not a block. The live diagnostic below tells you whether each bot can actually reach your site through the edge (Cloudflare, host firewall). If a bot returns 403 despite being allowed here, the block lives at the edge — see the AI Crawl Control panel in your CDN dashboard.', 'livada-seo' ); ?>
		</p>
	</div>

	<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
		<input type="hidden" name="action" value="livada_seo_save_ai_bots" />
		<?php wp_nonce_field( 'livada_seo_save_ai_bots' ); ?>

		<div class="ls-section">
			<h3 style="margin-top:0;"><?php esc_html_e( 'Enforcement mode', 'livada-seo' ); ?></h3>
			<label style="display:flex; align-items:flex-start; gap:10px; padding:12px; border:1px solid #e0e0e0; border-radius:6px; background: <?php echo $hard_block ? '#f0fff4' : '#fff8e1'; ?>;">
				<input type="checkbox"
				       name="livada_seo[ai_bots_hard_block]"
				       value="1"
				       <?php checked( $hard_block ); ?>
				       style="margin-top:2px;" />
				<span>
					<strong><?php esc_html_e( 'Hard block — return HTTP 403 to blocked bots', 'livada-seo' ); ?></strong>
					<br>
					<span class="description">
						<?php esc_html_e( 'When enabled (recommended), blocked bots receive a real HTTP 403 from PHP — scrapers that ignore robots.txt are stopped at the server. When disabled, only the robots.txt Disallow directive is published — well-behaved bots obey, scrapers can still reach the site.', 'livada-seo' ); ?>
					</span>
				</span>
			</label>
			<p class="description" style="margin-top:8px;">
				<?php esc_html_e( 'Note: Hard block runs at parse_request (priority 1) — no theme load, no DB hit beyond settings cache. Performance impact is negligible (a single user-agent string match per request).', 'livada-seo' ); ?>
			</p>
		</div>

		<div class="ls-section">
			<div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-bottom:16px;">
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Save changes', 'livada-seo' ); ?></button>
				<button type="button" id="livada-seo-test-all-bots" class="button">
					<?php esc_html_e( 'Run live diagnostic (test all bots)', 'livada-seo' ); ?>
				</button>
				<a href="<?php echo esc_url( $ls_help_ai_url ); ?>"
				   target="_blank"
				   rel="noopener"
				   class="button"
				   style="background:#EEF2FF;border-color:#4F46E5;color:#4F46E5;">
					<?php esc_html_e( '💬 Ask the Livada AI Assistant', 'livada-seo' ); ?>
				</a>
				<span id="livada-seo-test-status" class="description" style="margin-left:8px;"></span>
			</div>

			<?php foreach ( $categories as $cat_key => $cat_meta ) :
				if ( empty( $grouped[ $cat_key ] ) ) {
					continue;
				}
				?>
				<h3 style="margin-top:24px;">
					<?php echo esc_html( $cat_meta['label'] ); ?>
					<span class="description" style="font-weight:400; margin-left:8px;">— <?php echo esc_html( $cat_meta['recommendation'] ); ?></span>
				</h3>
				<p class="description"><?php echo esc_html( $cat_meta['description'] ); ?></p>

				<table class="widefat striped" style="margin-top:8px;">
					<thead>
						<tr>
							<th style="width:50px;"><?php esc_html_e( 'Allow', 'livada-seo' ); ?></th>
							<th><?php esc_html_e( 'Bot', 'livada-seo' ); ?></th>
							<th><?php esc_html_e( 'Operator', 'livada-seo' ); ?></th>
							<th style="width:120px;"><?php esc_html_e( 'Live status', 'livada-seo' ); ?></th>
							<th style="width:90px;"><?php esc_html_e( 'Test', 'livada-seo' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $grouped[ $cat_key ] as $key => $bot ) :
							$checked = ! empty( $allow_map[ $key ] );
							?>
							<tr>
								<td>
									<label class="ls-switch">
										<input type="checkbox"
										       name="livada_seo[ai_bots][<?php echo esc_attr( $key ); ?>]"
										       value="1"
										       <?php checked( $checked ); ?> />
									</label>
								</td>
								<td>
									<strong><?php echo esc_html( $bot['name'] ); ?></strong><br>
									<code style="font-size:11px;"><?php echo esc_html( $bot['slug'] ); ?></code>
								</td>
								<td><?php echo esc_html( $bot['owner'] ); ?></td>
								<td class="ls-bot-status" data-bot="<?php echo esc_attr( $key ); ?>">
									<span class="description"><?php esc_html_e( '—', 'livada-seo' ); ?></span>
								</td>
								<td>
									<button type="button"
									        class="button button-small livada-seo-test-bot"
									        data-bot="<?php echo esc_attr( $key ); ?>">
										<?php esc_html_e( 'Test', 'livada-seo' ); ?>
									</button>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endforeach; ?>

			<p style="margin-top:24px;">
				<button type="submit" class="button button-primary"><?php esc_html_e( 'Save changes', 'livada-seo' ); ?></button>
			</p>
		</div>
	</form>

	<div class="ls-section" style="margin-top:24px;">
		<h3><?php esc_html_e( 'How to read the live diagnostic', 'livada-seo' ); ?></h3>
		<ul style="margin-left:20px; list-style: disc;">
			<li><strong style="color:#00a32a;">200</strong> — <?php esc_html_e( 'Bot can reach your site. Working as expected when allowed.', 'livada-seo' ); ?></li>
			<li><strong style="color:#d63638;">403 / 401</strong> — <?php esc_html_e( 'Bot blocked at the edge (Cloudflare, host firewall). If you allowed the bot here but still see 403, the block is NOT in WordPress — check your CDN.', 'livada-seo' ); ?></li>
			<li><strong style="color:#dba617;">301 / 302</strong> — <?php esc_html_e( 'Redirect. Usually fine.', 'livada-seo' ); ?></li>
			<li><strong>5xx</strong> — <?php esc_html_e( 'Server error. Investigate.', 'livada-seo' ); ?></li>
		</ul>
	</div>
</div>

<script>
(function(){
	function setStatus(td, result){
		var code = result && result.code;
		var err  = result && result.error;
		var html;
		if (err) {
			html = '<span style="color:#d63638;">ERR</span> <code style="font-size:10px;">'+ String(err).slice(0,40) +'</code>';
		} else if (!code) {
			html = '<span class="description">—</span>';
		} else {
			var color = '#666';
			if (code === 200) color = '#00a32a';
			else if (code === 403 || code === 401) color = '#d63638';
			else if (code === 301 || code === 302) color = '#dba617';
			else if (code >= 500) color = '#d63638';
			html = '<strong style="color:'+ color +'; font-size:14px;">'+ code +'</strong>';
		}
		td.innerHTML = html;
	}

	function testOne(bot, td){
		td.innerHTML = '<span class="description">…</span>';
		var fd = new FormData();
		fd.append('action', 'livada_seo_test_ai_bot');
		fd.append('nonce', livadaSEO.nonce);
		fd.append('bot', bot);
		fetch(livadaSEO.ajaxUrl, { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); })
			.then(function(j){ setStatus(td, j && j.data ? j.data : { error: 'bad_response' }); })
			.catch(function(e){ setStatus(td, { error: String(e) }); });
	}

	document.addEventListener('click', function(e){
		var btn = e.target.closest('.livada-seo-test-bot');
		if (!btn) return;
		e.preventDefault();
		var bot = btn.getAttribute('data-bot');
		var td  = document.querySelector('.ls-bot-status[data-bot="'+ bot +'"]');
		if (td) testOne(bot, td);
	});

	var all = document.getElementById('livada-seo-test-all-bots');
	if (all) {
		all.addEventListener('click', function(e){
			e.preventDefault();
			var status = document.getElementById('livada-seo-test-status');
			status.textContent = '<?php echo esc_js( __( 'Testing all bots…', 'livada-seo' ) ); ?>';
			all.disabled = true;

			var fd = new FormData();
			fd.append('action', 'livada_seo_test_ai_bots');
			fd.append('nonce', livadaSEO.nonce);
			fetch(livadaSEO.ajaxUrl, { method:'POST', credentials:'same-origin', body: fd })
				.then(function(r){ return r.json(); })
				.then(function(j){
					if (j && j.data) {
						Object.keys(j.data).forEach(function(bot){
							var td = document.querySelector('.ls-bot-status[data-bot="'+ bot +'"]');
							if (td) setStatus(td, j.data[bot]);
						});
						status.textContent = '<?php echo esc_js( __( 'Done.', 'livada-seo' ) ); ?>';
					} else {
						status.textContent = '<?php echo esc_js( __( 'Error.', 'livada-seo' ) ); ?>';
					}
					all.disabled = false;
				})
				.catch(function(e){
					status.textContent = String(e);
					all.disabled = false;
				});
		});
	}
})();
</script>
