<?php
/**
 * Admin settings page under Settings → Capsquery Facial Authentication.
 */

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

class Capsq_Admin {

	public function __construct() {
		add_action( 'admin_menu', array( $this, 'register_menu' ) );
		add_action( 'admin_init', array( $this, 'register_settings' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) );
	}

	public function register_menu() {
		add_menu_page(
	        __( 'Capsquery Facial Authentication', 'capsquery-facial-authentication' ),       // Page title
	        __( 'Capsquery Facial Authentication', 'capsquery-facial-authentication' ),       // Menu title
	        'manage_options',                       // Capability
	        'capsquery-facial-authentication',      // Menu slug
	        array( $this, 'render_page' ),          // Callback
	        'dashicons-smiley',  					// Icon (change if you prefer)
	        60                                      // Position
	    );
	}

	public function register_settings() {
		register_setting(
			'capsq_settings_group',
			Capsq_Helpers::OPTION_ENABLED,
			array(
				'type'              => 'boolean',
				'sanitize_callback' => array( $this, 'sanitize_bool' ),
				'default'           => true,
			)
		);

		register_setting(
			'capsq_settings_group',
			Capsq_Helpers::OPTION_THRESHOLD,
			array(
				'sanitize_callback' => array( $this, 'sanitize_threshold' ),
			)
		);


		add_settings_section(
			'capsq_general_section',
			__( 'General', 'capsquery-facial-authentication' ),
			array( $this, 'render_general_section' ),
			'capsquery-facial-authentication'
		);

		add_settings_field(
			'capsq_enabled',
			__( 'Enable Capsquery Facial Authentication', 'capsquery-facial-authentication' ),
			array( $this, 'render_enabled_field' ),
			'capsquery-facial-authentication',
			'capsq_general_section'
		);

		add_settings_field(
			'capsq_match_threshold',
			__( 'Match sensitivity', 'capsquery-facial-authentication' ),
			array( $this, 'render_threshold_field' ),
			'capsquery-facial-authentication',
			'capsq_general_section'
		);
	}

	public function sanitize_bool( $value ) {
		return ! empty( $value );
	}

	public function sanitize_threshold( $value ) {
		$allowed = array( '0.41', '0.45', '0.55' );

		if ( ! in_array( (string) $value, $allowed, true ) ) {
			return '0.55';
		}

		return $value;
	}

	public function enqueue_admin_styles( $hook ) {
		if ( 'settings_page_capsquery-facial-authentication' !== $hook ) {
			return;
		}
		wp_enqueue_style(
			'capsq-admin',
			CAPSQ_PLUGIN_URL . 'assets/css/capsq-admin.css',
			array(),
			capsq_asset_version( 'assets/css/capsq-admin.css' )
		);
	}

	public function render_general_section() {
		echo '<p>' . esc_html__( 'Configure Capsquery Facial Authentication for your site.', 'capsquery-facial-authentication' ) . '</p>';
	}

	public function render_enabled_field() {
		$enabled = Capsq_Helpers::is_enabled();
		?>
		<input type="hidden" name="<?php echo esc_attr( Capsq_Helpers::OPTION_ENABLED ); ?>" value="0" />
		<label>
			<input type="checkbox" name="<?php echo esc_attr( Capsq_Helpers::OPTION_ENABLED ); ?>" value="1" <?php checked( $enabled ); ?> />
			<?php esc_html_e( 'Allow face recognition login on wp-login.php and via the [capsquery_facial_authentication] shortcode.', 'capsquery-facial-authentication' ); ?>
		</label>
		<?php
	}

	public function render_threshold_field() {
		$current = (string) Capsq_Helpers::get_threshold();
		
		$options = array(
			'0.41' => __( 'High (Strict)', 'capsquery-facial-authentication' ),
			'0.45' => __( 'Moderate', 'capsquery-facial-authentication' ),
			'0.55' => __( 'Relaxed', 'capsquery-facial-authentication' ),
		);
		?>

		<select name="<?php echo esc_attr( Capsq_Helpers::OPTION_THRESHOLD ); ?>">
			<?php foreach ( $options as $value => $label ) : ?>
				<option value="<?php echo esc_attr( $value ); ?>" <?php selected( $current, $value ); ?>>
					<?php echo esc_html( $label ); ?>
				</option>
			<?php endforeach; ?>
		</select>

		<p class="description">
			<?php esc_html_e( 'Choose how strict face matching should be. Higher sensitivity is more secure but may require more consistent lighting and positioning.', 'capsquery-facial-authentication' ); ?>
		</p>

		<?php
	}
	

	public function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}

		if ( isset( $_POST['capsq_delete_all_data'] ) && check_admin_referer( 'capsq_delete_all_data' ) ) {
			$this->delete_all_face_data();
			add_settings_error( 'capsq_settings', 'capsq_data_deleted', __( 'All facial authentication data has been removed.', 'capsquery-facial-authentication' ), 'updated' );
		}

		$enrolled_count = $this->count_enrolled_users();
		?>
		<div class="wrap capsq-admin-wrap">
			<h1><?php esc_html_e( 'Capsquery Facial Authentication Settings', 'capsquery-facial-authentication' ); ?></h1>

			<?php settings_errors( 'capsq_settings' ); ?>

			<div class="capsq-admin-pro-banner">
				<h2>Available Shortcode: [capsquery_facial_authentication]</h2>
				 
				<span>
					<p>Usage:</p>
					<ol>
				 		<li>[capsquery_facial_authentication] - Basic Shortcode</li>
				 		<li>[capsquery_facial_authentication redirect="https://example.com/dashboard"] - Shortcode with login Redirect Url</li>
				 		<li>[capsquery_facial_authentication button_label="Sign in with Face"] - Login Button text change option</li>
				 	</ol>
				</span>
 
			</div> 

			<form method="post" action="options.php">
				<?php
					settings_fields( 'capsq_settings_group' );
					do_settings_sections( 'capsquery-facial-authentication' );
					submit_button();
				?>
			</form>

			<hr />

			<h2><?php esc_html_e( 'Data management', 'capsquery-facial-authentication' ); ?></h2>
			<p>
				<?php
				printf(
					/* translators: %d: number of enrolled users */
					esc_html__( 'Currently enrolled: %d user(s).', 'capsquery-facial-authentication' ),
					(int) $enrolled_count
				);
				?>
			</p>
			<form method="post" onsubmit="return confirm('<?php echo esc_js( __( 'Delete all enrolled face data and PINs? This cannot be undone.', 'capsquery-facial-authentication' ) ); ?>');">
				<?php wp_nonce_field( 'capsq_delete_all_data' ); ?>
				<input type="hidden" name="capsq_delete_all_data" value="1" />
				<?php submit_button( __( 'Delete all facial authentication data', 'capsquery-facial-authentication' ), 'delete', 'submit', false ); ?>
			</form>
		</div>
		<?php
	}

	private function count_enrolled_users() {
		$count = wp_cache_get( 'capsq_enrolled_count', 'capsq' );

		if ( false === $count ) {
			global $wpdb;
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- no core API for a distinct-user count by meta_key; result is cached below.
			$count = (int) $wpdb->get_var(
				$wpdb->prepare(
					"SELECT COUNT(DISTINCT user_id) FROM {$wpdb->usermeta} WHERE meta_key = %s",
					'_capsq_face_descriptor'
				)
			);
			wp_cache_set( 'capsq_enrolled_count', $count, 'capsq', HOUR_IN_SECONDS );
		}

		return (int) $count;
	}

	private function delete_all_face_data() {
		global $wpdb;

		$wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$wpdb->usermeta} WHERE meta_key IN (%s, %s)",
				'_capsq_face_descriptor',
				'_capsq_pin_hash'
			)
		);
		wp_cache_delete( 'capsq_all_descriptors', 'capsq' );
		wp_cache_delete( 'capsq_enrolled_count', 'capsq' );
	}
}