<?php
/**
 * WooCommerce Blocks integration for FlexiLay gateway.
 *
 * This file MUST NOT fatal if Woo Blocks packages are unavailable (older WooCommerce versions,
 * or blocks plugin not installed). We guard all Blocks-only classes.
 */

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

if ( ! class_exists( '\Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType' ) ) {
	// Blocks not available; keep plugin activation safe.
	if ( ! class_exists( 'Flexilay_Blocks' ) ) {
		final class Flexilay_Blocks {
			public static function init() : void {
				// no-op
			}
		}
	}
	return;
}

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;

final class FlexiLay_Blocks_Payment_Method extends AbstractPaymentMethodType {

	/** @var string */
	protected $name = 'flexilay';

	/** @var array */
	protected $settings = [];

	public function initialize() {
		$this->settings = get_option( 'woocommerce_flexilay_settings', [] );
	}

	public function is_active() {
		$enabled = $this->settings['enabled'] ?? 'no';

		// Woo stores checkbox values differently across versions: 'yes', '1', 'on', true.
		if ( is_bool( $enabled ) ) {
			return $enabled;
		}
		$enabled = strtolower( (string) $enabled );
		return in_array( $enabled, [ 'yes', '1', 'on', 'true' ], true );
	}

	public function get_payment_method_script_handles() {
		$handle = 'flexilay-gateway-blocks';

		wp_register_script(
			$handle,
			plugins_url( '../assets/js/blocks.js', __FILE__ ),
			[ 'wc-blocks-registry', 'wc-settings', 'wp-element', 'wp-i18n' ],
			defined( 'FLEXILAY_WOO_PLUGIN_VERSION' ) ? FLEXILAY_WOO_PLUGIN_VERSION : null,
			true
		);

		return [ $handle ];
	}

	public function get_payment_method_data() {
		$title       = $this->settings['title'] ?? __( 'FlexiLay', 'flexilay-gateway-for-woocommerce' );
		$description = $this->settings['description'] ?? __( 'Choose your deposit and payment schedule with FlexiLay.', 'flexilay-gateway-for-woocommerce' );

		return [
			'title'       => $title,
			'description' => $description,
			'supports'    => [
				'features' => [ 'products' ],
			],
		];
	}
}

if ( ! class_exists( 'Flexilay_Blocks' ) ) {
	final class Flexilay_Blocks {
		public static function init() : void {
			add_action( 'woocommerce_blocks_loaded', [ __CLASS__, 'register_payment_method' ] );
		}

		public static function register_payment_method() : void {
			if ( ! class_exists( '\Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry' ) ) {
				return;
			}
			add_action(
				'woocommerce_blocks_payment_method_type_registration',
				function ( $payment_method_registry ) {
					try {
						$payment_method_registry->register( new FlexiLay_Blocks_Payment_Method() );
					} catch ( \Throwable $e ) {
						// Keep checkout resilient.
					}
				}
			);
		}
	}
}
