<?php
/**
 * Trait for shared security checks across Bankful payment gateways.
 *
 * @package Bankful
 */

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

/**
 * Shared HTTPS enforcement for Bankful gateway classes.
 */
trait Bankful_Security_Checks_Trait {

	/**
	 * Check if the gateway is available for use.
	 *
	 * Disables the gateway when the site is not running on a secure HTTPS connection.
	 * Allows CLI, Cron, and authenticated REST API contexts to bypass the check
	 * (e.g., subscription renewals).
	 *
	 * @return bool
	 */
	public function is_available() {
		// Allow payment processing in non-browser contexts (cron renewals, CLI, REST API).
		if ( ( defined( 'WP_CLI' ) && WP_CLI )
			|| ( defined( 'DOING_CRON' ) && DOING_CRON )
			|| ( defined( 'REST_REQUEST' ) && REST_REQUEST && is_user_logged_in() ) ) {
			return parent::is_available();
		}

		// Require secure connection for user-facing payment flows.
		if ( ! bankful_is_secure_connection() ) {
			return false;
		}

		return parent::is_available();
	}

	/**
	 * Enforce secure connection for payment processing.
	 *
	 * Call at the start of process_payment() to block insecure requests.
	 *
	 * @param int $order_id Order ID being processed.
	 * @return array|null Failure array if blocked, null to continue.
	 */
	protected function enforce_secure_connection( $order_id ) {
		if ( bankful_is_secure_connection() ) {
			return null;
		}

		static::log( 'Payment blocked for order ' . $order_id . ': insecure connection.', 'error' );

		wc_add_notice(
			__( 'Payment cannot be processed over an insecure (HTTP) connection. Please contact the store administrator to enable HTTPS.', 'bankful' ),
			'error'
		);

		return array( 'result' => 'failure' );
	}
}
