<?php

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

$g = static function ( $k, $d = '' ) use ( $seo ) {
	return isset( $seo[ $k ] ) ? (string) $seo[ $k ] : $d;
};
$represents = ( 'person' === $g( 'org_represents', 'organization' ) ) ? 'person' : 'organization';
$logo       = $g( 'org_logo' );
?>
<div class="aieo-dmm-section">
	<h2><?php esc_html_e( 'Schema — Organization', 'ai-eshop-optimizer' ); ?></h2>
	<p class="description" style="max-width:880px;">
		<?php esc_html_e( 'Who the site represents + the logo, contact and address — emitted as the JSON-LD Organization (or Person) that Google attaches to your brand. Imported from AIOSEO if present; edit here.', 'ai-eshop-optimizer' ); ?>
	</p>

	<div class="aieo-dmm-card">
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Site represents', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<label><input type="radio" name="org_represents" value="organization" <?php checked( 'organization', $represents ); ?>> <?php esc_html_e( 'An organization', 'ai-eshop-optimizer' ); ?></label>
					&nbsp;&nbsp;
					<label><input type="radio" name="org_represents" value="person" <?php checked( 'person', $represents ); ?>> <?php esc_html_e( 'A person', 'ai-eshop-optimizer' ); ?></label>
				</td>
			</tr>
			<tr>
				<th><label for="aieo-org-name"><?php esc_html_e( 'Name', 'ai-eshop-optimizer' ); ?></label></th>
				<td><input type="text" id="aieo-org-name" class="regular-text" value="<?php echo esc_attr( $g( 'org_name' ) ); ?>" placeholder="<?php echo esc_attr( get_bloginfo( 'name' ) ); ?>"></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Logo', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<input type="url" id="aieo-org-logo" class="regular-text" style="width:60%;" value="<?php echo esc_attr( $logo ); ?>" placeholder="https://…">
					<button type="button" class="button" id="aieo-org-logo-pick"><?php esc_html_e( 'Select image', 'ai-eshop-optimizer' ); ?></button>
					<div id="aieo-org-logo-preview" style="margin-top:6px;"><?php if ( '' !== $logo ) : ?><img src="<?php echo esc_url( $logo ); ?>" style="max-height:60px;border:1px solid #e2e8f0;"><?php endif; ?></div>
				</td>
			</tr>
			<tr>
				<th><label for="aieo-org-phone"><?php esc_html_e( 'Phone', 'ai-eshop-optimizer' ); ?></label></th>
				<td><input type="text" id="aieo-org-phone" class="regular-text" value="<?php echo esc_attr( $g( 'org_phone' ) ); ?>"></td>
			</tr>
			<tr>
				<th><label for="aieo-org-email"><?php esc_html_e( 'Email', 'ai-eshop-optimizer' ); ?></label></th>
				<td><input type="email" id="aieo-org-email" class="regular-text" value="<?php echo esc_attr( $g( 'org_email' ) ); ?>"></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Address / location', 'ai-eshop-optimizer' ); ?></th>
				<td>
					<input type="text" id="aieo-org-street" class="regular-text" style="margin-bottom:4px;" value="<?php echo esc_attr( $g( 'org_street' ) ); ?>" placeholder="<?php esc_attr_e( 'Street address', 'ai-eshop-optimizer' ); ?>"><br>
					<input type="text" id="aieo-org-locality" value="<?php echo esc_attr( $g( 'org_locality' ) ); ?>" placeholder="<?php esc_attr_e( 'City', 'ai-eshop-optimizer' ); ?>">
					<input type="text" id="aieo-org-region" value="<?php echo esc_attr( $g( 'org_region' ) ); ?>" placeholder="<?php esc_attr_e( 'Region', 'ai-eshop-optimizer' ); ?>">
					<input type="text" id="aieo-org-postcode" value="<?php echo esc_attr( $g( 'org_postcode' ) ); ?>" placeholder="<?php esc_attr_e( 'Postcode', 'ai-eshop-optimizer' ); ?>">
					<input type="text" id="aieo-org-country" value="<?php echo esc_attr( $g( 'org_country' ) ); ?>" placeholder="<?php esc_attr_e( 'Country', 'ai-eshop-optimizer' ); ?>">
				</td>
			</tr>
		</table>
		<p>
			<button type="button" class="button button-primary" id="aieo-org-save"><?php esc_html_e( 'Save', 'ai-eshop-optimizer' ); ?></button>
			<span id="aieo-org-status" style="margin-left:8px;font-size:12px;"></span>
		</p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Store locations (Local SEO)', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;">
			<?php
			echo wp_kses_post( sprintf(
				
				_n( '%1$s store location is configured in %2$sLocations &amp; Reviews%3$s.', '%1$s store locations are configured in %2$sLocations &amp; Reviews%3$s.', (int) $loc_count, 'ai-eshop-optimizer' ),
				'<strong>' . (int) $loc_count . '</strong>',
				'<a href="' . esc_url( $loc_url ) . '">',
				'</a>'
			) );
			echo ' ';
			esc_html_e( 'When enabled, each enabled location is emitted as a LocalBusiness in your structured data, linked to this Organization. Address, geo and opening hours come from Google; the location flagged HQ backs the Organization address. Physical-shop review stars come from each location\'s Google Business Profile — we do not self-emit ratings (Google penalises that).', 'ai-eshop-optimizer' );
			?>
		</p>
		<p>
			<label><input type="checkbox" id="aieo-loc-schema" <?php checked( ! empty( $seo['locations_schema_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Emit LocalBusiness schema for store locations', 'ai-eshop-optimizer' ); ?></strong></label>
		</p>
		<p><a class="button" href="<?php echo esc_url( $loc_url ); ?>"><?php esc_html_e( 'Manage locations →', 'ai-eshop-optimizer' ); ?></a></p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Returns & shipping (Product schema)', 'ai-eshop-optimizer' ); ?></h3>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'Optional: add MerchantReturnPolicy + shipping to every product Offer. Leave OFF unless these reflect your ACTUAL terms — wrong values trigger Merchant Center issues. Emitted only when enabled.', 'ai-eshop-optimizer' ); ?>
		</p>
		<p><label><input type="checkbox" id="aieo-return-enabled" <?php checked( ! empty( $seo['return_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Emit return policy', 'ai-eshop-optimizer' ); ?></strong></label></p>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Return window (days)', 'ai-eshop-optimizer' ); ?></th>
				<td><input type="number" min="0" id="aieo-return-days" style="width:90px;" value="<?php echo esc_attr( $seo['return_days'] ?? '' ); ?>" placeholder="14">
					&nbsp;<?php esc_html_e( 'Country', 'ai-eshop-optimizer' ); ?> <input type="text" id="aieo-return-country" maxlength="2" style="width:60px;text-transform:uppercase;" value="<?php echo esc_attr( $seo['return_country'] ?? '' ); ?>" placeholder="GR">
					&nbsp;<label><input type="checkbox" id="aieo-return-free" <?php checked( ! empty( $seo['return_free'] ) ); ?>> <?php esc_html_e( 'Free returns', 'ai-eshop-optimizer' ); ?></label>
				</td>
			</tr>
		</table>
		<p><label><input type="checkbox" id="aieo-ship-enabled" <?php checked( ! empty( $seo['ship_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Emit shipping details', 'ai-eshop-optimizer' ); ?></strong></label></p>
		<table class="form-table">
			<tr>
				<th><?php esc_html_e( 'Shipping rate', 'ai-eshop-optimizer' ); ?></th>
				<td><input type="text" id="aieo-ship-rate" style="width:90px;" value="<?php echo esc_attr( $seo['ship_rate'] ?? '' ); ?>" placeholder="0.00">
					&nbsp;<?php esc_html_e( 'Country', 'ai-eshop-optimizer' ); ?> <input type="text" id="aieo-ship-country" maxlength="2" style="width:60px;text-transform:uppercase;" value="<?php echo esc_attr( $seo['ship_country'] ?? '' ); ?>" placeholder="GR">
				</td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Handling (days, min–max)', 'ai-eshop-optimizer' ); ?></th>
				<td><input type="number" min="0" id="aieo-handling-min" style="width:70px;" value="<?php echo esc_attr( $seo['handling_min'] ?? '' ); ?>" placeholder="0"> – <input type="number" min="0" id="aieo-handling-max" style="width:70px;" value="<?php echo esc_attr( $seo['handling_max'] ?? '' ); ?>" placeholder="1"></td>
			</tr>
			<tr>
				<th><?php esc_html_e( 'Transit (days, min–max)', 'ai-eshop-optimizer' ); ?></th>
				<td><input type="number" min="0" id="aieo-transit-min" style="width:70px;" value="<?php echo esc_attr( $seo['transit_min'] ?? '' ); ?>" placeholder="1"> – <input type="number" min="0" id="aieo-transit-max" style="width:70px;" value="<?php echo esc_attr( $seo['transit_max'] ?? '' ); ?>" placeholder="3"></td>
			</tr>
		</table>
		<p class="description"><?php esc_html_e( 'Applies site-wide to every product Offer (and each variation).', 'ai-eshop-optimizer' ); ?></p>

		<hr style="margin:16px 0;border:none;border-top:1px solid #e2e8f0;">
		<p><label><input type="checkbox" id="aieo-schema-faq-enabled" <?php checked( ! empty( $seo['schema_faq_enabled'] ) ); ?>> <strong><?php esc_html_e( 'Emit an FAQ for AI answer engines (ChatGPT, Perplexity, Google AI)', 'ai-eshop-optimizer' ); ?></strong></label></p>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'Adds a FAQPage to each product, generated from the return/shipping terms above plus the product\'s stock status — no extra setup, no per-visit cost (baked into the static head cache nightly). This is for AI/LLM answer engines, NOT Google rich results (Google retired FAQ snippets). Emitted only for the questions that are actually configured above.', 'ai-eshop-optimizer' ); ?>
		</p>

		<p><button type="button" class="button button-primary aieo-seo-save-proxy"><?php esc_html_e( 'Save', 'ai-eshop-optimizer' ); ?></button></p>
	</div>

	<div class="aieo-dmm-card">
		<h3><?php esc_html_e( 'Product ratings & colour (Product schema)', 'ai-eshop-optimizer' ); ?></h3>

		<?php
		
		$color_taxes = ( isset( $seo['color_attribute_taxonomies'] ) && is_array( $seo['color_attribute_taxonomies'] ) ) ? $seo['color_attribute_taxonomies'] : array();
		$all_taxes   = function_exists( 'wc_get_attribute_taxonomies' ) ? wc_get_attribute_taxonomies() : array();
		?>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'Flag which product attributes actually denote a colour. Their value is written into each simple/parent product\'s schema "color" (clears the Merchant-listing "missing color" warning). Variation colour is detected separately.', 'ai-eshop-optimizer' ); ?>
		</p>
		<table class="form-table">
			<tr>
				<th><label for="aieo-color-taxes"><?php esc_html_e( 'Colour attributes', 'ai-eshop-optimizer' ); ?></label></th>
				<td>
					<?php if ( empty( $all_taxes ) ) : ?>
						<em><?php esc_html_e( 'No global product attributes found.', 'ai-eshop-optimizer' ); ?></em>
					<?php else : ?>
						<select id="aieo-color-taxes" multiple size="<?php echo (int) min( 8, max( 3, count( $all_taxes ) ) ); ?>" style="min-width:280px;">
							<?php foreach ( $all_taxes as $att ) :
								$slug = 'pa_' . $att->attribute_name; ?>
								<option value="<?php echo esc_attr( $slug ); ?>" <?php selected( in_array( $slug, $color_taxes, true ) ); ?>><?php echo esc_html( $att->attribute_label . ' (' . $slug . ')' ); ?></option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php esc_html_e( 'Ctrl/Cmd-click to select multiple. Applied on the next vitals build / colour backfill.', 'ai-eshop-optimizer' ); ?></p>
					<?php endif; ?>
				</td>
			</tr>
		</table>

		<?php
		
		$rv_enabled    = ! empty( $seo['rating_review_enabled'] );
		$means         = ( isset( $seo['rating_star_meanings'] ) && is_array( $seo['rating_star_meanings'] ) ) ? $seo['rating_star_meanings'] : array();
		$mean_defaults = array(
			1 => __( 'Our customers rate this poorly.', 'ai-eshop-optimizer' ),
			2 => __( 'Our customers find this below average.', 'ai-eshop-optimizer' ),
			3 => __( 'Our customers find this average.', 'ai-eshop-optimizer' ),
			4 => __( 'Our customers find this very good.', 'ai-eshop-optimizer' ),
			5 => __( 'Our customers find this excellent.', 'ai-eshop-optimizer' ),
		);
		?>
		<p style="margin-top:14px;"><label><input type="checkbox" id="aieo-rating-review-enabled" <?php checked( $rv_enabled ); ?>> <strong><?php esc_html_e( 'Emit an aggregate review from genuine star ratings', 'ai-eshop-optimizer' ); ?></strong></label></p>
		<p class="description" style="max-width:880px;">
			<?php esc_html_e( 'When a product has genuine star ratings, emit a Review whose body is the matching sentence below (chosen by the rounded average) and whose rating is the REAL average — a plain-language gloss of real data, not an invented review. Genuine WooCommerce customer reviews, if enabled, are always emitted too. Toggle off if Google ever flags it.', 'ai-eshop-optimizer' ); ?>
		</p>
		<table class="form-table">
			<?php for ( $i = 1; $i <= 5; $i++ ) :
				$val = ( isset( $means[ $i ] ) && '' !== $means[ $i ] ) ? (string) $means[ $i ] : ''; ?>
				<tr>
					<th><label for="aieo-star-mean-<?php echo (int) $i; ?>"><?php echo esc_html( sprintf( _n( '%d star', '%d stars', $i, 'ai-eshop-optimizer' ), $i ) ); ?></label></th>
					<td><input type="text" id="aieo-star-mean-<?php echo (int) $i; ?>" class="large-text" value="<?php echo esc_attr( $val ); ?>" placeholder="<?php echo esc_attr( $mean_defaults[ $i ] ); ?>"></td>
				</tr>
			<?php endfor; ?>
		</table>
		<p><button type="button" class="button button-primary aieo-seo-save-proxy"><?php esc_html_e( 'Save', 'ai-eshop-optimizer' ); ?></button></p>
	</div>
</div>
<script>
(function(){
	var nonce = <?php echo wp_json_encode( $nonce ); ?>, ajax = <?php echo wp_json_encode( $ajax ); ?>;
	var logoField = document.getElementById('aieo-org-logo'), pick = document.getElementById('aieo-org-logo-pick');
	if (pick) {
		var frame;
		pick.addEventListener('click', function(e){
			e.preventDefault();
			// wp.media is enqueued at render and loads in the FOOTER, so check it
			// at click time — at parse time (when this inline script first runs)
			// it isn't defined yet, which is why the picker never opened before.
			if (!window.wp || !wp.media) { return; }
			if (frame) { frame.open(); return; }
			frame = wp.media({ title: 'Logo', multiple: false, library: { type: 'image' } });
			frame.on('select', function(){
				var a = frame.state().get('selection').first().toJSON();
				logoField.value = a.url;
				document.getElementById('aieo-org-logo-preview').innerHTML = '<img src="' + a.url + '" style="max-height:60px;border:1px solid #e2e8f0;">';
			});
			frame.open();
		});
	}
	var save = document.getElementById('aieo-org-save'), st = document.getElementById('aieo-org-status');
	if (save) save.addEventListener('click', function(){
		save.disabled = true; st.style.color = '#64748b'; st.textContent = <?php echo wp_json_encode( __( 'Saving…', 'ai-eshop-optimizer' ) ); ?>;
		var fd = new FormData();
		fd.set('action', 'aieo_seo_save_schema'); fd.set('nonce', nonce);
		fd.set('org_represents', (document.querySelector('input[name=org_represents]:checked')||{}).value || 'organization');
		[['org_name','aieo-org-name'],['org_logo','aieo-org-logo'],['org_phone','aieo-org-phone'],['org_email','aieo-org-email'],['org_street','aieo-org-street'],['org_locality','aieo-org-locality'],['org_region','aieo-org-region'],['org_postcode','aieo-org-postcode'],['org_country','aieo-org-country']].forEach(function(p){
			var el = document.getElementById(p[1]); fd.set(p[0], el ? el.value : '');
		});
		var locEl = document.getElementById('aieo-loc-schema');
		fd.set('locations_schema_enabled', locEl && locEl.checked ? '1' : '');
		var rEn = document.getElementById('aieo-return-enabled');
		fd.set('return_enabled', rEn && rEn.checked ? '1' : '');
		fd.set('return_days', (document.getElementById('aieo-return-days')||{}).value || '');
		fd.set('return_country', (document.getElementById('aieo-return-country')||{}).value || '');
		var rFree = document.getElementById('aieo-return-free');
		fd.set('return_free', rFree && rFree.checked ? '1' : '');
		var sEn = document.getElementById('aieo-ship-enabled');
		fd.set('ship_enabled', sEn && sEn.checked ? '1' : '');
		fd.set('ship_rate', (document.getElementById('aieo-ship-rate')||{}).value || '');
		fd.set('ship_country', (document.getElementById('aieo-ship-country')||{}).value || '');
		fd.set('handling_min', (document.getElementById('aieo-handling-min')||{}).value || '');
		fd.set('handling_max', (document.getElementById('aieo-handling-max')||{}).value || '');
		fd.set('transit_min', (document.getElementById('aieo-transit-min')||{}).value || '');
		fd.set('transit_max', (document.getElementById('aieo-transit-max')||{}).value || '');
		var faqEn = document.getElementById('aieo-schema-faq-enabled');
		fd.set('schema_faq_enabled', faqEn && faqEn.checked ? '1' : '');
		var ctEl = document.getElementById('aieo-color-taxes');
		if (ctEl) { Array.prototype.forEach.call(ctEl.selectedOptions, function(o){ fd.append('color_attribute_taxonomies[]', o.value); }); }
		var rvEn = document.getElementById('aieo-rating-review-enabled');
		fd.set('rating_review_enabled', rvEn && rvEn.checked ? '1' : '');
		for (var si = 1; si <= 5; si++) {
			var mEl = document.getElementById('aieo-star-mean-' + si);
			fd.set('rating_star_meanings[' + si + ']', mEl ? mEl.value : '');
		}
		fetch(ajax, { method:'POST', credentials:'same-origin', body: fd })
			.then(function(r){ return r.json(); })
			.then(function(j){ save.disabled = false; st.style.color = (j&&j.success)?'#15803d':'#b91c1c'; st.textContent = (j&&j.data&&j.data.message)||'Saved.'; })
			.catch(function(){ save.disabled = false; st.style.color = '#b91c1c'; st.textContent = 'Network error.'; });
	});
	// Toggling the locations-schema switch saves immediately (with the form).
	var locToggle = document.getElementById('aieo-loc-schema');
	if (locToggle && save) { locToggle.addEventListener('change', function(){ save.click(); }); }
	document.querySelectorAll('.aieo-seo-save-proxy').forEach(function(b){ if (save) { b.addEventListener('click', function(){ save.click(); }); } });
})();
</script>
