<?php
/**
 * Setup XProfile Component
 *
 * @package Nisje
 */

namespace Dekode\Nisje\Components;

defined( 'ABSPATH' ) || die( 'Shame on you' );

/**
 * XProfile Component Class
 */
class XProfile extends Component {
	/**
	 * Constructor
	 */
	public function __construct() {
		parent::start(
			'xprofile',
			__( 'Xprofile', 'nisje' )
		);
	}

	/**
	 * Setup filters
	 */
	public function setup_filters() {
		add_action( 'xprofile_field_after_sidebarbox', [ $this, 'admin_metabox' ] );
		add_action( 'xprofile_fields_saved_field', [ $this, 'update_setting' ] );
	}

	/**
	 * Register REST Endpoints
	 */
	public function register_rest_routes() {
		// Register Field Endpoints.
		nisje_include( 'includes/components/xprofile/rest-handlers/class-xprofile-fields-controller.php' );
		$controller = new \Dekode\Nisje\Components\Rest\XProfile_Fields_Controller();
		$controller->register_routes();

		// Register Group Endpoints.
		nisje_include( 'includes/components/xprofile/rest-handlers/class-xprofile-groups-controller.php' );
		$controller = new \Dekode\Nisje\Components\Rest\XProfile_Groups_Controller();
		$controller->register_routes();
	}

	/**
	 * Show a metabox in the sitebar of single field edit/create screen in admin
	 *
	 * @param object $field Field.
	 */
	public function admin_metabox( $field ) {
		$can_edit = bp_xprofile_get_meta( $field->id, 'field', 'member_can_edit' );

		if ( ! $can_edit ) {
			$can_edit = 'yes';
		}
		?>
			<div class="postbox">
				<h3><label for="member-can-edit"><?php esc_html_e( 'Is This Field Editable?', 'nisje' ); ?></label></h3>
				<div class="inside">
					<ul>
						<li>
							<input type="radio" id="member-can-edit-allowed" name="member-can-edit" value="yes" <?php checked( $can_edit, 'yes' ); ?> />
							<label for="member-can-edit-allowed"><?php esc_html_e( 'Let Users change this field', 'nisje' ); ?></label>
						</li>
						<li>
							<input type="radio" id="member-can-edit-disabled" name="member-can-edit" value="no" <?php checked( $can_edit, 'no' ); ?> />
							<label for="member-can-edit-disabled"><?php esc_html_e( 'Do not allow a user to change this field .', 'nisje' ); ?></label>
						</li>
					</ul>
				</div>
			</div>
		<?php
	}

	/**
	 * Update the editing preference when field is saved
	 *
	 * @param object $field Field object.
	 *
	 * @phpcs:disable WordPress.Security.NonceVerification.NoNonceVerification
	 */
	public function update_setting( $field ) {
		$member_can = ( isset( $_POST['member-can-edit'] ) && 'no' === $_POST['member-can-edit'] ) ? 'no' : 'yes'; // phpcs:ignore

		return bp_xprofile_update_meta( $field->id, 'field', 'member_can_edit', $member_can );
	}
}
