<?php

// B2B Module - Legacy Hooks
// Registers Twig globals for trade customer detection and pricing.
// Auto-discovered via modules/[star]/hooks.php glob in core/includes/twig.php
// $twig is available in scope from the auto-discovery include.

use Mtc\Modules\B2B\Enums\TradeCustomerStatus;
use Mtc\Modules\B2B\Models\TradeCustomer;
use Mtc\Modules\B2B\Services\TradePricingService;
use Mtc\Modules\Members\Classes\Authenticator;

if (!config('b2b.enabled')) {
    return;
}

// Determine if the current logged-in member is an approved trade customer
$isTradeCustomer = false;
$tradeTier = null;
$tradeCustomer = null;

// Instantiate Authenticator directly instead of using the Auth facade,
// because the facade binding may not be registered yet (B2B hooks load before Members hooks)
$b2bMember = (new Authenticator())->getLoggedInMember();

if ($b2bMember && !empty($b2bMember->id)) {
    $tradeCustomer = TradeCustomer::where('member_id', $b2bMember->id)
        ->where('status', TradeCustomerStatus::Approved->value)
        ->with('tier')
        ->first();

    if ($tradeCustomer && $tradeCustomer->tier) {
        $isTradeCustomer = true;
        $tradeTier = $tradeCustomer->tier;
    }
}

// Register Twig globals
$twig->addGlobal('is_trade_customer', $isTradeCustomer);
$twig->addGlobal('trade_tier', $tradeTier);
$twig->addGlobal('trade_customer', $tradeCustomer);
$twig->addGlobal('trade_pricing_service', app(TradePricingService::class));
