<?php

namespace HulkPlugins\Woo\AccountPages\Admin\Services;

use HulkPlugins\Woo\AccountPages\Core\SingletonTrait;

defined( 'ABSPATH' ) || exit;

class AccountPageMetaBoxService {

	use SingletonTrait;

	/**
	 * Get editable system roles
	 */
	public function get_system_roles(): array {
		static $cache = null;

		if ( $cache !== null ) {
			return (array) $cache;
		}

		require_once ABSPATH . 'wp-admin/includes/user.php';

		$roles = get_editable_roles();
		$cache = array_map( static fn( $role ) => $role['name'], $roles );
		return $cache;
	}

	/**
	 * Get user roles for the page. If pages role is present
	 * in the meta then return it else return all site roles.
	 *
	 * @param $page_id
	 *
	 * @return array
	 */
	public function get_allowed_user_roles( $page_id ): array {
		$roles = (array) get_post_meta( $page_id, 'hulk_woo_ap_user_roles', true );
		if ( empty( $roles[0] ) ) {
			$roles  = array_keys( $this->get_system_roles() );
		}
		return $roles;
	}

	/**
	 * Get my-account page URL
	 */
	public function get_account_page_url(): ?string {
		static $url = null;

		if ( is_null( $url ) ) {
			$url   = wc_get_page_permalink( 'myaccount' );
		}

		return $url;
	}
}
