<?php

declare(strict_types=1);

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

namespace App\Filament\Widgets;

use App\Filament\Pages\HostSystemUpdateCenterPage;
use App\Models\DberpSystemUpdateNotice;
use App\Services\DberpPermissionService;
use App\Services\DberpSystemUpdateNoticeService;
use Filament\Notifications\Notification;
use Filament\Widgets\Widget;
use Illuminate\Support\Facades\Auth;

class SystemUpdateNoticeWorkbenchWidget extends Widget
{
    protected static bool $isLazy = true;

    protected string $view = 'filament.widgets.system-update-notice-workbench-widget';

    protected int|string|array $columnSpan = 'full';

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

    public function notice(): ?DberpSystemUpdateNotice
    {
        return app(DberpSystemUpdateNoticeService::class)->latestActiveNoticeFor(Auth::user());
    }

    public function panelData(): ?array
    {
        return app(DberpSystemUpdateNoticeService::class)->panelViewDataFor(Auth::user());
    }

    public function updateCenterUrl(): string
    {
        return HostSystemUpdateCenterPage::getUrl(panel: 'admin');
    }

    public function markSystemUpdateNoticeAsRead(): void
    {
        $notice = $this->notice();

        if ($notice === null) {
            return;
        }

        $user = Auth::user();

        if ($user === null) {
            return;
        }

        if (! app(DberpSystemUpdateNoticeService::class)->markAsRead($user, (int) $notice->getKey())) {
            return;
        }

        Notification::make()
            ->success()
            ->title(__('dberp.system_update_notice.messages.marked_read'))
            ->send();
    }

    public function dismissSystemUpdateNotice(): void
    {
        $notice = $this->notice();

        if ($notice === null) {
            return;
        }

        $user = Auth::user();

        if ($user === null) {
            return;
        }

        if (! app(DberpSystemUpdateNoticeService::class)->dismiss($user, (int) $notice->getKey())) {
            return;
        }

        Notification::make()
            ->success()
            ->title(__('dberp.system_update_notice.messages.dismissed'))
            ->send();
    }
}
