<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Widgets;

use App\Business\Inventory\InventoryGovernanceReminderService;
use App\Filament\Resources\DberpInventoryBatches\DberpInventoryBatchResource;
use App\Filament\Resources\DberpInventoryExceptions\DberpInventoryExceptionResource;
use App\Filament\Resources\DberpInventoryReplenishmentSuggestions\DberpInventoryReplenishmentSuggestionResource;
use App\Filament\Resources\DberpInventoryWarnings\DberpInventoryWarningResource;
use App\Filament\Resources\DberpStocktakeDifferences\DberpStocktakeDifferenceResource;
use App\Services\DberpPermissionService;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

class InventoryGovernanceOverviewStatsWidget extends BaseWidget
{
    protected ?string $pollingInterval = null;

    public static function canView(): bool
    {
        return app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::VIEW_WORKBENCH_OVERVIEW);
    }

    protected function getStats(): array
    {
        $metrics = app(InventoryGovernanceReminderService::class)->overviewMetrics();

        return [
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.expired_batches'), (string) $metrics['expired_batch_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_exceptions'))
                ->color('danger')
                ->url($this->exceptionUrl('expired_batch_stock')),
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.near_expiry_batches'), (string) $metrics['near_expiry_batch_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_batches'))
                ->color('warning')
                ->url($this->nearExpiryBatchUrl()),
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.pending_stocktake_difference'), (string) $metrics['pending_stocktake_difference_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_differences'))
                ->color('danger')
                ->url($this->differenceUrl('pending')),
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.pending_replenishment'), (string) $metrics['pending_replenishment_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_replenishment'))
                ->color('primary')
                ->url($this->replenishmentUrl('pending')),
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.low_stock'), (string) $metrics['low_stock_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_warnings'))
                ->color('warning')
                ->url(DberpInventoryWarningResource::getUrl('index')),
            Stat::make((string) __('dberp.widgets.inventory_overview_stats.open_exceptions'), (string) $metrics['open_inventory_exception_count'])
                ->description((string) __('dberp.widgets.inventory_overview_stats.link_exceptions'))
                ->color('danger')
                ->url($this->exceptionUrl()),
        ];
    }

    private function exceptionUrl(?string $type = null): string
    {
        $filters = [
            'status' => ['value' => 'open'],
        ];

        if ($type !== null) {
            $filters['exception_type'] = ['value' => $type];
        }

        return DberpInventoryExceptionResource::getUrl('index').'?'.http_build_query([
            'filters' => $filters,
        ]);
    }

    private function replenishmentUrl(string $status): string
    {
        return DberpInventoryReplenishmentSuggestionResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'status' => [
                    'value' => $status,
                ],
            ],
        ]);
    }

    private function differenceUrl(string $status): string
    {
        return DberpStocktakeDifferenceResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'status' => [
                    'value' => $status,
                ],
            ],
        ]);
    }

    private function nearExpiryBatchUrl(): string
    {
        return DberpInventoryBatchResource::getUrl('index').'?'.http_build_query([
            'filters' => [
                'expiry_status' => [
                    'value' => 'near_expiry',
                ],
            ],
        ]);
    }
}
