<?php
/**
 * Store Trust Network settings tab.
 *
 * Ships in the free build as a locked teaser; the working form renders only for
 * multi-site Pro licenses. Mirrors how reports.php / webhooks.php gate their Pro
 * content, so a free user clicking the tab never hits a stripped file.
 *
 * @package TrustLens\Admin\Views\Settings
 * @since   1.3.5
 */

defined( 'ABSPATH' ) || exit;

// Non-eligible users (free build, or a Pro license without multi-site) get the
// promotional upsell via the shared component — same pattern as the Webhooks and
// Reports tabs. Free builds also land here, since wstl_can_use_network() is stripped.
if ( ! function_exists( 'wstl_can_use_network' ) || ! wstl_can_use_network() ) {
	$wstl_features = array(
		__( 'Cross-store risk flags shared privately between your own stores', 'trustlens' ),
		__( 'Only an irreversible keyed hash is shared — never names or emails', 'trustlens' ),
		__( 'Background sync keeps checkout fast and never blocks if a store is offline', 'trustlens' ),
		__( 'Catches repeat offenders on their first order at a new store', 'trustlens' ),
	);
	$wstl_compare  = array(
		array( __( 'Customer history', 'trustlens' ), __( 'This store only', 'trustlens' ), __( 'Shared across your stores', 'trustlens' ) ),
		array( __( 'Data shared between stores', 'trustlens' ), __( 'N/A', 'trustlens' ), __( 'Hashed signal only — no PII', 'trustlens' ) ),
		array( __( 'New-customer protection', 'trustlens' ), __( 'After local history builds', 'trustlens' ), __( 'From their first order', 'trustlens' ) ),
	);

	// A customer already on a paid plan (e.g. Starter, single-site) HAS Pro — the
	// network just needs a multi-site plan, so pitch a PLAN UPGRADE, not "get Pro".
	// Free / unlicensed users fall through to the standard get-Pro upsell defaults.
	$wstl_opts = array();
	if ( function_exists( 'wstl_can_use_pro' ) && wstl_can_use_pro() ) {
		$wstl_opts = array(
			'badge'              => '',
			'compare_free_label' => __( 'Your plan', 'trustlens' ),
			'compare_pro_label'  => __( 'Professional / Business', 'trustlens' ),
			'primary_cta'        => __( 'Upgrade to Professional or Business', 'trustlens' ),
			'secondary_cta'      => __( 'Compare plans', 'trustlens' ),
		);
	}

	wstl_render_pro_upsell(
		__( 'Store Trust Network', 'trustlens' ),
		__( 'Link the WooCommerce stores you own so a customer flagged for return abuse or chargebacks at one store is recognized at the others — without ever sharing names or email addresses.', 'trustlens' ),
		$wstl_features,
		$wstl_compare,
		__( 'Available on the Professional and Business plans', 'trustlens' ),
		null,
		$wstl_opts
	);
	return;
}

$wstl_key   = wstl_network_get_group_key();
$wstl_peers = (string) get_option( 'trustlens_network_peers', '' );
?>
<div class="wstl-card">
	<h2><?php esc_html_e( 'Store Trust Network', 'trustlens' ); ?></h2>
	<p class="description">
		<?php esc_html_e( 'Privately share customer risk flags across your own linked stores. Paste the SAME group key into every store you own, and list each other store URL below. Customer emails are never shared — only an irreversible keyed hash.', 'trustlens' ); ?>
	</p>

	<form method="post" action="options.php">
		<?php settings_fields( 'trustlens_network' ); ?>

		<table class="form-table" role="presentation">
			<tr>
				<th scope="row"><?php esc_html_e( 'Enable network', 'trustlens' ); ?></th>
				<td>
					<label class="wstl-toggle">
						<input type="hidden" name="trustlens_module_store_network_enabled" value="0">
						<input type="checkbox" name="trustlens_module_store_network_enabled" value="1" <?php checked( (bool) get_option( 'trustlens_module_store_network_enabled', false ) ); ?>>
						<span class="wstl-toggle-slider"></span>
					</label>
					<p class="description"><?php esc_html_e( 'Off by default. Requires a group key below.', 'trustlens' ); ?></p>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="trustlens_network_group_key"><?php esc_html_e( 'Group key', 'trustlens' ); ?></label></th>
				<td>
					<input type="text" id="trustlens_network_group_key" name="trustlens_network_group_key" value="<?php echo esc_attr( $wstl_key ); ?>" class="regular-text code" autocomplete="off">
					<button type="button" class="button" id="wstl-gen-network-key"><?php esc_html_e( 'Generate', 'trustlens' ); ?></button>
					<p class="description"><?php esc_html_e( 'Generate once, then paste the identical key into every store you own. Keep it secret.', 'trustlens' ); ?></p>
				</td>
			</tr>
			<tr>
				<th scope="row"><label for="trustlens_network_peers"><?php esc_html_e( 'Linked store URLs', 'trustlens' ); ?></label></th>
				<td>
					<textarea id="trustlens_network_peers" name="trustlens_network_peers" rows="4" class="large-text code" placeholder="https://store-two.example.com"><?php echo esc_textarea( $wstl_peers ); ?></textarea>
					<p class="description"><?php esc_html_e( 'One https:// store URL per line. This store pulls flags from each, hourly.', 'trustlens' ); ?></p>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Share my flags', 'trustlens' ); ?></th>
				<td>
					<label class="wstl-toggle">
						<input type="hidden" name="trustlens_network_share_flags" value="0">
						<input type="checkbox" name="trustlens_network_share_flags" value="1" <?php checked( (bool) get_option( 'trustlens_network_share_flags', true ) ); ?>>
						<span class="wstl-toggle-slider"></span>
					</label>
				</td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'Caution penalty', 'trustlens' ); ?></th>
				<td><input type="number" name="trustlens_network_caution_penalty" min="0" max="50" value="<?php echo esc_attr( (string) get_option( 'trustlens_network_caution_penalty', 15 ) ); ?>" class="small-text"> <?php esc_html_e( 'points', 'trustlens' ); ?></td>
			</tr>
			<tr>
				<th scope="row"><?php esc_html_e( 'High-risk penalty', 'trustlens' ); ?></th>
				<td><input type="number" name="trustlens_network_high_penalty" min="0" max="50" value="<?php echo esc_attr( (string) get_option( 'trustlens_network_high_penalty', 35 ) ); ?>" class="small-text"> <?php esc_html_e( 'points', 'trustlens' ); ?></td>
			</tr>
		</table>

		<?php submit_button(); ?>
	</form>
</div>

<?php
// --- Sync status panel ------------------------------------------------------
$wstl_status   = (array) get_option( 'trustlens_network_sync_status', array() );
$wstl_counts   = class_exists( 'TrustLens_Network_Flag_Repository' )
	? ( new TrustLens_Network_Flag_Repository() )->count_by_origin()
	: array(
		'local'  => 0,
		'remote' => 0,
	);
$wstl_peer_cfg = class_exists( 'TrustLens_Network_Sync' ) ? TrustLens_Network_Sync::peer_urls( $wstl_peers ) : array();
$wstl_last_run = isset( $wstl_status['last_run'] ) ? (string) $wstl_status['last_run'] : '';
$wstl_peer_st  = isset( $wstl_status['peers'] ) && is_array( $wstl_status['peers'] ) ? $wstl_status['peers'] : array();
?>
<div class="wstl-card">
	<h2><?php esc_html_e( 'Sync status', 'trustlens' ); ?></h2>
	<p class="description">
		<?php esc_html_e( 'Last sync:', 'trustlens' ); ?>
		<strong>
		<?php
		echo '' !== $wstl_last_run
			/* translators: %s: human-readable time difference, e.g. "5 mins". */
			? esc_html( sprintf( __( '%s ago', 'trustlens' ), human_time_diff( (int) strtotime( $wstl_last_run ) ) ) )
			: esc_html__( 'never', 'trustlens' );
		?>
			</strong>
		&middot; <?php esc_html_e( 'Flags shared by you:', 'trustlens' ); ?> <strong><?php echo esc_html( (string) $wstl_counts['local'] ); ?></strong>
		&middot; <?php esc_html_e( 'Pulled from peers:', 'trustlens' ); ?> <strong><?php echo esc_html( (string) $wstl_counts['remote'] ); ?></strong>
	</p>

	<?php if ( ! empty( $wstl_peer_cfg ) ) : ?>
		<table class="widefat striped" style="max-width:680px;">
			<thead>
				<tr>
					<th><?php esc_html_e( 'Linked store', 'trustlens' ); ?></th>
					<th><?php esc_html_e( 'Status', 'trustlens' ); ?></th>
					<th><?php esc_html_e( 'Flags pulled', 'trustlens' ); ?></th>
					<th><?php esc_html_e( 'Checked', 'trustlens' ); ?></th>
				</tr>
			</thead>
			<tbody>
			<?php
			foreach ( $wstl_peer_cfg as $wstl_p ) :
				$wstl_st  = isset( $wstl_peer_st[ $wstl_p ] ) ? $wstl_peer_st[ $wstl_p ] : null;
				$wstl_dot = '#888';
				if ( $wstl_st ) {
					$wstl_dot = 'ok' === $wstl_st['state'] ? '#2e7d32' : ( 'skipped' === $wstl_st['state'] ? '#888' : '#c62828' );
				}
				?>
				<tr>
					<td><?php echo esc_html( $wstl_p ); ?></td>
					<td>
						<?php if ( ! $wstl_st ) : ?>
							<?php esc_html_e( 'Not synced yet', 'trustlens' ); ?>
						<?php else : ?>
							<span style="color:<?php echo esc_attr( $wstl_dot ); ?>;" aria-hidden="true">&#9679;</span>
							<?php echo esc_html( (string) $wstl_st['detail'] ); ?>
						<?php endif; ?>
					</td>
					<td><?php echo $wstl_st ? esc_html( (string) (int) $wstl_st['received'] ) : '&mdash;'; ?></td>
					<td>
					<?php
					echo $wstl_st && ! empty( $wstl_st['time'] )
						/* translators: %s: human-readable time difference, e.g. "5 mins". */
						? esc_html( sprintf( __( '%s ago', 'trustlens' ), human_time_diff( (int) strtotime( (string) $wstl_st['time'] ) ) ) )
						: '&mdash;';
					?>
						</td>
				</tr>
			<?php endforeach; ?>
			</tbody>
		</table>
	<?php else : ?>
		<p class="description"><?php esc_html_e( 'Add one or more linked store URLs above to start syncing.', 'trustlens' ); ?></p>
	<?php endif; ?>

	<p>
		<button type="button" class="button" id="wstl-network-sync-now"><?php esc_html_e( 'Sync now', 'trustlens' ); ?></button>
		<span id="wstl-network-sync-feedback" style="margin-left:8px;color:#555;"></span>
	</p>
</div>

<script>
( function () {
	var sb = document.getElementById( 'wstl-network-sync-now' );
	if ( ! sb ) {
		return;
	}
	sb.addEventListener( 'click', function () {
		var fb = document.getElementById( 'wstl-network-sync-feedback' );
		sb.disabled = true;
		fb.textContent = '<?php echo esc_js( __( 'Syncing…', 'trustlens' ) ); ?>';
		var data = new FormData();
		data.append( 'action', 'wstl_network_sync_now' );
		data.append( 'nonce', '<?php echo esc_js( wp_create_nonce( 'trustlens_admin' ) ); ?>' );
		fetch( ajaxurl, { method: 'POST', credentials: 'same-origin', body: data } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( resp ) {
				if ( resp && resp.success ) {
					location.reload();
				} else {
					fb.textContent = ( resp && resp.data && resp.data.message ) || '<?php echo esc_js( __( 'Sync failed.', 'trustlens' ) ); ?>';
					sb.disabled = false;
				}
			} )
			.catch( function () {
				fb.textContent = '<?php echo esc_js( __( 'Request failed.', 'trustlens' ) ); ?>';
				sb.disabled = false;
			} );
	} );
} )();
</script>
<script>
( function () {
	var btn = document.getElementById( 'wstl-gen-network-key' );
	if ( ! btn ) {
		return;
	}
	btn.addEventListener( 'click', function () {
		var bytes = new Uint8Array( 32 ), hex = '', i;
		( window.crypto || window.msCrypto ).getRandomValues( bytes );
		for ( i = 0; i < bytes.length; i++ ) {
			hex += ( '0' + bytes[ i ].toString( 16 ) ).slice( -2 );
		}
		document.getElementById( 'trustlens_network_group_key' ).value = hex;
	} );
} )();
</script>
