<?php

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

$src_badge = array(
	'manual' => '#2563eb',
	'slug'   => '#7c3aed',
	'import' => '#0891b2',
);
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Redirects', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:880px;">
		<?php esc_html_e( 'Send old or broken URLs to the right place (301/302/307) or mark them gone (410). Renaming a published product/post slug auto-creates a 301. Unmatched 404s are logged below so you can turn the top misses into redirects. Active once the SEO engine is enabled.', 'ai-eshop-optimizer' ); ?>
	</p>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Add a redirect', 'ai-eshop-optimizer' ); ?></h3>
		<p>
			<input type="text" id="aieo-rd-source" class="regular-text" placeholder="<?php esc_attr_e( '/old-path', 'ai-eshop-optimizer' ); ?>" style="width:32%;">
			<span style="margin:0 4px;">&rarr;</span>
			<input type="text" id="aieo-rd-target" class="regular-text" placeholder="<?php esc_attr_e( '/new-path or https://…', 'ai-eshop-optimizer' ); ?>" style="width:32%;">
			<select id="aieo-rd-code">
				<option value="301">301 <?php esc_html_e( 'Permanent', 'ai-eshop-optimizer' ); ?></option>
				<option value="302">302 <?php esc_html_e( 'Temporary', 'ai-eshop-optimizer' ); ?></option>
				<option value="307">307 <?php esc_html_e( 'Temporary (keep method)', 'ai-eshop-optimizer' ); ?></option>
				<option value="410">410 <?php esc_html_e( 'Gone', 'ai-eshop-optimizer' ); ?></option>
			</select>
			<label style="margin-left:8px;"><input type="checkbox" id="aieo-rd-regex"> <?php esc_html_e( 'Regex', 'ai-eshop-optimizer' ); ?></label>
			<button type="button" class="button button-primary" id="aieo-rd-add"><?php esc_html_e( 'Add', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-rd-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
		<p>
			<button type="button" class="button" id="aieo-rd-import"><?php esc_html_e( 'Import redirects from AIOSEO', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-rd-import-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Bulk edit (Excel / XLSX)', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'Export every redirect rule to an Excel file, delete or fix rows there, then re-upload to apply. Rows are matched (upserted) by Source Path. Tick "Full sync" to also delete rules you removed from the sheet — handy for bulk-clearing noise.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p>
			<button type="button" class="button" id="aieo-rd-export"><?php esc_html_e( 'Export to XLSX', 'ai-eshop-optimizer' ); ?></button>
			<span style="margin:0 12px;color:#cbd5e1;">|</span>
			<input type="file" id="aieo-rd-xlsx" accept=".xlsx" style="max-width:240px;">
			<label style="margin-left:8px;"><input type="checkbox" id="aieo-rd-fullsync"> <?php esc_html_e( 'Full sync (delete rules not in the file)', 'ai-eshop-optimizer' ); ?></label>
			<button type="button" class="button button-primary" id="aieo-rd-import-xlsx"><?php esc_html_e( 'Import', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-rd-xlsx-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php echo esc_html( sprintf(  __( 'Redirects (%d)', 'ai-eshop-optimizer' ), count( $redirects ) ) ); ?></h3>
		<table class="widefat striped" id="aieo-rd-table">
			<thead><tr>
				<th><?php esc_html_e( 'Source', 'ai-eshop-optimizer' ); ?></th>
				<th><?php esc_html_e( 'Target', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:60px;"><?php esc_html_e( 'Code', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:70px;"><?php esc_html_e( 'Source', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:60px;"><?php esc_html_e( 'Hits', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:60px;"><?php esc_html_e( 'On', 'ai-eshop-optimizer' ); ?></th>
				<th style="width:60px;"></th>
			</tr></thead>
			<tbody>
			<?php if ( empty( $redirects ) ) : ?>
				<tr><td colspan="7"><?php esc_html_e( 'No redirects yet.', 'ai-eshop-optimizer' ); ?></td></tr>
			<?php else : foreach ( $redirects as $r ) : ?>
				<?php $color = isset( $src_badge[ $r['source'] ] ) ? $src_badge[ $r['source'] ] : '#64748b'; ?>
				<tr data-id="<?php echo (int) $r['id']; ?>">
					<td><code><?php echo esc_html( $r['source_path'] ); ?></code><?php echo ! empty( $r['is_regex'] ) ? ' <span style="font-size:10px;color:#b45309;">regex</span>' : ''; ?></td>
					<td><code><?php echo esc_html( $r['target'] ); ?></code></td>
					<td><?php echo (int) $r['status_code']; ?></td>
					<td><span style="color:<?php echo esc_attr( $color ); ?>;font-size:11px;"><?php echo esc_html( (string) $r['source'] ); ?></span></td>
					<td><?php echo (int) $r['hits']; ?></td>
					<td><input type="checkbox" class="aieo-rd-toggle" <?php checked( ! empty( $r['enabled'] ) ); ?>></td>
					<td><button type="button" class="button-link aieo-rd-del" style="color:#b91c1c;"><?php esc_html_e( 'Delete', 'ai-eshop-optimizer' ); ?></button></td>
				</tr>
			<?php endforeach; endif; ?>
			</tbody>
		</table>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php echo esc_html( sprintf(  __( 'Top 404s (%d)', 'ai-eshop-optimizer' ), count( $fourohfour ) ) ); ?></h3>
		<?php if ( empty( $fourohfour ) ) : ?>
			<p><?php esc_html_e( 'No 404s logged yet.', 'ai-eshop-optimizer' ); ?></p>
		<?php else : ?>
			<table class="widefat striped" id="aieo-404-table">
				<thead><tr>
					<th><?php esc_html_e( 'Missing path', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:60px;"><?php esc_html_e( 'Hits', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:140px;"><?php esc_html_e( 'Last seen', 'ai-eshop-optimizer' ); ?></th>
					<th style="width:160px;"></th>
				</tr></thead>
				<tbody>
				<?php foreach ( $fourohfour as $f ) : ?>
					<tr data-id="<?php echo (int) $f['id']; ?>" data-path="<?php echo esc_attr( $f['path'] ); ?>">
						<td><code><?php echo esc_html( $f['path'] ); ?></code></td>
						<td><?php echo (int) $f['hits']; ?></td>
						<td style="font-size:11px;color:#64748b;"><?php echo esc_html( (string) $f['last_seen'] ); ?></td>
						<td>
							<button type="button" class="button button-small aieo-404-fix"><?php esc_html_e( 'Create redirect', 'ai-eshop-optimizer' ); ?></button>
							<button type="button" class="button-link aieo-404-dismiss" style="color:#64748b;"><?php esc_html_e( 'Dismiss', 'ai-eshop-optimizer' ); ?></button>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>
		<?php endif; ?>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Rebuild SEO index', 'ai-eshop-optimizer' ); ?></h3>
		<?php if ( isset( $provider_active ) && ! $provider_active ) : ?>
			<div class="notice notice-warning inline" style="margin:0 0 10px;"><p>
				<?php esc_html_e( 'AIEO is not the active SEO provider on this site (a competitor SEO plugin is active, or the engine is off in SEO → General). The head builder deliberately materialises nothing in that state — rows exist only when AIEO owns the head — so this rebuild will run through the objects without writing anything. Run it again after cut-over.', 'ai-eshop-optimizer' ); ?>
			</p></div>
		<?php endif; ?>
		<p class="description" style="max-width:880px;margin-top:0;">
			<?php esc_html_e( 'Re-materialise canonical URLs + sitemap eligibility for the selected object types, then regenerate the sitemap. Use after a bulk re-categorisation, a brand / need / tag import, or to pull freshly-published pages in. Every public content type on this site is offered — including custom types. Terms finish in seconds; large post types (e.g. Products) can take a few minutes.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p style="display:flex;flex-wrap:wrap;gap:6px 18px;align-items:center;max-width:880px;">
			<?php
			
			
			$rebuild_types = ( isset( $rebuild_types ) && is_array( $rebuild_types ) ) ? $rebuild_types : array();
			
			
			$rebuild_default = get_option( 'aieo_seo_rebuild_last_types', array() );
			if ( ! is_array( $rebuild_default ) || empty( $rebuild_default ) ) {
				$rebuild_default = array();
				foreach ( $rebuild_types as $tk => $t ) {
					if ( 'attributes' !== $tk && ! post_type_exists( $tk ) ) {
						$rebuild_default[] = $tk; 
					}
				}
			}
			foreach ( $rebuild_types as $tk => $t ) :
				?>
				<label style="white-space:nowrap;"><input type="checkbox" class="aieo-seo-rebuild-type" value="<?php echo esc_attr( $tk ); ?>" <?php checked( in_array( $tk, $rebuild_default, true ) ); ?>> <?php echo esc_html( $t['label'] ); ?> <span style="color:#94a3b8;">(<?php echo (int) $t['count']; ?>)</span></label>
			<?php endforeach; ?>
		</p>
		<p>
			<button type="button" class="button button-secondary" id="aieo-seo-rebuild-btn"><?php esc_html_e( 'Rebuild selected', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-seo-rebuild-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'New products auto-pick their deepest category as canonical on save; this is for bulk/after-the-fact rebuilds. Hidden products keep their canonical but stay out of the sitemap.', 'ai-eshop-optimizer' ); ?>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Custom robots.txt rules', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;margin-top:0;">
			<?php esc_html_e( 'AIEO serves your robots.txt directly as a static file — ahead of WordPress and any multilingual plugin. The block below is always included and managed automatically: it follows your Settings → Reading "Discourage search engines" choice and advertises your sitemap. Add your own rules underneath; they are appended and go live immediately.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p style="margin:0 0 4px;"><strong><?php esc_html_e( 'Always included (managed automatically):', 'ai-eshop-optimizer' ); ?></strong></p>
		<pre id="aieo-robots-default" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;padding:10px;max-width:880px;white-space:pre-wrap;font-size:12px;margin:0 0 12px;"><?php echo esc_html( isset( $robots_default ) ? $robots_default : '' ); ?></pre>
		<p style="margin:0 0 4px;"><label for="aieo-robots-custom"><strong><?php esc_html_e( 'Your additional rules:', 'ai-eshop-optimizer' ); ?></strong></label></p>
		<textarea id="aieo-robots-custom" class="large-text code" rows="8" style="max-width:880px;font-family:monospace;" placeholder="User-agent: SomeBot&#10;Disallow: /&#10;&#10;User-agent: *&#10;Disallow: /private/"><?php echo esc_textarea( isset( $robots_custom ) ? $robots_custom : '' ); ?></textarea>
		<p class="description" style="max-width:880px;margin-top:4px;"><?php esc_html_e( 'Plain robots.txt syntax (User-agent / Disallow / Allow / Crawl-delay / comments). Do not repeat the managed lines above — they are added for you.', 'ai-eshop-optimizer' ); ?></p>
		<p>
			<button type="button" class="button button-primary" id="aieo-robots-save"><?php esc_html_e( 'Save robots.txt rules', 'ai-eshop-optimizer' ); ?></button>
			<a href="<?php echo esc_url( home_url( '/robots.txt' ) ); ?>" target="_blank" rel="noopener" class="button"><?php esc_html_e( 'View robots.txt', 'ai-eshop-optimizer' ); ?></a>
			<span id="aieo-robots-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Edge serving (nginx)', 'ai-eshop-optimizer' ); ?></h3>
		<p>
			<button type="button" class="button button-secondary" id="aieo-rd-rebuild-edge"><?php esc_html_e( 'Regenerate edge files now', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-rd-rebuild-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
		<p class="description" style="max-width:880px;"><?php esc_html_e( 'Rewrites the redirect .map files + version.txt and rebuilds the sitemap shards from the current rules. Bumping version.txt makes the panel reload nginx.', 'ai-eshop-optimizer' ); ?></p>
		<p class="description" style="max-width:880px;">
			<?php
			echo esc_html( sprintf(
				
				__( 'For zero-PHP serving, redirects are written as nginx map files in %s (+ the sitemap as static XML). The hosting panel installs the config below — namespacing the map variables per site on shared nginx — and reloads nginx when version.txt changes; PHP serves as the fallback until then.', 'ai-eshop-optimizer' ),
				$edge_dir
			) );
			?>
		</p>
		<p class="description" style="max-width:880px;color:#15803d;font-weight:600;margin:0 0 6px;">
			<?php esc_html_e( 'Reference only — auto-installed by the Rooster panel (it polls version.txt and reloads nginx itself). Do NOT copy-paste this into your nginx config.', 'ai-eshop-optimizer' ); ?>
		</p>
		<textarea readonly rows="16" class="widefat" style="font-family:monospace;font-size:11px;"><?php echo esc_textarea( $nginx ); ?></textarea>
	</div>
</div>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	function post(action, data, cb){
		var fd = new FormData();
		fd.set('action', action); fd.set('nonce', nonce);
		Object.keys(data || {}).forEach(function(k){ fd.set(k, data[k]); });
		fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); })
			.then(function(j){ cb(j); })
			.catch(function(){ cb({ success:false, data:{ message:'Network error.' } }); });
	}
	var add = document.getElementById('aieo-rd-add'), st = document.getElementById('aieo-rd-status');
	if (add) add.addEventListener('click', function(){
		var source = document.getElementById('aieo-rd-source').value.trim();
		var target = document.getElementById('aieo-rd-target').value.trim();
		var code = document.getElementById('aieo-rd-code').value;
		var is_regex = document.getElementById('aieo-rd-regex').checked ? 1 : 0;
		if (!source) { st.style.color='#b91c1c'; st.textContent='Source required.'; return; }
		add.disabled = true; st.style.color='#64748b'; st.textContent='Saving…';
		post('aieo_seo_redirect_save', { source:source, target:target, code:code, is_regex:is_regex }, function(j){
			add.disabled = false;
			if (j && j.success) { location.reload(); }
			else { st.style.color='#b91c1c'; st.textContent=(j&&j.data&&j.data.message)||'Failed.'; }
		});
	});
	document.querySelectorAll('.aieo-rd-del').forEach(function(b){
		b.addEventListener('click', function(){
			var tr = b.closest('tr'); if (!tr || !confirm('Delete this redirect?')) return;
			post('aieo_seo_redirect_delete', { id: tr.getAttribute('data-id') }, function(j){ if (j&&j.success) tr.remove(); });
		});
	});
	document.querySelectorAll('.aieo-rd-toggle').forEach(function(c){
		c.addEventListener('change', function(){
			var tr = c.closest('tr');
			post('aieo_seo_redirect_toggle', { id: tr.getAttribute('data-id'), enabled: c.checked ? 1 : 0 }, function(j){
				if (!j || !j.success) {
					c.checked = !c.checked; // refused (e.g. would create a loop) — revert the switch
					alert((j && j.data && j.data.message) || 'Toggle failed.');
				}
			});
		});
	});
	document.querySelectorAll('.aieo-404-fix').forEach(function(b){
		b.addEventListener('click', function(){
			var tr = b.closest('tr'), p = tr.getAttribute('data-path');
			document.getElementById('aieo-rd-source').value = p;
			document.getElementById('aieo-rd-target').focus();
			window.scrollTo({ top: 0, behavior: 'smooth' });
		});
	});
	document.querySelectorAll('.aieo-404-dismiss').forEach(function(b){
		b.addEventListener('click', function(){
			var tr = b.closest('tr');
			post('aieo_seo_404_dismiss', { id: tr.getAttribute('data-id') }, function(j){ if (j&&j.success) tr.remove(); });
		});
	});
	var imp = document.getElementById('aieo-rd-import'), ist = document.getElementById('aieo-rd-import-status');
	if (imp) imp.addEventListener('click', function(){
		imp.disabled = true; ist.style.color='#64748b'; ist.textContent='Importing…';
		post('aieo_seo_redirect_import', {}, function(j){
			imp.disabled = false;
			if (j && j.success) {
				if (!j.data.available) { ist.style.color='#64748b'; ist.textContent='No AIOSEO redirects found.'; }
				else {
					ist.style.color='#15803d';
					var msg = 'Imported ' + (j.data.imported|0) + '.';
					if (j.data.skipped_missing_target|0) { msg += ' Skipped ' + (j.data.skipped_missing_target|0) + ' with targets that don’t exist on this site.'; }
					if (j.data.skipped_loop|0) { msg += ' Skipped ' + (j.data.skipped_loop|0) + ' that would loop.'; }
					if (j.data.regex_unverified|0) { msg += ' ' + (j.data.regex_unverified|0) + ' regex rules imported unverified.'; }
					ist.textContent = msg;
					setTimeout(function(){ location.reload(); }, (j.data.skipped_missing_target|0) || (j.data.skipped_loop|0) ? 3500 : 800);
				}
			} else { ist.style.color='#b91c1c'; ist.textContent=(j&&j.data&&j.data.message)||'Failed.'; }
		});
	});

	// Bulk XLSX export — form POST so the browser downloads via Content-Disposition.
	var exp = document.getElementById('aieo-rd-export');
	if (exp) exp.addEventListener('click', function(){
		var f = document.createElement('form');
		f.method = 'POST'; f.action = ajax; f.style.display = 'none';
		[['action','aieo_seo_redirect_export'],['nonce',nonce]].forEach(function(p){
			var i = document.createElement('input'); i.type='hidden'; i.name=p[0]; i.value=p[1]; f.appendChild(i);
		});
		document.body.appendChild(f); f.submit(); document.body.removeChild(f);
	});

	// Bulk XLSX import (upsert by source; optional full-sync delete of missing rules).
	var impx = document.getElementById('aieo-rd-import-xlsx'),
		ixs  = document.getElementById('aieo-rd-xlsx-status'),
		fin  = document.getElementById('aieo-rd-xlsx');
	if (impx) impx.addEventListener('click', function(){
		if (!fin || !fin.files || !fin.files[0]) { ixs.style.color='#b91c1c'; ixs.textContent='Choose an .xlsx file first.'; return; }
		var fs = document.getElementById('aieo-rd-fullsync').checked;
		if (fs && !confirm('Full sync will DELETE any rule not present in the uploaded file. Continue?')) return;
		impx.disabled = true; ixs.style.color='#64748b'; ixs.textContent='Importing…';
		post('aieo_seo_redirect_import_xlsx', { xlsx_file: fin.files[0], full_sync: fs ? 1 : 0 }, function(j){
			impx.disabled = false;
			if (j && j.success) {
				ixs.style.color='#15803d';
				ixs.textContent = 'Upserted ' + (j.data.upserts|0) + ', deleted ' + (j.data.deleted|0) + ', skipped ' + (j.data.skipped|0)
					+ ((j.data.skipped_missing_target|0) ? ' (' + (j.data.skipped_missing_target|0) + ' missing targets' + ((j.data.skipped_loop|0) ? ', ' + (j.data.skipped_loop|0) + ' loops' : '') + ')' : ((j.data.skipped_loop|0) ? ' (' + (j.data.skipped_loop|0) + ' loops)' : ''))
					+ '. Total ' + (j.data.total|0) + '.';
				setTimeout(function(){ location.reload(); }, (j.data.skipped_missing_target|0) || (j.data.skipped_loop|0) ? 3500 : 1800);
			} else { ixs.style.color='#b91c1c'; ixs.textContent=(j&&j.data&&j.data.message)||'Failed.'; }
		});
	});

	// Manual edge-file regeneration (redirect maps + version.txt + sitemap shards).
	var rb = document.getElementById('aieo-rd-rebuild-edge'), rbs = document.getElementById('aieo-rd-rebuild-status');
	if (rb) rb.addEventListener('click', function(){
		rb.disabled = true; rbs.style.color='#64748b'; rbs.textContent='Regenerating…';
		post('aieo_seo_redirect_rebuild_edge', {}, function(j){
			rb.disabled = false;
			if (j && j.success) {
				var c = j.data.counts || {}, tot = Object.keys(c).reduce(function(a,k){ return a + (c[k]|0); }, 0);
				var sm = (j.data.sitemap && j.data.sitemap.urls) ? (', sitemap ' + (j.data.sitemap.urls|0) + ' URLs') : '';
				rbs.style.color='#15803d';
				rbs.textContent = 'Done — ' + tot + ' map lines, version ' + (j.data.version||'?') + sm + '.';
			} else { rbs.style.color='#b91c1c'; rbs.textContent=(j&&j.data&&j.data.message)||'Failed.'; }
		});
	});

	// Per-type SEO-index rebuild — batched progress loop (canonical + indexable + sitemap).
	var rbi = document.getElementById('aieo-seo-rebuild-btn'), rbis = document.getElementById('aieo-seo-rebuild-status');
	if (rbi) rbi.addEventListener('click', function(){
		var types = Array.prototype.slice.call(document.querySelectorAll('.aieo-seo-rebuild-type:checked')).map(function(c){ return c.value; });
		if (!types.length) { rbis.style.color='#b91c1c'; rbis.textContent='Select at least one type.'; return; }
		if ((types.indexOf('post') >= 0 || types.indexOf('page') >= 0 || types.indexOf('product') >= 0) &&
			!confirm('Rebuilding Posts / Pages / Products can take several minutes. Continue?')) { return; }
		rbi.disabled = true; rbis.style.color='#64748b'; rbis.textContent='Starting…';
		var st = { types: types.join(','), ti: 0, last_id: 0, done_count: 0, total: -1 };
		function step(){
			post('aieo_seo_index_rebuild', st, function(j){
				if (!j || !j.success) { rbis.style.color='#b91c1c'; rbis.textContent=(j&&j.data&&j.data.message)||'Failed.'; rbi.disabled=false; return; }
				var d = j.data;
				st.ti = d.ti; st.last_id = d.last_id; st.done_count = d.done_count; st.total = d.total;
				if (d.done) {
					rbis.style.color='#15803d';
					rbis.textContent = 'Done — ' + d.done_count + ' objects rebuilt, sitemap regenerated.';
					rbi.disabled = false;
				} else {
					rbis.textContent = d.done_count + ' / ' + d.total + ' rebuilt' + (d.label ? (' — ' + d.label + '…') : '…');
					step();
				}
			});
		}
		step();
	});

	// Custom robots.txt rules — save + re-materialise the static file.
	var rbtn = document.getElementById('aieo-robots-save'), rst = document.getElementById('aieo-robots-status');
	if (rbtn) rbtn.addEventListener('click', function(){
		rbtn.disabled = true; rst.style.color = '#64748b'; rst.textContent = 'Saving…';
		post('aieo_seo_save_robots', { custom: document.getElementById('aieo-robots-custom').value }, function(j){
			rbtn.disabled = false;
			if (j && j.success) { rst.style.color = '#15803d'; rst.textContent = (j.data && j.data.message) || 'Saved.'; }
			else { rst.style.color = '#b91c1c'; rst.textContent = (j && j.data && j.data.message) || 'Failed.'; }
		});
	});
})();
</script>
