<?php
/**
 * Client mode – role, restrictions, invite flow (Ultimate Bundle).
 *
 * @package EasySite_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Whether current user is an EasySite Client.
 *
 * @return bool
 */
function easysite_current_user_is_client() {
	$user = wp_get_current_user();
	return $user && $user->exists() && in_array( 'easysite_client', (array) $user->roles, true );
}

/**
 * Register EasySite Client role.
 */
function easysite_register_client_role() {
	if ( get_role( 'easysite_client' ) ) {
		return;
	}
	add_role(
		'easysite_client',
		__( 'EasySite Client', 'easysite-pro' ),
		array(
			'read'               => true,
			'edit_posts'         => true,
			'edit_pages'         => true,
			'upload_files'       => true,
			'edit_theme_options' => true,
		)
	);
}
add_action( 'after_switch_theme', 'easysite_register_client_role' );
add_action( 'init', 'easysite_register_client_role' );

/**
 * Restrict client role admin access.
 */
function easysite_client_role_restrictions() {
	if ( ! easysite_current_user_is_client() ) {
		return;
	}
	$hide = array(
		'plugins.php',
		'themes.php',
		'tools.php',
		'options-general.php',
		'users.php',
		'edit.php?post_type=product',
		'woocommerce',
		'easysite-license',
		'easysite-site-kit',
	);
	foreach ( $hide as $page ) {
		remove_menu_page( $page );
		remove_submenu_page( 'easysite-setup', $page );
	}
	remove_submenu_page( 'easysite-setup', 'easysite-license' );
	remove_submenu_page( 'easysite-setup', 'easysite-site-kit' );
}
add_action( 'admin_menu', 'easysite_client_role_restrictions', 999 );

/**
 * Client dashboard widget with visual editor link.
 */
function easysite_client_ve_dashboard_widget() {
	if ( ! easysite_current_user_is_client() && ! easysite_get_mod( 'easysite_client_mode', false ) ) {
		return;
	}
	$agency  = easysite_get_brand_name();
	$message = easysite_get_mod( 'easysite_help_message', __( 'Click below to edit your website — no technical skills needed.', 'easysite-pro' ) );
	$front_id = (int) get_option( 'page_on_front' );
	$ve_url   = $front_id ? add_query_arg( 'easysite_edit', '1', get_permalink( $front_id ) ) : add_query_arg( 'easysite_edit', '1', home_url( '/' ) );

	wp_add_dashboard_widget(
		'easysite_client_ve',
		sprintf( __( 'Edit your site — %s', 'easysite-pro' ), $agency ),
		function () use ( $message, $ve_url ) {
			echo '<p>' . esc_html( $message ) . '</p>';
			echo '<p><a class="button button-primary button-hero" href="' . esc_url( $ve_url ) . '">' . esc_html__( 'Edit your site visually', 'easysite-pro' ) . '</a></p>';
			echo '<p><a class="button" href="' . esc_url( admin_url( 'admin.php?page=easysite-site-settings' ) ) . '">' . esc_html__( 'Site colors & logo', 'easysite-pro' ) . '</a></p>';
			echo '<p><a class="button" href="' . esc_url( admin_url( 'admin.php?page=easysite-client-help' ) ) . '">' . esc_html__( 'Help & guides', 'easysite-pro' ) . '</a></p>';
		}
	);
}
add_action( 'wp_dashboard_setup', 'easysite_client_ve_dashboard_widget' );

/**
 * Register client invite submenu.
 */
function easysite_client_invite_menu() {
	if ( ! easysite_is_bundle() || easysite_current_user_is_client() ) {
		return;
	}
	add_submenu_page(
		'easysite-setup',
		__( 'Invite Client', 'easysite-pro' ),
		__( 'Invite Client', 'easysite-pro' ),
		'manage_options',
		'easysite-invite-client',
		'easysite_render_invite_client_page'
	);
}
add_action( 'admin_menu', 'easysite_client_invite_menu', 20 );

/**
 * Render invite client page.
 */
function easysite_render_invite_client_page() {
	$sent = isset( $_GET['invited'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	?>
	<div class="wrap">
		<h1><?php esc_html_e( 'Invite your client', 'easysite-pro' ); ?></h1>
		<p><?php esc_html_e( 'Create a login for your client. They can edit content visually but cannot install plugins or change themes.', 'easysite-pro' ); ?></p>
		<?php if ( $sent ) : ?>
			<div class="notice notice-success"><p><?php esc_html_e( 'Client account created! Share the login details securely.', 'easysite-pro' ); ?></p></div>
		<?php endif; ?>
		<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
			<?php wp_nonce_field( 'easysite_invite_client', 'easysite_invite_nonce' ); ?>
			<input type="hidden" name="action" value="easysite_invite_client" />
			<table class="form-table">
				<tr>
					<th><label for="client_name"><?php esc_html_e( 'Name', 'easysite-pro' ); ?></label></th>
					<td><input type="text" name="client_name" id="client_name" class="regular-text" required /></td>
				</tr>
				<tr>
					<th><label for="client_email"><?php esc_html_e( 'Email', 'easysite-pro' ); ?></label></th>
					<td><input type="email" name="client_email" id="client_email" class="regular-text" required /></td>
				</tr>
				<tr>
					<th><label for="client_password"><?php esc_html_e( 'Password', 'easysite-pro' ); ?></label></th>
					<td>
						<input type="text" name="client_password" id="client_password" class="regular-text" required />
						<p class="description"><?php esc_html_e( 'Generate a strong password and share it with your client.', 'easysite-pro' ); ?></p>
					</td>
				</tr>
				<tr>
					<th><?php esc_html_e( 'Client mode', 'easysite-pro' ); ?></th>
					<td>
						<label><input type="checkbox" name="enable_client_mode" value="1" <?php checked( easysite_get_mod( 'easysite_client_mode', false ) ); ?> />
						<?php esc_html_e( 'Enable simplified dashboard for all clients', 'easysite-pro' ); ?></label>
					</td>
				</tr>
			</table>
			<p class="submit"><button type="submit" class="button button-primary"><?php esc_html_e( 'Create client account', 'easysite-pro' ); ?></button></p>
		</form>
	</div>
	<?php
}

/**
 * Handle client invite form.
 */
function easysite_handle_invite_client() {
	if ( ! isset( $_POST['easysite_invite_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['easysite_invite_nonce'] ) ), 'easysite_invite_client' ) ) {
		wp_die( esc_html__( 'Security check failed.', 'easysite-pro' ) );
	}
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html__( 'Permission denied.', 'easysite-pro' ) );
	}

	$email    = isset( $_POST['client_email'] ) ? sanitize_email( wp_unslash( $_POST['client_email'] ) ) : '';
	$name     = isset( $_POST['client_name'] ) ? sanitize_text_field( wp_unslash( $_POST['client_name'] ) ) : '';
	$password = isset( $_POST['client_password'] ) ? wp_unslash( $_POST['client_password'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput

	if ( ! is_email( $email ) || ! $name || ! $password ) {
		wp_die( esc_html__( 'Please fill in all fields.', 'easysite-pro' ) );
	}

	if ( email_exists( $email ) ) {
		$user = get_user_by( 'email', $email );
		if ( $user ) {
			$user->set_role( 'easysite_client' );
		}
	} else {
		$user_id = wp_create_user( sanitize_user( $email, true ), $password, $email );
		if ( is_wp_error( $user_id ) ) {
			wp_die( esc_html( $user_id->get_error_message() ) );
		}
		wp_update_user( array( 'ID' => $user_id, 'display_name' => $name, 'role' => 'easysite_client' ) );
	}

	if ( ! empty( $_POST['enable_client_mode'] ) ) {
		set_theme_mod( 'easysite_client_mode', true );
	}

	wp_safe_redirect( admin_url( 'admin.php?page=easysite-invite-client&invited=1' ) );
	exit;
}
add_action( 'admin_post_easysite_invite_client', 'easysite_handle_invite_client' );
