<?php

namespace SoftminalB2B\Pricing;

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

/**
 * Whose rules a management request is acting on — the marketplace admin, or one
 * vendor managing only their own catalogue.
 *
 * This is the mirror of WholesaleX's `..._pricing_manager_context`: core always
 * answers "the admin, managing everything" (`is_vendor => false`), and the Dokan
 * bridge overrides `smb2b_vendor_context` for a vendor-dashboard request to say
 * "vendor N, may manage only their own rules". It gates *who may write which
 * rules* (Phase 5 self-service), and is deliberately separate from the buyer-side
 * pricing {@see Context}: this is about the manager, not the shopper.
 *
 * Added up front (even though v1 is admin-set only) so vendor self-service lands
 * later without another core change. With no bridge active it is inert.
 */
class VendorContext
{
    /**
     * The current management context.
     *
     * @return array{is_vendor:bool, vendor_id:int, can_manage:bool}
     */
    public static function current(): array
    {
        $default = [
            'is_vendor'  => false,
            'vendor_id'  => 0,
            // The marketplace admin manages every rule; a vendor's own ceiling is
            // decided by the bridge when it claims a request as vendor-scoped.
            'can_manage' => current_user_can('manage_woocommerce'),
        ];

        /**
         * Declare who this management request belongs to. Core defaults to the
         * admin managing everything. The Dokan bridge returns
         * `['is_vendor' => true, 'vendor_id' => N, 'can_manage' => bool]` for a
         * vendor-dashboard request so core scopes writes to that vendor.
         *
         * @param array{is_vendor:bool, vendor_id:int, can_manage:bool} $context
         */
        $context = apply_filters('smb2b_vendor_context', $default);

        if (!is_array($context)) {
            return $default;
        }

        return [
            'is_vendor'  => !empty($context['is_vendor']),
            'vendor_id'  => max(0, (int) ($context['vendor_id'] ?? 0)),
            'can_manage' => !empty($context['can_manage']),
        ];
    }

    /**
     * True when the current request is a vendor acting on their own catalogue
     * (rather than the marketplace admin).
     */
    public static function isVendor(): bool
    {
        return self::current()['is_vendor'];
    }

    /**
     * The vendor id owning the current management request, or 0 for the admin.
     */
    public static function vendorId(): int
    {
        return self::current()['vendor_id'];
    }
}
