<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\Pages;

use App\Filament\Contracts\DberpFilamentFormEditability;
use App\Filament\Support\DberpFormSaveSubheading;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Resources\Pages\EditRecord as FilamentEditRecord;
use Illuminate\Contracts\Support\Htmlable;

class EditRecord extends FilamentEditRecord
{
    public function getSubheading(): string|Htmlable|null
    {
        $parentSubheading = parent::getSubheading();

        if (! $this->isRecordFormEditable()) {
            if ($parentSubheading === null || $parentSubheading === '') {
                return (string) __('dberp.ui.read_only_document_subheading');
            }

            return $parentSubheading.' '.(string) __('dberp.ui.read_only_document_subheading');
        }

        return DberpFormSaveSubheading::append($parentSubheading);
    }

    /**
     * When false, the default form save action is hidden (page behaves as read-only for the schema).
     */
    protected function isRecordFormEditable(): bool
    {
        $resourceClass = static::getResource();

        if (in_array(DberpFilamentFormEditability::class, class_implements($resourceClass) ?: [], true)) {
            /** @var DberpFilamentFormEditability $resourceClass */
            return $resourceClass::isRecordFormEditableForFilament($this->getRecord());
        }

        return true;
    }

    /**
     * @return array<Action | ActionGroup>
     */
    protected function getFormActions(): array
    {
        if (! $this->isRecordFormEditable()) {
            return [$this->getCancelFormAction()];
        }

        return parent::getFormActions();
    }
}
