<?php

namespace Mtc\Modules\B2B\Providers;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Mtc\Modules\B2B\Console\Commands\SendOverdueReminders;
use Mtc\Modules\B2B\Events\AccountOrderPaidEvent;
use Mtc\Modules\B2B\Events\TradeApplicationApprovedEvent;
use Mtc\Modules\B2B\Events\TradeApplicationSubmittedEvent;
use Mtc\Modules\B2B\Services\AccountPaymentService;
use Mtc\Modules\B2B\Services\TradePricingService;
use Mtc\Shop\Events\ItemAdminTabnavEvent;

class B2BServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../config/b2b.php', 'b2b');
        $this->app->singleton(TradePricingService::class);
    }

    public function boot(): void
    {
        if (!config('b2b.enabled')) {
            return;
        }

        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
        $this->loadRoutesFrom(__DIR__ . '/../routes/b2b.php');
        $this->registerEventListeners();
        $this->commands([
            SendOverdueReminders::class,
        ]);

        $this->app->booted(function () {
            $schedule = $this->app->make(Schedule::class);
            $schedule->command('b2b:send-overdue-reminders')->daily();
        });
    }

    protected function registerEventListeners(): void
    {
        // Product admin: add "Trade Pricing" tab
        Event::listen(ItemAdminTabnavEvent::class, function (ItemAdminTabnavEvent $event) {
            $item = $event->getItem();
            $selected = request()->is('*/item-trade-pricing*') ? ' class="selected"' : '';
            return '<li' . $selected . '><a href="/modules/B2B/admin/item-trade-pricing.php?id=' . (int) $item->id . '">Trade Pricing</a></li>';
        });

        // Payment gateway: inject "Pay on Account" option at checkout
        if (config('b2b.pay_on_account_enabled')) {
            Event::listen('shop.checkout.load_payment_gateways', function ($basket) {
                $service = app(AccountPaymentService::class);
                return $service->renderPayOnAccountForm($basket);
            });
        }

        // Trade application submitted: send admin notification email
        Event::listen(TradeApplicationSubmittedEvent::class, function (TradeApplicationSubmittedEvent $event) {
            $tradeCustomer = $event->tradeCustomer;
            $twig = app('twig');
            $html = $twig->render('b2b/emails/application_submitted_admin.twig', [
                'trade_customer' => $tradeCustomer,
                'address'        => $tradeCustomer->address,
                'member'         => $tradeCustomer->member,
            ]);
            email(
                config('site.from_email'),
                'New Trade Account Application: ' . $tradeCustomer->company_name,
                $html
            );
        });

        // Trade application approved: send customer welcome email
        Event::listen(TradeApplicationApprovedEvent::class, function (TradeApplicationApprovedEvent $event) {
            $tradeCustomer = $event->tradeCustomer;
            $twig = app('twig');
            $html = $twig->render('b2b/emails/application_approved.twig', [
                'trade_customer' => $tradeCustomer,
                'tier'           => $tradeCustomer->tier,
                'member'         => $tradeCustomer->member,
            ]);
            email(
                $tradeCustomer->member->email,
                'Your Trade Account Has Been Approved',
                $html
            );
        });

        // Account order paid: send payment received email
        Event::listen(AccountOrderPaidEvent::class, function (AccountOrderPaidEvent $event) {
            $accountOrder = $event->accountOrder;
            $tradeCustomer = $accountOrder->tradeCustomer;
            $twig = app('twig');
            $html = $twig->render('b2b/emails/account_payment_received.twig', [
                'account_order'  => $accountOrder,
                'trade_customer' => $tradeCustomer,
                'member'         => $tradeCustomer->member,
            ]);
            email(
                $tradeCustomer->member->email,
                'Payment Received - ' . $accountOrder->po_number,
                $html
            );
        });

        // Member admin: add "Trade Account" tab for members with trade profiles
        Event::listen('Members/Admin/MemberOpenTabNav', function ($id = null) {
            if (empty($id)) {
                return '';
            }
            $tradeCustomer = \Mtc\Modules\B2B\Models\TradeCustomer::where('member_id', $id)->first();
            if (!$tradeCustomer) {
                return '';
            }
            $selected = request()->is('*/B2B/admin/customers*') ? ' class="selected"' : '';
            return '<li' . $selected . '><a href="/modules/B2B/admin/customers.php?action=view&id=' . $tradeCustomer->id . '">Trade Account</a></li>';
        });

        // Admin dashboard: add B2B trade stats card
        Event::listen('Admin::dashboardStats', function () {
            return [
                [
                    'name' => 'B2B Trade',
                    'type' => 'numeric',
                    'id'   => 'js_b2bTradeOverview',
                    'url'  => '/modules/B2B/admin/stats.php?section=trade_overview',
                ],
            ];
        });
    }
}
