<?php

final class ITSEC_Malware_Scheduling_Validator extends ITSEC_Validator {
	private $valid_contacts;


	public function get_id() {
		return 'malware-scheduling';
	}

	protected function sanitize_settings() {
		$this->sanitize_setting( 'bool', 'email_notifications', __( 'Email Notifications', 'it-l10n-ithemes-security-pro' ) );

		if ( $this->sanitize_setting( 'array', 'email_contacts', __( 'Email Contacts', 'it-l10n-ithemes-security-pro' ) ) ) {
			$users_and_roles = $this->get_available_admin_users_and_roles();
			$users = array_keys( $users_and_roles['users'] );
			$roles = array_keys( $users_and_roles['roles'] );

			$this->valid_contacts = array_merge( $users, $roles );

			$this->sanitize_setting( array( $this, 'get_validated_contact' ), 'email_contacts', __( 'Email Contacts', 'it-l10n-ithemes-security-pro' ) );
		}
	}

	public function get_validated_contact( $contact ) {
		if ( in_array( $contact, $this->valid_contacts ) ) {
			return $contact;
		}

		return false;
	}

	public function get_available_admin_users_and_roles() {
		if ( is_callable( 'wp_roles' ) ) {
			$roles = wp_roles();
		} else {
			$roles = new WP_Roles();
		}

		$available_roles = array();
		$available_users = array();

		foreach ( $roles->roles as $role => $details ) {
			if ( isset( $details['capabilities']['manage_options'] ) && ( true === $details['capabilities']['manage_options'] ) ) {
				$available_roles["role:$role"] = translate_user_role( $details['name'] );

				$users = get_users( array( 'role' => $role ) );

				foreach ( $users as $user ) {
					/* translators: 1: user display name, 2: user login */
					$available_users[$user->ID] = sprintf( __( '%1$s (%2$s)', 'it-l10n-ithemes-security-pro' ), $user->display_name, $user->user_login );
				}
			}
		}

		natcasesort( $available_users );

		return array(
			'users' => $available_users,
			'roles' => $available_roles,
		);
	}
}

ITSEC_Modules::register_validator( new ITSEC_Malware_Scheduling_Validator() );
