<?php
/**
 * Connection Limits Utility
 *
 * Handles connection limit validation for different plans.
 *
 * @package    MOMCS_Sync
 * @subpackage MOMCS_Sync/includes/common/utils
 * @author     miniOrange
 * @license    Expat
 * @link       https://miniorange.com
 * @since      1.0.0
 */

declare( strict_types=1 );

namespace MOMCS_Sync\Includes\Common\Utils;

use MOMCS_Sync\Includes\Common\Models\Multichannels_Model;

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

/**
 * Handles connection limit validation for different plans.
 */
class Connection_Limits {

	/**
	 * Check if user can add a new Amazon connection.
	 *
	 * @return array{can_add: bool, current_count: int, max_allowed: int, message: string}
	 */
	public static function can_add_amazon_connection(): array {
		$model                = new Multichannels_Model();
		$existing_connections = $model->get_channels_by_marketplace( 'amazon' );
		$current_count        = count( $existing_connections );

		$limits      = apply_filters( 'momcs_channel_limits', Utils::get_plan_limits() );
		$max_allowed = $limits['max_amazon_connections'] ?? 1;

		$can_add = $current_count < $max_allowed;

		$message = '';
		if ( ! $can_add ) {
			$message = sprintf(
				/* translators: %d: maximum number of connections allowed */
				__( 'You have reached the maximum limit of %d Amazon connection(s) for your plan. Upgrade to Premium for unlimited connections.', 'multi-channel-for-woocommerce' ),
				$max_allowed
			);
		}

		return array(
			'can_add'       => $can_add,
			'current_count' => $current_count,
			'max_allowed'   => $max_allowed,
			'message'       => $message,
		);
	}

	/**
	 * Get current connection stats for display.
	 *
	 * @return array{count: int, limit: int, is_unlimited: bool}
	 */
	public static function get_connection_stats(): array {
		$model                = new Multichannels_Model();
		$existing_connections = $model->get_channels_by_marketplace( 'amazon' );
		$count                = count( $existing_connections );

		$limits       = apply_filters( 'momcs_channel_limits', Utils::get_plan_limits() );
		$limit        = $limits['max_amazon_connections'] ?? 1;
		$is_unlimited = $limit >= PHP_INT_MAX;

		return array(
			'count'        => $count,
			'limit'        => $limit,
			'is_unlimited' => $is_unlimited,
		);
	}
}
