<?php
/**
 * KooKoa Folders — Global helper functions.
 *
 * Top-level procedural helpers used across the plugin. Kept separate from
 * the main {@see KookoaWPF} class so the bootstrap file does not mix
 * function definitions and OO declarations
 * (Universal.Files.SeparateFunctionsFromOO).
 *
 * @package KookoaWPF
 */

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

/**
 * Get allowed roles for plugin access.
 *
 * Reads the `kookoawpf_allowed_roles` option (set from the Access Control
 * row in Settings → General). Administrator is always included so admins
 * can never lock themselves out by saving an incomplete role list.
 *
 * @return string[]
 */
function kookoawpf_get_allowed_roles() {
	$allowed = get_option( 'kookoawpf_allowed_roles', array( 'administrator' ) );
	if ( ! is_array( $allowed ) || empty( $allowed ) ) {
		$allowed = array( 'administrator' );
	}
	if ( ! in_array( 'administrator', $allowed, true ) ) {
		$allowed[] = 'administrator';
	}
	return array_values( $allowed );
}

/**
 * Check if the current user has access based on RBAC roles.
 *
 * @return bool
 */
function kookoawpf_user_has_access() {
	$allowed_roles = kookoawpf_get_allowed_roles();
	$user          = wp_get_current_user();
	foreach ( $user->roles as $role ) {
		if ( in_array( $role, $allowed_roles, true ) ) {
			return true;
		}
	}
	return false;
}

/**
 * Resolve the sidebar width for the current user.
 *
 * Drag-resize stores the user's personal preference in user meta so that
 * non-admin roles in the RBAC allowlist can adjust their own workspace
 * without needing the manage_options capability. The Settings → General
 * "Sidebar width" field still writes the site-wide option, which acts
 * as the default for any user who hasn't dragged yet.
 *
 * Resolution order: user meta → site-wide option → 350px hard fallback.
 * All values are clamped to the supported 300-600 range.
 *
 * @return int Width in pixels.
 */
function kookoawpf_get_sidebar_width() {
	$user_value = (int) get_user_meta( get_current_user_id(), 'kookoawpf_sidebar_width', true );
	if ( $user_value >= 300 && $user_value <= 600 ) {
		return $user_value;
	}
	$global = (int) get_option( 'kookoawpf_sidebar_width', 350 );
	if ( $global >= 300 && $global <= 600 ) {
		return $global;
	}
	return 350;
}
