<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Woocommerce paychef payment gateway
 *
 * @package woo-paychef-gateway
 */

use Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType;
use PaychefPaymentGateway\Helper\SubscriptionHelper;

/**
 * WC_Paychef_Block_Base
 */
class PayChef_Gateway_Block_Base extends AbstractPaymentMethodType {

	/**
	 * Initializes the payment method type.
	 */
	public function initialize() {
		$this->settings = get_option( 'woocommerce_' . $this->name . '_settings', array() );
	}

	/**
	 * Returns if this payment method should be active. If false, the scripts will not be enqueued.
	 *
	 * @return boolean
	 */
	public function is_active() {
		return filter_var( $this->get_setting( 'enabled', false ), FILTER_VALIDATE_BOOLEAN );
	}

	/**
	 * Returns an array of scripts/handles to be registered for this payment method.
	 *
	 * @return array
	 */
	public function get_payment_method_script_handles() {
		$handle = 'paychef-blocks-payment-method-integration';
		$deps   = array(
			'wc-blocks-registry',
			'wc-settings',
			'wp-element',
			'wp-html-entities',
			'wp-i18n',
		);
		wp_register_script(
			$handle,
			plugins_url( 'assets/blocks/payment-method.js', PAYCHEF_MAIN_FILE ),
			$deps,
			true,
			true
		);
		if ( function_exists( 'wp_set_script_translations' ) ) {
			wp_set_script_translations( $handle );
		}
		return array( $handle );
	}

	/**
	 * Returns an array of key=>value pairs of data made available to the payment methods script.
	 *
	 * @return array
	 */
	public function get_payment_method_data() {
		$description = wp_kses_post( $this->settings['description'] );
		$supports    = $this->get_supported_features();
		if ( isset( $this->settings['subscriptions_enabled'] )
		     && 'yes' === $this->settings['subscriptions_enabled']
		     && SubscriptionHelper::isSubscription( WC()->cart )
		) {
			$supports     = array_merge(
				$supports,
				SubscriptionHelper::get_supported_features()
			);
			$description .= $this->get_subscription_checkbox();
		}

		$data = array(
			'title'       => $this->get_setting( 'title' ),
			'description' => $description,
			'supports'    => $supports,
			'icon'        => $this->get_payment_logo(),
		);

		// Add tokenization data for logged in users
		if (is_user_logged_in() && in_array('tokenization', $supports)) {
			$data['saved_tokens'] = $this->get_saved_payment_methods();
			$data['show_save_payment_method'] = !$this->is_subscription_or_renewal_order();
			$data['gateway_id'] = $this->name;
		}

		return $data;
	}

	/**
	 * Get subscription checkbox
	 */
	private function get_subscription_checkbox():string {
		$name       = esc_attr( 'paychef-allow-recurring-' . $this->name );
		$label_text = wp_kses_post( $this->settings['subscriptions_user_desc'] ?? '' );

		return sprintf(
			'<br/>
			<label for="%s">
				<input type="checkbox" checked="checked" name="%s" id="%s" value="1" />
				%s
			</label>
			',
			$name,
			$name,
			$name,
			$label_text
		);
	}

	/**
	 * Get payment logo
	 */
	private function get_payment_logo():string {
		$pm   = str_replace( PAYCHEF_PM_PREFIX, '', $this->name );
		$pm   = ( 'paychef' === $pm ? '' : $pm );
		$icon = '';
		if ( $pm ) {
			$icon_name = str_replace( '-', '_', $pm );
			$src = WC_HTTPS::force_https_url(
				plugins_url( 'includes/cardicons/card_' . $icon_name . '.svg', PAYCHEF_MAIN_FILE )
			);
			return '<img src="' . $src . '" alt="' . $pm . '" id="paychef-' . $pm . '"/>';
		} else {
			$subscription_logos = $this->settings['subscription_logos'] ?? array();
			$logos              = $this->settings['logos'] ?? array();
			if ( $logos && $subscription_logos ) {
				$logos = SubscriptionHelper::isSubscription( WC()->cart ) ? $subscription_logos : $logos;
				$icon  = '';
				foreach ( $logos as $logo ) {
					$icon_name = str_replace( '-', '_', $logo );
					$src   = WC_HTTPS::force_https_url(
						plugins_url( 'includes/cardicons/card_' . $icon_name . '.svg', PAYCHEF_MAIN_FILE )
					);
					$icon .= '<img src="' . $src . '" alt="' . $logo . '" id="paychef-' . $logo . '"/>';
				}
			}
		}
		return $icon;
	}

	/**
	 * Get supported features for this payment method
	 *
	 * @return array
	 */
	public function get_supported_features() {
		$features = array('products');
		
		// Add tokenization support for logged in users
		if (is_user_logged_in()) {
			$features[] = 'tokenization';
		}
		
		return $features;
	}

	/**
	 * Get saved payment methods for current user
	 *
	 * @return array
	 */
	private function get_saved_payment_methods() {
		if (!is_user_logged_in()) {
			return array();
		}

		$tokens = WC_Payment_Tokens::get_customer_tokens(get_current_user_id(), $this->name);
		$saved_methods = array();

		foreach ($tokens as $token) {
			if ($token instanceof WC_Payment_Token_CC) {
				$saved_methods[] = array(
					'id' => $token->get_id(),
					'display_name' => sprintf('**** %s', $token->get_last4()),
					'card_type' => $token->get_card_type(),
					'expiry_month' => $token->get_expiry_month(),
					'expiry_year' => $token->get_expiry_year(),
				);
			}
		}

		return $saved_methods;
	}

	/**
	 * Check if this is a subscription or renewal order
	 */
	private function is_subscription_or_renewal_order() {
		if (!class_exists('WC_Subscriptions_Cart')) {
			return false;
		}
		
		return WC_Subscriptions_Cart::cart_contains_subscription() || 
			   (function_exists('wcs_cart_contains_renewal') && wcs_cart_contains_renewal());
	}

}
