<?php
/**
 * PeachPay NMI payment integration admin settings.
 *
 * @package PeachPay
 */

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

/**
 * NMI Admin Integration class.
 * 
 * Handles the admin settings page for NMI payment gateway configuration.
 * NMI requires only two keys:
 * - Private Key (Security Key): For server-side API calls
 * - Public Tokenization Key: For Collect.js client-side tokenization
 */
final class PeachPay_Admin_NMI_Integration {

	/**
	 * Singleton instance.
	 *
	 * @var PeachPay_Admin_NMI_Integration|null
	 */
	private static $instance = null;

	/**
	 * Get singleton instance.
	 *
	 * @return PeachPay_Admin_NMI_Integration
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
			self::$instance->init();
		}
		return self::$instance;
	}

	/**
	 * Initialize admin hooks.
	 */
	private function init() {
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) );
		
		// AJAX handlers
		add_action( 'wp_ajax_peachpay_nmi_connect', array( $this, 'handle_nmi_connect' ) );
		add_action( 'wp_ajax_peachpay_nmi_disconnect', array( $this, 'handle_nmi_disconnect' ) );
		add_action( 'wp_ajax_save_nmi_gateway_settings', array( $this, 'handle_save_gateway_settings' ) );
	}

	/**
	 * Enqueue admin scripts.
	 *
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_admin_scripts( $hook ) {
		$current_page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$current_tab  = isset( $_GET['tab'] ) ? sanitize_text_field( wp_unslash( $_GET['tab'] ) ) : '';

		if ( 'peachpay' === $current_page && 'payment' === $current_tab ) {
			wp_enqueue_script( 'jquery' );
		}
	}

	/**
	 * Display the admin page content.
	 *
	 * @param array $args Optional arguments.
	 */
	public static function do_admin_page( $args = array() ) {
		?>
		<div id="nmi" class="peachpay-setting-section">
			<?php require PeachPay::get_plugin_path() . '/core/payments/nmi/admin/views/html-nmi-connect.php'; ?>
			
			<?php if ( peachpay_nmi_connected() ) : ?>
				<div>
					<?php
					if ( ! class_exists( 'WC_Payment_Gateway' ) || ! function_exists( 'WC' ) ) {
						echo '<div class="notice notice-error"><p>';
						esc_html_e( 'WooCommerce is not fully loaded. Please refresh the page.', 'peachpay-for-woocommerce' );
						echo '</p></div>';
					} else {
						$gateway_list = PeachPay_NMI_Integration::get_payment_gateways();
						if ( ! empty( $gateway_list ) && is_array( $gateway_list ) ) {
							require PeachPay::get_plugin_path() . '/core/admin/views/html-gateways.php';
						}
					}
					?>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Handle NMI connection.
	 * 
	 * For NMI, "connecting" simply means saving the API keys.
	 * Unlike ConvesioPay, there's no external API to call for connection.
	 */
	public function handle_nmi_connect() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Insufficient permissions', 'peachpay-for-woocommerce' ) );
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'peachpay_nmi_connect' ) ) {
			wp_send_json_error( __( 'Security check failed', 'peachpay-for-woocommerce' ) );
			return;
		}

		$public_tokenization_key = sanitize_text_field( wp_unslash( $_POST['public_tokenization_key'] ?? '' ) );
		$private_key             = sanitize_text_field( wp_unslash( $_POST['private_key'] ?? '' ) );

		// Validate keys
		if ( empty( $private_key ) ) {
			wp_send_json_error( __( 'Private Key (Security Key) is required.', 'peachpay-for-woocommerce' ) );
			return;
		}

		// Store NMI configuration
		$config = array(
			'private_key'             => $private_key,
			'public_tokenization_key' => $public_tokenization_key,
			'connected_at'            => current_time( 'mysql' ),
		);

		update_option( 'peachpay_connected_nmi_config', $config );

		// Auto-enable NMI card gateway
		$this->set_nmi_gateway_enabled( true );

		wp_send_json_success( __( 'NMI connected successfully!', 'peachpay-for-woocommerce' ) );
	}

	/**
	 * Handle NMI disconnection.
	 */
	public function handle_nmi_disconnect() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( __( 'Insufficient permissions', 'peachpay-for-woocommerce' ) );
			return;
		}

		if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ?? '' ) ), 'peachpay_nmi_disconnect' ) ) {
			wp_send_json_error( __( 'Security check failed', 'peachpay-for-woocommerce' ) );
			return;
		}

		// Delete configuration
		delete_option( 'peachpay_connected_nmi_config' );

		// Disable NMI gateway
		$this->set_nmi_gateway_enabled( false );

		wp_send_json_success( __( 'NMI disconnected successfully!', 'peachpay-for-woocommerce' ) );
	}

	/**
	 * Enable or disable NMI gateway.
	 *
	 * @param bool $enabled Whether to enable or disable.
	 */
	private function set_nmi_gateway_enabled( $enabled ) {
		$option_name      = 'woocommerce_peachpay_nmi_card_settings';
		$gateway_settings = get_option( $option_name, array() );

		$gateway_settings['enabled'] = $enabled ? 'yes' : 'no';

		update_option( $option_name, $gateway_settings );
	}

	/**
	 * Handle saving NMI gateway settings.
	 */
	public function handle_save_gateway_settings() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Insufficient permissions', 'peachpay-for-woocommerce' ) ) );
			return;
		}

		if ( ! isset( $_POST['nmi_gateway_settings_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nmi_gateway_settings_nonce'] ) ), 'nmi_gateway_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed', 'peachpay-for-woocommerce' ) ) );
			return;
		}

		if ( ! function_exists( 'WC' ) || ! WC()->payment_gateways ) {
			wp_send_json_error( array( 'message' => __( 'WooCommerce not available', 'peachpay-for-woocommerce' ) ) );
			return;
		}

		$gateways = WC()->payment_gateways->payment_gateways();
		$gateway  = $gateways['peachpay_nmi_card'] ?? null;

		if ( ! $gateway ) {
			wp_send_json_error( array( 'message' => __( 'NMI gateway not found', 'peachpay-for-woocommerce' ) ) );
			return;
		}

		$option_name = $gateway->get_option_key();
		$gateway->init_settings();
		$current_settings = $gateway->settings;

		// Update settings from POST
		if ( isset( $_POST['nmi_enabled'] ) ) {
			$current_settings['enabled'] = sanitize_text_field( wp_unslash( $_POST['nmi_enabled'] ) ) == 1 ? 'yes' : 'no';
		}

		if ( isset( $_POST['nmi_title'] ) ) {
			$current_settings['title'] = sanitize_text_field( wp_unslash( $_POST['nmi_title'] ) );
		}

		if ( isset( $_POST['nmi_description'] ) ) {
			$current_settings['description'] = sanitize_textarea_field( wp_unslash( $_POST['nmi_description'] ) );
		}

		if ( isset( $_POST['nmi_test_mode'] ) ) {
			$current_settings['test_mode'] = sanitize_text_field( wp_unslash( $_POST['nmi_test_mode'] ) ) === 'yes' ? 'yes' : 'no';
		}

		if ( isset( $_POST['nmi_capture_immediately'] ) ) {
			$current_settings['capture_immediately'] = sanitize_text_field( wp_unslash( $_POST['nmi_capture_immediately'] ) ) === 'yes' ? 'yes' : 'no';
		}

		// Gateway domain: sanitize (strip https://) and save
		if ( isset( $_POST['nmi_gateway_domain'] ) ) {
			$raw_domain = trim( sanitize_text_field( wp_unslash( $_POST['nmi_gateway_domain'] ) ) );
			if ( '' !== $raw_domain ) {
				$domain = PeachPay_NMI_Integration::sanitize_gateway_domain( $raw_domain );
				update_option( 'nmi_gateway_domain', $domain, true );
			} else {
				update_option( 'nmi_gateway_domain', '', true );
			}
		}

		if ( isset( $_POST['nmi_receipt'] ) ) {
			$current_settings['receipt'] = sanitize_text_field( wp_unslash( $_POST['nmi_receipt'] ) ) === 'yes' ? 'yes' : 'no';
		}

		// Private key: save submitted value (pre-filled in form; empty = clear). If not in POST, keep existing.
		if ( isset( $_POST['nmi_private_key'] ) ) {
			$current_settings['private_key'] = trim( sanitize_text_field( wp_unslash( $_POST['nmi_private_key'] ) ) );
		}

		// Public tokenization key: same logic.
		if ( isset( $_POST['nmi_public_tokenization_key'] ) ) {
			$current_settings['public_tokenization_key'] = trim( sanitize_text_field( wp_unslash( $_POST['nmi_public_tokenization_key'] ) ) );
		}

		// Save active API tab preference
		if ( isset( $_POST['nmi_active_api_tab'] ) ) {
			$tab = sanitize_text_field( wp_unslash( $_POST['nmi_active_api_tab'] ) );
			if ( in_array( $tab, array( 'collectjs', 'directapi' ), true ) ) {
				$current_settings['active_api_tab'] = $tab;
			}
		}

		// Save settings
		$settings_to_save = apply_filters( 'woocommerce_settings_api_sanitized_fields_' . $gateway->id, $current_settings );
		update_option( $option_name, $settings_to_save, 'yes' );

		// Update gateway instance
		$gateway->settings = $current_settings;
		
		if ( isset( $current_settings['enabled'] ) ) {
			$gateway->enabled = $current_settings['enabled'];
		}
		if ( isset( $current_settings['title'] ) ) {
			$gateway->title = $current_settings['title'];
		}
		if ( isset( $current_settings['description'] ) ) {
			$gateway->description = $current_settings['description'];
		}

		wp_send_json_success( array( 'message' => __( 'Settings saved successfully', 'peachpay-for-woocommerce' ) ) );
	}

	/**
	 * Get NMI configuration.
	 *
	 * @return array Configuration array.
	 */
	public static function get_config() {
		return get_option( 'peachpay_connected_nmi_config', array() );
	}
}
