<?php
namespace SabaiApps\Directories\Component\WordPressContent\FrontendSubmitRestrictor;

use SabaiApps\Directories\Component\FrontendSubmit\Restrictor\AbstractRestrictor;

class WooCommerceMembershipsFrontendSubmitRestrictor extends AbstractRestrictor {

	protected function _frontendsubmitRestrictorInfo() {
		return array(
			'label'            => __( 'Restrict by WooCommerce Memberships membership plan', 'directories-pro' ),
			'default_settings' => array(),
		);
	}

	public function frontendsubmitRestrictorEnabled() {
		return function_exists( 'wc_memberships' );
	}

	protected function _getRestrictionGroups() {
		$memberships = array();
		foreach ( wc_memberships_get_membership_plans() as $membership ) {
			$memberships[ $membership->get_slug() ] = $membership->get_name();
		}
		$memberships[0] = '— ' . __( 'No membership', 'directories-pro' ) . ' —';
		return $memberships;
	}

	protected function _getRestrictionGroupsByUser( $userId, $settings ) {
		if ( empty( $userId )
			|| ( ! $memberships = wc_memberships_get_user_active_memberships() )
		) {
			return array( 0 );
		}

		$ret = array();
		foreach ( $memberships as $membership ) {
			$ret[] = $membership->get_plan()->get_slug();
		}
		return $ret;
	}

	protected function _maybeFixRestrictorSettings( array $settings ) {
		foreach ( array_keys( $settings ) as $membership ) {
			if ( ! isset( $settings[ $membership ]['limit'] ) ) {
				$settings[ $membership ]['limit'] = $settings[ $membership ];
			}
		}
		return $settings;
	}
}
