<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

/**
 * Encapsulates all logic related to role-based menu overrides so the API layer
 * only orchestrates requests/responses.
 */
class MenuOverridesService
{
    private const OVERRIDES_OPTION_PREFIX = '_fleekdash_menu_overrides_';

    /**
     * Return overrides for a specific role.
     */
    public function getRoleOverrides(string $roleSlug): array
    {
        return \get_option($this->getOptionName($roleSlug), []);
    }

    /**
     * Persist overrides for a role.
     */
    public function saveRoleOverrides(string $roleSlug, array $overrides): void
    {
        \update_option($this->getOptionName($roleSlug), $overrides, false);
    }

    /**
     * Remove overrides for a role.
     */
    public function resetRoleOverrides(string $roleSlug): void
    {
        \delete_option($this->getOptionName($roleSlug));
    }

    /**
     * Return overrides for every registered WordPress role.
     *
     * @return array<string,array>
     */
    public function getAllRoleOverrides(): array
    {
        $roles = wp_roles()->get_names();
        $overrides = [];

        foreach (array_keys($roles) as $roleSlug) {
            $overrides[$roleSlug] = $this->getRoleOverrides($roleSlug);
        }

        return $overrides;
    }

    /**
     * Reset all persisted role overrides.
     */
    public function resetAllRoleOverrides(): void
    {
        global $wpdb;
        $like = $wpdb->esc_like(self::OVERRIDES_OPTION_PREFIX) . '%';
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s",
                $like
            )
        );
    }

    private function getOptionName(string $roleSlug): string
    {
        return sprintf(self::OVERRIDES_OPTION_PREFIX . '%s', $roleSlug);
    }
}
