<?php
/**
 * Data management settings tab.
 *
 * @package TrustLens\Admin\Views\Settings
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables scoped to included view file.

// Get sync status.
$sync = TrustLens_Historical_Sync::instance();
$sync_status = $sync->get_status();
$progress = $sync->get_progress();

// Get data statistics.
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Simple count query, table name from $wpdb->prefix is safe.
$customer_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_customers" );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$events_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_events" );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
$signals_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}trustlens_signals" );
?>

<div class="wstl-card">
	<h2><?php esc_html_e( 'Historical Data Sync', 'trustlens' ); ?></h2>

	<div id="wstl-sync-status" class="wstl-sync-status">
		<p>
			<strong><?php esc_html_e( 'Status:', 'trustlens' ); ?></strong>
			<span class="wstl-sync-status-text">
				<?php
				switch ( $sync_status['status'] ) {
					case 'running':
						esc_html_e( 'Running', 'trustlens' );
						break;
					case 'completed':
						esc_html_e( 'Complete', 'trustlens' );
						break;
					case 'failed':
						esc_html_e( 'Failed', 'trustlens' );
						break;
					default:
						esc_html_e( 'Not Started', 'trustlens' );
				}
				?>
			</span>
		</p>

		<?php
		$sync_running = 'running' === $sync_status['status'];
		$sync_progress_val = $sync_running ? ( $progress ) : 0;
		$sync_processed = $sync_status['processed_orders'] ?? 0;
		$sync_total = $sync_status['total_orders'] ?? 0;
		?>
		<div id="wstl-sync-progress-area" class="<?php echo $sync_running ? '' : 'wstl-modal-hidden'; ?>">
			<div class="wstl-progress-bar">
				<div class="wstl-progress-fill" style="width: <?php echo esc_attr( $sync_progress_val ); ?>%;"></div>
			</div>
			<p class="wstl-progress-text" id="wstl-sync-orders-text">
				<?php
				echo esc_html(
					sprintf(
						/* translators: %1$d: processed, %2$d: total, %3$s: percentage */
						__( 'Processed %1$d of %2$d orders (%3$s%%)', 'trustlens' ),
						$sync_processed,
						$sync_total,
						number_format( $sync_progress_val, 1 )
					)
				);
				?>
			</p>
		</div>

		<?php
		// The status schema exposes started_at/completed_at; prefer the
		// completion time, falling back to the start time for an in-progress
		// or interrupted run.
		$sync_last_run = $sync_status['completed_at'] ?? null;
		if ( empty( $sync_last_run ) ) {
			$sync_last_run = $sync_status['started_at'] ?? null;
		}
		?>
		<?php if ( ! empty( $sync_last_run ) ) : ?>
			<p class="description">
				<?php
				printf(
					/* translators: %s: date/time */
					esc_html__( 'Last run: %s', 'trustlens' ),
					esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $sync_last_run ) ) )
				);
				?>
			</p>
		<?php endif; ?>
	</div>

	<p class="wstl-mt-20">
		<button type="button" class="button button-primary" id="wstl-start-sync" <?php echo $sync_running ? ' style="display:none;"' : ''; ?>>
			<?php esc_html_e( 'Start Historical Sync', 'trustlens' ); ?>
		</button>
		<button type="button" class="button" id="wstl-stop-sync" <?php echo $sync_running ? '' : ' style="display:none;"'; ?>>
			<?php esc_html_e( 'Stop Sync', 'trustlens' ); ?>
		</button>
		<span class="spinner wstl-spinner-inline"></span>
	</p>

	<p class="description">
		<?php esc_html_e( 'Sync analyzes your existing WooCommerce orders to build customer trust profiles. This runs in the background and may take some time for large stores.', 'trustlens' ); ?>
	</p>
</div>

<?php
// Test data seeder (stripped from production builds).
if ( class_exists( 'TrustLens_Test_Data_Seeder' ) ) :
$seeder = TrustLens_Test_Data_Seeder::instance();
$has_test_data = $seeder->has_test_data();
$test_data_count = $has_test_data ? $seeder->get_test_data_count() : 0;
?>

<div class="wstl-card wstl-card-dev">
	<h2><?php esc_html_e( 'Test Data (Development)', 'trustlens' ); ?></h2>
	<p class="description wstl-mb-15">
		<?php esc_html_e( 'Generate sample customer data across all trust segments to test plugin functionality without real WooCommerce orders.', 'trustlens' ); ?>
	</p>

	<div id="wstl-test-data-status">
		<?php if ( $has_test_data ) : ?>
			<p>
				<span class="dashicons dashicons-yes-alt wstl-icon-success"></span>
				<?php
				printf(
					/* translators: %d: number of test customers */
					esc_html__( '%d test customers currently in database.', 'trustlens' ),
					absint( $test_data_count )
				);
				?>
			</p>
		<?php else : ?>
			<p>
				<span class="dashicons dashicons-info wstl-icon-info"></span>
				<?php esc_html_e( 'No test data. Click below to generate 65 sample customers across all segments.', 'trustlens' ); ?>
			</p>
		<?php endif; ?>
	</div>

	<p class="wstl-mt-15">
		<?php if ( $has_test_data ) : ?>
			<button type="button" class="button button-link-delete" id="wstl-remove-test-data">
				<?php esc_html_e( 'Remove Test Data', 'trustlens' ); ?>
			</button>
		<?php else : ?>
			<p class="wstl-mb-15">
				<label for="wstl-seed-deterministic">
					<input type="checkbox" id="wstl-seed-deterministic" checked>
					<?php esc_html_e( 'Reproducible data (fixed seed) — generates identical data every run, ideal for screenshots', 'trustlens' ); ?>
				</label>
			</p>
			<button type="button" class="button button-primary" id="wstl-seed-test-data">
				<?php esc_html_e( 'Generate Test Data', 'trustlens' ); ?>
			</button>
		<?php endif; ?>
		<button type="button" class="button" id="wstl-check-clean-test-data">
			<?php esc_html_e( 'Check &amp; Clean', 'trustlens' ); ?>
		</button>
		<span class="spinner wstl-spinner-inline" id="wstl-test-data-spinner"></span>
	</p>
	<p class="description wstl-mt-5">
		<?php esc_html_e( 'Check &amp; Clean scans every table for leftover or orphaned test data and removes it — useful even when no test data is reported above.', 'trustlens' ); ?>
	</p>

	<div id="wstl-test-data-result" class="wstl-mt-10"></div>

	<p class="description wstl-mt-15">
		<?php esc_html_e( 'Test data includes:', 'trustlens' ); ?>
	</p>
	<ul class="wstl-list-disc">
		<li><?php esc_html_e( '30 Healthy customers (VIP/Trusted, score ~85-95)', 'trustlens' ); ?></li>
		<li><?php esc_html_e( '10 Normal customers (score ~50-65)', 'trustlens' ); ?></li>
		<li><?php esc_html_e( '8 Caution customers (score ~30-45, moderate abuse)', 'trustlens' ); ?></li>
		<li><?php esc_html_e( '7 Risk customers (score ~10-25, address hopping)', 'trustlens' ); ?></li>
		<li><?php esc_html_e( '5 Critical customers (score ~0-9, blocked, country mismatches)', 'trustlens' ); ?></li>
		<li><?php esc_html_e( 'Shipping address fingerprints with country codes', 'trustlens' ); ?></li>
	</ul>
</div>
<?php endif; ?>

<div class="wstl-card">
	<h2><?php esc_html_e( 'Data Statistics', 'trustlens' ); ?></h2>

	<table class="form-table">
		<tr>
			<th scope="row"><?php esc_html_e( 'Customers', 'trustlens' ); ?></th>
			<td><strong><?php echo esc_html( number_format( $customer_count ) ); ?></strong></td>
		</tr>
		<tr>
			<th scope="row"><?php esc_html_e( 'Events Logged', 'trustlens' ); ?></th>
			<td><strong><?php echo esc_html( number_format( $events_count ) ); ?></strong></td>
		</tr>
		<tr>
			<th scope="row"><?php esc_html_e( 'Signals Recorded', 'trustlens' ); ?></th>
			<td><strong><?php echo esc_html( number_format( $signals_count ) ); ?></strong></td>
		</tr>
	</table>
</div>

<?php
// Usage-data opt-in control. Lets a user who skipped the first-run Freemius
// opt-in turn on sharing later, and shows current state. This is the basic
// WordPress-environment opt-in — never customer data. Guarded so the free
// build without the SDK loaded degrades gracefully.
if ( function_exists( 'wstl_fs' ) ) :
	$wstl_optin_fs    = wstl_fs();
	$wstl_optin_is_in = $wstl_optin_fs->is_registered();
	?>
	<div class="wstl-card">
		<h2><?php esc_html_e( 'Help Improve TrustLens', 'trustlens' ); ?></h2>
		<?php if ( $wstl_optin_is_in ) : ?>
			<p>
				<span class="dashicons dashicons-yes-alt wstl-icon-success"></span>
				<?php esc_html_e( "You're sharing your site's basic WordPress environment with us — thank you. It helps us catch compatibility issues early and keep TrustLens working with your store.", 'trustlens' ); ?>
			</p>
			<p>
				<a class="button" href="<?php echo esc_url( $wstl_optin_fs->get_account_url() ); ?>"><?php esc_html_e( 'Manage data sharing', 'trustlens' ); ?></a>
			</p>
		<?php else : ?>
			<p>
				<?php esc_html_e( "Share your site's basic WordPress environment (like PHP and plugin versions) so we can catch compatibility issues early, fix problems faster, and keep improving TrustLens. We never collect your customers' data, orders, or payments.", 'trustlens' ); ?>
			</p>
			<p>
				<a class="button button-primary" href="<?php echo esc_url( $wstl_optin_fs->get_reconnect_url() ); ?>"><?php esc_html_e( 'Share usage data', 'trustlens' ); ?></a>
			</p>
		<?php endif; ?>
	</div>
	<?php
endif;
?>

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

	<div class="wstl-card">
		<h2><?php esc_html_e( 'Data Management', 'trustlens' ); ?></h2>

		<table class="form-table">
			<tr>
				<th scope="row"><?php esc_html_e( 'Uninstall Behavior', 'trustlens' ); ?></th>
				<td>
					<label>
						<input type="hidden" name="trustlens_remove_data_on_uninstall" value="0">
						<input type="checkbox" name="trustlens_remove_data_on_uninstall" value="1" <?php checked( get_option( 'trustlens_remove_data_on_uninstall', false ) ); ?>>
						<?php esc_html_e( 'Remove all TrustLens data when plugin is deleted', 'trustlens' ); ?>
					</label>
					<p class="description">
						<?php esc_html_e( 'Warning: This will permanently delete all TrustLens customer data, events, signals, linked-account fingerprints, category stats, and logs when the plugin is uninstalled.', 'trustlens' ); ?>
					</p>
				</td>
			</tr>
		</table>

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

<?php // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
