<?php

namespace Mtc\Plugins\Consumables\Providers;

use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;
use Mtc\Plugins\Consumables\Classes\ConsumableStockService;
use Mtc\Shop\Events\ItemAdminTabnavEvent;
use Mtc\Shop\Events\OrderPaidEvent;

class ConsumablesServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(ConsumableStockService::class);
    }

    public function boot(): void
    {
        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        $this->registerEventListeners();
    }

    protected function registerEventListeners(): void
    {
        // Add "Consumables" tab to item admin
        Event::listen(ItemAdminTabnavEvent::class, function (ItemAdminTabnavEvent $event) {
            $item = $event->getItem();
            $selected = request()->is('*/Consumables/admin/item*') ? ' class="selected"' : '';
            return '<li' . $selected . '><a href="/plugins/Consumables/admin/item.php?id='
                . (int) $item->id . '">Consumables</a></li>';
        });

        // Deduct consumable stock when an order is paid
        Event::listen(OrderPaidEvent::class, function (OrderPaidEvent $event) {
            $service = app(ConsumableStockService::class);
            $service->deductForOrder($event->getOrder());
        });
    }
}
