<?php
if (!defined('ABSPATH')) {
    exit;
}

class BMTQB_Capabilities {
    const MANAGE_SETTINGS = 'quote_manage_settings';
    const VIEW_SUBMISSIONS = 'quote_view_submissions';
    const EDIT_SUBMISSIONS = 'quote_edit_submissions';
    const DELETE_SUBMISSIONS = 'quote_delete_submissions';
    const MANAGE_INTEGRATIONS = 'quote_manage_integrations';
    const MANAGE_UPDATES = 'quote_manage_updates';
    const MANAGE_QUESTION_EXTENSIONS = 'quote_manage_question_extensions';

    public static function init() {
        add_action('admin_init', [__CLASS__, 'ensure_role_caps']);
        add_filter('user_has_cap', [__CLASS__, 'grant_runtime_caps'], 10, 4);
    }

    public static function all_caps() {
        return [
            self::MANAGE_SETTINGS,
            self::VIEW_SUBMISSIONS,
            self::EDIT_SUBMISSIONS,
            self::DELETE_SUBMISSIONS,
            self::MANAGE_INTEGRATIONS,
            self::MANAGE_UPDATES,
            self::MANAGE_QUESTION_EXTENSIONS,
        ];
    }

    public static function editor_caps() {
        return [
            self::MANAGE_SETTINGS,
            self::VIEW_SUBMISSIONS,
            self::EDIT_SUBMISSIONS,
        ];
    }

    public static function activate() {
        self::ensure_role_caps();
    }

    public static function ensure_role_caps() {
        $admin = get_role('administrator');
        if ($admin) {
            foreach (self::all_caps() as $cap) {
                $admin->add_cap($cap);
            }
        }

        $editor = get_role('editor');
        if ($editor) {
            foreach (self::editor_caps() as $cap) {
                $editor->add_cap($cap);
            }
        }
    }

    public static function grant_runtime_caps($allcaps, $caps, $args, $user) {
        $requested_cap = $args[0] ?? '';
        if (!in_array($requested_cap, self::all_caps(), true)) {
            return $allcaps;
        }

        if (!empty($allcaps['manage_options'])) {
            $allcaps[$requested_cap] = true;
            return $allcaps;
        }

        if (!empty($allcaps['edit_pages']) && in_array($requested_cap, self::editor_caps(), true)) {
            $allcaps[$requested_cap] = true;
        }

        return $allcaps;
    }
}
