<?php

namespace FKWCSQ\Admin;

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

/**
 * Onboarding Class for Square Payment Gateway
 */
class Onboard {
	private static $instance = null;

	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	private function __construct() {
		if ( ! is_admin() || ! current_user_can( 'manage_options' ) ) {
			return;
		}

		add_action( 'init', array( $this, 'init_onboarding' ) );
	}

	/**
	 * Initialize onboarding on init hook
	 */
	public function init_onboarding() {
		add_action( 'admin_notices', array( $this, 'show_onboarding_notice' ) );
		add_action( 'admin_init', array( $this, 'handle_skip_setup' ) );
	}

	/**
	 * Handle skip setup action
	 */
	public function handle_skip_setup() {
		if ( isset( $_GET['fkwcsq-hide-notice'] ) && isset( $_GET['_fkwcsq_notice_nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['_fkwcsq_notice_nonce'] ) ), 'fkwcsq_hide_notices_nonce' ) ) {
			update_option( 'fkwcsq_setup_status', 'skipped' );
			wp_redirect( remove_query_arg( array( 'fkwcsq-hide-notice', '_fkwcsq_notice_nonce' ) ) );
			exit;
		}
	}

	/**
	 * Check if Square is connected
	 *
	 * @return bool
	 */
	public function is_square_connected() {
		return \FKWCSQ\Square::is_configured();
	}

	/**
	 * Show onboarding notice when Square is not connected for the allowed screens
	 */
	public function show_onboarding_notice() {
		$screen          = get_current_screen();
		$screen_id       = $screen ? $screen->id : '';
		$allowed_screens = array(
			'woocommerce_page_wc-settings',
			'dashboard',
			'plugins',
		);

		if ( ! in_array( $screen_id, $allowed_screens, true ) || $this->is_square_connected() === true ) {
			return;
		}

		$status = get_option( 'fkwcsq_setup_status', false );
		if ( empty( $status ) ) {
			$middleware     = \FKWCSQ\Includes\Modules\Connection\MiddleWare::get_instance();
			$connection_url = $middleware->get_connection_url();

			?>
			<div class="notice notice-info wcf-notice">
				<p><b><?php esc_html_e( 'Thanks for installing Square Payment Gateway for WooCommerce!', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></b></p>
				<p><?php esc_html_e( 'Connect your Square account to start accepting payments.', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></p>
				<p>
					<a href="<?php echo esc_url( $connection_url ); ?>" class="button button-primary"><?php esc_html_e( 'Connect Square Account', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></a>
					<a class="button-secondary" href="<?php echo esc_url( wp_nonce_url( add_query_arg( 'fkwcsq-hide-notice', 'install' ), 'fkwcsq_hide_notices_nonce', '_fkwcsq_notice_nonce' ) ); ?>"><?php esc_html_e( 'Skip Setup', 'funnelkit-payment-gateway-square-for-woocommerce' ); ?></a>
				</p>
			</div>
			<?php
		}
	}

	/**
	 * Check if re-authentication is required for the current site
	 *
	 * Re-authentication is required when:
	 * - Square is connected (has valid tokens)
	 * - AND either:
	 *   a) The connection timestamp option doesn't exist (old site before tracking)
	 *   b) If cutoff_timestamp is provided: connection timestamp is before the cutoff date
	 *
	 * This helps identify sites that need to re-authenticate for version-specific features
	 *
	 * @param int|null $cutoff_timestamp Optional. Unix timestamp cutoff date. Connections before this date require re-auth.
	 *                                   If null (default), only checks if timestamp exists.
	 *                                   If provided, also checks if connection was before the cutoff date.
	 * @return bool True if re-authentication is required, false otherwise
	 */
	public static function is_reauthentication_required( $cutoff_timestamp = null ) {
		// Check if Square is connected
		if ( ! \FKWCSQ\Square::is_configured() ) {
			return false;
		}

		// Check if connection timestamp exists
		$connection_timestamp = get_option( 'fkwcsq_connection_timestamp', false );

		// If timestamp doesn't exist, re-authentication is required
		if ( false === $connection_timestamp ) {
			return true;
		}

		// If no cutoff timestamp provided, only check existence (already passed above)
		if ( null === $cutoff_timestamp ) {
			return false;
		}

		// Check if connection was made before the cutoff date
		return (int) $connection_timestamp < (int) $cutoff_timestamp;
	}
}
