<?php
/**
 * General tab — archive slug, listings/page, distance unit, currency, dealer permissions.
 *
 * Plus the inline "Re-sync vehicle specs" maintenance action (admin-post handler).
 *
 * Extracted from AdminSettings per QUALITY-IMPROVEMENT-PLAN.md §T2-2.
 *
 * @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 GeneralTab extends AbstractSettingsTab {

	/**
	 * Settings API option group. Hardcoded so the tab can register fields
	 * without piercing AdminSettings' private const. Stable WP contract.
	 */
	public const OPTION_GROUP = 'trx_ad_settings_group';

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

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

	public function register(): void {
		register_setting(
			self::OPTION_GROUP,
			AdminSettings::OPTION_KEY,
			array(
				'type'              => 'array',
				'sanitize_callback' => array( AdminSettings::class, 'sanitize' ),
			)
		);

		add_settings_section(
			'trx_ad_general',
			__( 'General Settings', 'trx-auto-dealer' ),
			array( $this, 'renderSectionDescription' ),
			AdminSettings::PAGE_SLUG
		);

		$fields = array(
			array( 'archive_slug', __( 'Archive Slug', 'trx-auto-dealer' ), 'renderArchiveSlug' ),
			array( 'listings_per_page', __( 'Listings Per Page', 'trx-auto-dealer' ), 'renderListingsPerPage' ),
			array( 'default_sort', __( 'Default Sort Order', 'trx-auto-dealer' ), 'renderDefaultSort' ),
			array( 'distance_unit', __( 'Distance Unit', 'trx-auto-dealer' ), 'renderDistanceUnit' ),
			array( 'currency_symbol', __( 'Currency Symbol', 'trx-auto-dealer' ), 'renderCurrencySymbol' ),
			array( 'currency_code', __( 'Currency Code (ISO 4217)', 'trx-auto-dealer' ), 'renderCurrencyCode' ),
			array( 'dealer_can_publish', __( 'Dealer Publishing', 'trx-auto-dealer' ), 'renderDealerCanPublish' ),
			array( 'dealer_profile_requires_review', __( 'Dealer Profile Review', 'trx-auto-dealer' ), 'renderDealerProfileRequiresReview' ),
			array( 'allow_svg_uploads', __( 'SVG Icon Uploads', 'trx-auto-dealer' ), 'renderAllowSvgUploads' ),
		);
		foreach ( $fields as $f ) {
			add_settings_field( $f[0], $f[1], array( $this, $f[2] ), AdminSettings::PAGE_SLUG, 'trx_ad_general' );
		}
	}

	public function render(): void {
		?>
		<form method="post" action="options.php">
			<?php
			settings_fields( self::OPTION_GROUP );
			do_settings_sections( AdminSettings::PAGE_SLUG );
			submit_button();
			?>
		</form>
		<p class="description" style="max-width:640px;margin-top:16px;">
			<?php
			printf(
				/* translators: %s: Maintenance tab link. */
				esc_html__( 'Operator actions (re-sync vehicle specs, flush filter cache) live on the %s tab.', 'trx-auto-dealer' ),
				'<a href="' . esc_url(
					add_query_arg(
						array(
							'post_type' => 'trx_ad_listing',
							'page'      => AdminSettings::PAGE_SLUG,
							'tab'       => 'maintenance',
						),
						admin_url( 'edit.php' )
					)
				) . '">' . esc_html__( 'Maintenance', 'trx-auto-dealer' ) . '</a>'
			);
			?>
		</p>
		<?php
	}

	public function renderSectionDescription(): void {
		echo '<p>';
		esc_html_e( 'Configure general settings for the Auto Dealer plugin.', 'trx-auto-dealer' );
		echo '</p>';
	}

	public function renderArchiveSlug(): void {
		$settings = AdminSettings::getSettings();
		printf(
			'<input type="text" name="%s[archive_slug]" id="trx_ad_archive_slug" value="%s" class="regular-text">'
			. '<p class="description">%s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			esc_attr( (string) ( $settings['archive_slug'] ?? '' ) ),
			esc_html__( 'URL slug for the vehicle archive page. Changes require a permalink flush.', 'trx-auto-dealer' )
		);
	}

	public function renderListingsPerPage(): void {
		$settings = AdminSettings::getSettings();
		printf(
			'<input type="number" name="%s[listings_per_page]" id="trx_ad_listings_per_page" value="%d" min="1" max="100" class="small-text">'
			. '<p class="description">%s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			(int) ( $settings['listings_per_page'] ?? 12 ),
			esc_html__( 'Number of vehicle listings to show per page on the archive.', 'trx-auto-dealer' )
		);
	}

	public function renderDistanceUnit(): void {
		$settings = AdminSettings::getSettings();
		$current  = (string) ( $settings['distance_unit'] ?? 'km' );

		printf( '<select name="%s[distance_unit]" id="trx_ad_distance_unit">', esc_attr( AdminSettings::OPTION_KEY ) );
		printf(
			'<option value="km"%s>%s</option>',
			selected( $current, 'km', false ),
			esc_html__( 'Kilometers (km)', 'trx-auto-dealer' )
		);
		printf(
			'<option value="miles"%s>%s</option>',
			selected( $current, 'miles', false ),
			esc_html__( 'Miles (mi)', 'trx-auto-dealer' )
		);
		echo '</select>';
		printf( '<p class="description">%s</p>', esc_html__( 'Unit for mileage and distance displays.', 'trx-auto-dealer' ) );
	}

	public function renderCurrencySymbol(): void {
		$settings = AdminSettings::getSettings();
		printf(
			'<input type="text" name="%s[currency_symbol]" id="trx_ad_currency_symbol" value="%s" class="small-text" maxlength="5">'
			. '<p class="description">%s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			esc_attr( (string) ( $settings['currency_symbol'] ?? '$' ) ),
			esc_html__( 'Currency symbol displayed with prices (e.g. $, EUR, GBP).', 'trx-auto-dealer' )
		);
	}

	public function renderCurrencyCode(): void {
		$settings = AdminSettings::getSettings();
		printf(
			'<input type="text" name="%s[currency_code]" id="trx_ad_currency_code" value="%s" class="small-text" maxlength="3" pattern="[A-Za-z]{3}" style="text-transform:uppercase;">'
			. '<p class="description">%s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			esc_attr( (string) ( $settings['currency_code'] ?? 'USD' ) ),
			esc_html__( '3-letter ISO 4217 code used in schema.org Offer markup and exports (USD, EUR, GBP, etc.). The symbol above is what visitors see; the code is for machines.', 'trx-auto-dealer' )
		);
	}

	public function renderDefaultSort(): void {
		$settings = AdminSettings::getSettings();
		$current  = (string) ( $settings['default_sort'] ?? 'newest' );
		$options  = array(
			'newest'     => __( 'Newest first', 'trx-auto-dealer' ),
			'price_asc'  => __( 'Price: low to high', 'trx-auto-dealer' ),
			'price_desc' => __( 'Price: high to low', 'trx-auto-dealer' ),
			'year_desc'  => __( 'Year: newest first', 'trx-auto-dealer' ),
		);
		printf( '<select name="%s[default_sort]" id="trx_ad_default_sort">', esc_attr( AdminSettings::OPTION_KEY ) );
		foreach ( $options as $value => $label ) {
			printf(
				'<option value="%s"%s>%s</option>',
				esc_attr( $value ),
				selected( $current, $value, false ),
				esc_html( $label )
			);
		}
		echo '</select>';
		printf( '<p class="description">%s</p>', esc_html__( 'Order used on the inventory archive when the visitor has not chosen a sort.', 'trx-auto-dealer' ) );
	}

	public function renderDealerCanPublish(): void {
		$settings = AdminSettings::getSettings();
		$enabled  = ! empty( $settings['dealer_can_publish'] );
		printf(
			'<label><input type="checkbox" name="%1$s[dealer_can_publish]" value="1"%2$s> %3$s</label>'
			. '<p class="description">%4$s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			checked( $enabled, true, false ),
			esc_html__( 'Allow dealer-role users to publish their own listings without admin approval.', 'trx-auto-dealer' ),
			esc_html__( 'Off by default — new dealer-created listings stay in Pending status until an administrator publishes them. Turn on to let dealers publish directly.', 'trx-auto-dealer' )
		);
	}

	public function renderAllowSvgUploads(): void {
		$settings = AdminSettings::getSettings();
		$enabled  = ! empty( $settings['allow_svg_uploads'] );
		printf(
			'<label><input type="checkbox" name="%1$s[allow_svg_uploads]" value="1"%2$s> %3$s</label>'
			. '<p class="description">%4$s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			checked( $enabled, true, false ),
			esc_html__( 'Allow administrators to upload SVG files to the media library (e.g. custom taxonomy icons).', 'trx-auto-dealer' ),
			esc_html__( 'Off by default. Only administrators can upload; every SVG is scanned on upload and rejected if it contains scripts, event handlers, or external references.', 'trx-auto-dealer' )
		);
	}

	public function renderDealerProfileRequiresReview(): void {
		$settings = AdminSettings::getSettings();
		$enabled  = ! empty( $settings['dealer_profile_requires_review'] );
		printf(
			'<label><input type="checkbox" name="%1$s[dealer_profile_requires_review]" value="1"%2$s> %3$s</label>'
			. '<p class="description">%4$s</p>',
			esc_attr( AdminSettings::OPTION_KEY ),
			checked( $enabled, true, false ),
			esc_html__( 'Require admin review when a dealer updates their own profile.', 'trx-auto-dealer' ),
			esc_html__( 'Off by default — dealers update their profile directly. Turn on to force every save by a dealer to Pending status; an administrator must republish before the changes go live.', 'trx-auto-dealer' )
		);
	}
}
