<?php
/**
 * Card Payment Block
 *
 * @package FunnelKit_Square
 * @subpackage Blocks
 */

namespace FKWCSQ\Includes\Blocks;

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

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

/**
 * Card_Block class.
 *
 * Handles Card payment method registration for WooCommerce Blocks.
 */
class Card_Block extends AbstractPaymentMethodType {

	/**
	 * Payment method name.
	 *
	 * @var string
	 */
	protected $name = 'fkwcsq_square';

	/**
	 * Gateway settings.
	 *
	 * @var array
	 */
	protected $settings;

	/**
	 * Initialize the block.
	 *
	 * @return void
	 */
	public function initialize() {
		$this->settings = get_option( 'woocommerce_fkwcsq_square_settings', array() );
	}

	/**
	 * Check if the payment method is active.
	 *
	 * @return bool
	 */
	public function is_active() {
		return isset( $this->settings['enabled'] ) && 'yes' === $this->settings['enabled'];
	}

	/**
	 * Get script handles for the payment method.
	 *
	 * @return array
	 */
	public function get_payment_method_script_handles() {
		$asset_path = FKWCSQ_ABSPATH . 'build/index.asset.php';
		$version    = FKWCSQ_VERSION;
		$deps       = array();

		if ( file_exists( $asset_path ) ) {
			$asset   = require $asset_path;
			$version = isset( $asset['version'] ) ? $asset['version'] : $version;
			$deps    = isset( $asset['dependencies'] ) ? $asset['dependencies'] : $deps;
		}

		// Register Square SDK.
		wp_register_script(
			'square-web-sdk',
			Square::get_web_sdk_url(),
			array(),
			null, // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- External SDK versioned by Square
			true
		);

		// Register our blocks script.
		wp_register_script(
			'fkwcsq-blocks-integration',
			FKWCSQ_PLUGIN_URL . 'build/index.js',
			array_merge( $deps, array( 'square-web-sdk' ) ),
			$version,
			true
		);

		return array( 'fkwcsq-blocks-integration' );
	}

	/**
	 * Get the gateway supports array.
	 *
	 * @return array
	 */
	private function get_gateway_supports() {
		$gateways = WC()->payment_gateways()->payment_gateways();
		if ( isset( $gateways[ $this->name ] ) ) {
			return $gateways[ $this->name ]->supports;
		}
		return array( 'products', 'refunds', 'tokenization' );
	}

	/**
	 * Check if cart contains a subscription.
	 *
	 * @return bool
	 */
	private function cart_contains_subscription() {
		if ( class_exists( 'WC_Subscriptions_Cart' ) && method_exists( 'WC_Subscriptions_Cart', 'cart_contains_subscription' ) ) {
			return \WC_Subscriptions_Cart::cart_contains_subscription();
		}
		return false;
	}

	/**
	 * Check if tokenization is enabled.
	 *
	 * @return bool
	 */
	private function is_tokenization_enabled() {
		return isset( $this->settings['tokenization'] ) && 'yes' === $this->settings['tokenization'];
	}

	/**
	 * Get payment method data to pass to JavaScript.
	 *
	 * @return array
	 */
	public function get_payment_method_data() {
		$api = \FKWCSQ\Includes\API::get_instance();

		// Get cart total in smallest currency unit (cents) for SCA/3DS verification.
		$amount   = '0';
		$currency = get_woocommerce_currency();
		if ( WC()->cart ) {
			// Convert to cents (smallest currency unit).
			$cart_total = WC()->cart->get_total( 'edit' );
			$amount     = strval( round( floatval( $cart_total ) * 100 ) );
		}

		// Determine saved cards visibility.
		$tokenization_enabled = $this->is_tokenization_enabled();
		$is_logged_in         = is_user_logged_in();
		$has_subscription     = $this->cart_contains_subscription();
		$show_saved_cards     = $tokenization_enabled && $is_logged_in;
		$show_save_option     = $tokenization_enabled && $is_logged_in && ! $has_subscription;

		$data = array(
			'title'            => $this->settings['title'] ?? __( 'Credit Card', 'funnelkit-payment-gateway-square-for-woocommerce' ),
			'description'      => $this->settings['description'] ?? '',
			'supports'         => $this->get_gateway_supports(),
			'application_id'   => Square::get_application_id(),
			'location_id'      => $api->get_location_id(),
			'is_sandbox'       => Square::is_sandbox_mode(),
			'enabled'          => $this->is_active(),
			'amount'           => $amount,
			'currency'         => $currency,
			'show_saved_cards' => $show_saved_cards,
			'show_save_option' => $show_save_option,
		);

		// Add test card info when in sandbox mode.
		if ( Square::is_sandbox_mode() ) {
			$data['test_card_info'] = array(
				'message'   => __( 'Test Mode Enabled: Use demo card 4111111111111111 with any future date and CVV.', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'link_text' => __( 'Check more demo cards', 'funnelkit-payment-gateway-square-for-woocommerce' ),
				'link_url'  => 'https://developer.squareup.com/docs/devtools/sandbox/payments',
			);
		}

		return $data;
	}
}
