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

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

class MemberPressFrontendSubmitRestrictor extends AbstractRestrictor {

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

	public function frontendsubmitRestrictorEnabled() {
		return defined( 'MEPR_VERSION' );
	}

	protected function _getRestrictionGroups() {
		$memberships = array();
		foreach ( \MeprProduct::get_all() as $membership ) {
			$memberships[ $membership->post_name ] = $membership->post_title;
		}
		$memberships[0] = '— ' . __( 'No membership', 'directories-pro' ) . ' —';
		return $memberships;
	}

	protected function _getRestrictionGroupsByUser( $userId, $settings ) {
		if ( empty( $userId )
			|| ( ! $memberships = ( new \MeprUser( $userId ) )->active_product_subscriptions( 'products' ) )
		) {
			return array( 0 );
		}

		$ret = array();
		foreach ( $memberships as $membership ) {
			$ret[] = $membership->post_name;
		}
		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;
	}
}
