<?php
/**
 * Maintenance tab — operator actions for repairing plugin state (re-sync specs,
 * future: flush caches, regenerate term counts).
 *
 * Lives next to the per-feature tabs so dealers don't have to scroll past General
 * Settings to find the re-sync button (the previous spot — bottom of General —
 * was easy to miss and led to "cards are blank" support tickets).
 *
 * @package ThemeREX\AutoDealer\Admin\Settings\Tabs
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Admin\Settings\Tabs;

defined( 'ABSPATH' ) || exit;

use ThemeREX\AutoDealer\Admin\AdminSettings;
use ThemeREX\AutoDealer\Admin\Settings\AbstractSettingsTab;

final class MaintenanceTab extends AbstractSettingsTab {

	public function getKey(): string {
		return 'maintenance';
	}

	public function getLabel(): string {
		return __( 'Maintenance', 'trx-auto-dealer' );
	}

	public function register(): void {
		// No options registered — actions are POSTs to admin-post.php handlers
		// already wired in AdminSettings::register() (admin_post_trx_ad_resync_specs).
	}

	public function render(): void {
		$resync_msg    = isset( $_GET['trx_ad_resync_msg'] ) ? sanitize_key( (string) $_GET['trx_ad_resync_msg'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$flush_msg     = isset( $_GET['trx_ad_flush_msg'] ) ? sanitize_key( (string) $_GET['trx_ad_flush_msg'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$uninstall_msg = isset( $_GET['trx_ad_uninstall_msg'] ) ? sanitize_key( (string) $_GET['trx_ad_uninstall_msg'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		if ( 'done' === $flush_msg ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Filter aggregation cache flushed.', 'trx-auto-dealer' ) . '</p></div>';
		}

		if ( 'done' === $uninstall_msg ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Uninstall preference saved.', 'trx-auto-dealer' ) . '</p></div>';
		}

		if ( 'done' === $resync_msg ) {
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Vehicle specs re-synced. Compare page and cards will now reflect the current admin data.', 'trx-auto-dealer' ) . '</p></div>';
			$report = get_transient( 'trx_ad_resync_report' );
			delete_transient( 'trx_ad_resync_report' );
			if ( is_array( $report ) && ! empty( $report ) ) {
				echo '<details style="background:#f6f7f7;border:1px solid #c3c4c7;padding:8px 12px;margin:8px 0;max-width:900px;"><summary style="cursor:pointer;font-weight:600;">' . esc_html__( 'Per-listing sync result (click to expand)', 'trx-auto-dealer' ) . '</summary>';
				echo '<table class="widefat" style="margin-top:8px;"><thead><tr><th>ID</th><th>Title</th><th>Result</th><th>Cols written</th><th>Sample (year/make/model)</th></tr></thead><tbody>';
				foreach ( $report as $row ) {
					$ok       = empty( $row['error'] );
					$colNames = is_array( $row['data'] ?? null ) ? implode( ', ', array_keys( $row['data'] ) ) : '';
					$sample   = sprintf(
						'year=%s make=%s model=%s',
						$row['data']['year'] ?? '-',
						$row['data']['make'] ?? '-',
						$row['data']['model'] ?? '-'
					);
					echo '<tr>';
					echo '<td>' . esc_html( (string) $row['id'] ) . '</td>';
					echo '<td>' . esc_html( (string) $row['title'] ) . '</td>';
					echo '<td style="color:' . ( $ok ? '#00853b' : '#b32d2e' ) . '">' . esc_html( $ok ? 'OK' : (string) $row['error'] ) . '</td>';
					echo '<td>' . esc_html( $colNames ) . '</td>';
					echo '<td>' . esc_html( $sample ) . '</td>';
					echo '</tr>';
				}
				echo '</tbody></table></details>';
			}
		}
		?>
		<h2><?php esc_html_e( 'Re-sync vehicle specs', 'trx-auto-dealer' ); ?></h2>
		<p class="description" style="max-width:640px;">
			<?php esc_html_e( 'If a listing shows missing details on the compare page, vehicle cards, or filter sidebar even though the admin edit screen has the data, run a re-sync. This rebuilds every listing\'s specs row from its post meta and clears the filter cache.', 'trx-auto-dealer' ); ?>
		</p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:8px;">
			<?php wp_nonce_field( 'trx_ad_resync_specs' ); ?>
			<input type="hidden" name="action" value="trx_ad_resync_specs">
			<?php submit_button( __( 'Re-sync vehicle specs', 'trx-auto-dealer' ), 'secondary', 'submit', false ); ?>
		</form>

		<hr style="margin:32px 0;">

		<h2><?php esc_html_e( 'Flush filter aggregation cache', 'trx-auto-dealer' ); ?></h2>
		<p class="description" style="max-width:640px;">
			<?php esc_html_e( 'Force the cached filter facets (makes / body styles / fuel types / counts) to rebuild on the next archive view. Run this if the sidebar filter shows stale options after a bulk import or taxonomy edit.', 'trx-auto-dealer' ); ?>
		</p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:8px;">
			<?php wp_nonce_field( 'trx_ad_flush_cache' ); ?>
			<input type="hidden" name="action" value="trx_ad_flush_cache">
			<?php submit_button( __( 'Flush filter cache', 'trx-auto-dealer' ), 'secondary', 'submit', false ); ?>
		</form>

		<hr style="margin:32px 0;">

		<h2><?php esc_html_e( 'Uninstall', 'trx-auto-dealer' ); ?></h2>
		<p class="description" style="max-width:640px;">
			<?php esc_html_e( 'By default, deleting the plugin keeps your listings, dealers, leads, and settings so nothing is lost on an accidental removal or reinstall. Enable this option to remove ALL plugin data (listings, taxonomies, custom tables, options, and roles) when the plugin is deleted from the Plugins screen.', 'trx-auto-dealer' ); ?>
		</p>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="margin-top:8px;">
			<?php wp_nonce_field( 'trx_ad_uninstall_pref' ); ?>
			<input type="hidden" name="action" value="trx_ad_uninstall_pref">
			<label for="trx_ad_delete_data_on_uninstall">
				<input
					type="checkbox"
					id="trx_ad_delete_data_on_uninstall"
					name="trx_ad_delete_data_on_uninstall"
					value="1"
					<?php checked( (bool) get_option( 'trx_ad_delete_data_on_uninstall', false ) ); ?> />
				<?php esc_html_e( 'Delete all data on uninstall', 'trx-auto-dealer' ); ?>
			</label>
			<?php submit_button( __( 'Save uninstall preference', 'trx-auto-dealer' ), 'secondary', 'submit', false ); ?>
		</form>
		<?php
	}
}
