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

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

class RoleFrontendSubmitRestrictor extends AbstractRestrictor {

	protected function _frontendsubmitRestrictorInfo() {
		return array(
			'label' => __( 'Restrict by WordPress user role', 'directories-pro' ),
		);
	}

	protected function _getRestrictionGroups() {
		$roles            = $this->_application->getPlatform()->getRoles();
		$roles['_guest_'] = '— ' . __( 'Guest', 'directories-pro' ) . ' —';
		return $roles;
	}

	protected function _getRestrictionGroupsByUser( $userId, $settings ) {
		if ( empty( $userId ) ) {
			return array( '_guest_' );
		}

		if ( false === $roles = $this->_application->getPlatform()->getRoles( $userId ) ) {
			throw new RuntimeException( 'Failed fetching user data for user ID:' . $userId );
		}
		return $roles;
	}

	protected function _getRestrictorSettingsForm( $group, array $bundles, array $settings ) {
		$form        = parent::_getRestrictorSettingsForm( $group, $bundles, $settings );
		$admin_roles = $this->_application->getPlatform()->getAdministratorRoles();
		if ( isset( $admin_roles[ $group ] ) ) {
			unset( $form['limit'] );
		} else {
			foreach ( array_keys( $bundles ) as $bundle_name ) {
				// Check submission perm
				$perm = 'entity_create_' . $bundle_name;
				if ( $group !== '_guest_' ) {
					if ( get_role( $group )->has_cap( 'drts_' . $perm ) ) {
						continue;
					}
				} elseif ( $this->_application->getPlatform()->guestHasPermission( $perm ) ) {
						continue;
				}
				$form['limit'][ $bundle_name ]['#disabled'] = true;
			}
		}
		return $form;
	}

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