<?php

// B2B Module - Legacy Loader
// Registers event listeners for basket price override and coupon blocking.
// Auto-discovered via modules/[star]/loader.php glob in core/includes/twig.php
// Note: Laravel Event::listen() calls are in B2BServiceProvider.
// This file handles basket-related events only.

use App\Events\BasketLoadedEvent;
use Illuminate\Support\Facades\Event;
use Mtc\Modules\B2B\Enums\TradeCustomerStatus;
use Mtc\Modules\B2B\Models\TradeCustomer;
use Mtc\Modules\B2B\Services\TradePricingService;
use Mtc\Shop\Events\BasketGetItemsEvent;
use Mtc\Shop\Events\ShopItemDataEvent;

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

// Override basket item prices with trade prices for trade customers
Event::listen(BasketGetItemsEvent::class, function (BasketGetItemsEvent $event) {
    $service = app(TradePricingService::class);
    return $service->overrideBasketPrices($event);
});

// Override displayed prices on browse/detail pages with trade prices
Event::listen(ShopItemDataEvent::class, function (ShopItemDataEvent $event) {
    $service = app(TradePricingService::class);
    $service->overrideItemPrices($event);
});

// Block coupons for trade customers — remove any applied coupon after basket loads
Event::listen(BasketLoadedEvent::class, function (BasketLoadedEvent $event) {
    $basket = $event->getBasket();

    $memberId = $basket->member ?? null;
    if (!$memberId) {
        return;
    }

    $isTradeCustomer = TradeCustomer::where('member_id', $memberId)
        ->where('status', TradeCustomerStatus::Approved->value)
        ->exists();

    if (!$isTradeCustomer) {
        return;
    }

    // Clear any coupon that was applied
    if (!empty($basket->coupon_code)) {
        \Mtc\Shop\Basket::where('id', $basket->id)->update(['coupon' => '']);

        $basket->coupon_code = '';
        $basket->coupon_deduct = 0;
        $basket->coupon_percentoff = 0;
        $basket->coupon_amountof = 0;
        $basket->coupon_error = 'Coupons are not available for trade accounts';
    }
});
