<?php

declare(strict_types=1);

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

namespace App\Filament\Resources\DberpSalespersons\Pages;

use App\Filament\Resources\DberpSalespersons\DberpSalespersonResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpDeleteRecordAction;
use App\Models\DberpSalesperson;
use Filament\Actions\DeleteAction;

class EditDberpSalesperson extends EditRecord
{
    protected static string $resource = DberpSalespersonResource::class;

    /**
     * 打开编辑页时，若已关联职员，表单快照与职员主档对齐（职员后补的部门、岗位、电话等会立即显示）。
     *
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        if (! empty($data['employee_id'])) {
            return DberpSalesperson::syncSnapshotFieldsFromEmployee($data);
        }

        return $data;
    }

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        foreach (['employee_id', 'department_id', 'position_id'] as $key) {
            if (array_key_exists($key, $data) && ($data[$key] === '' || $data[$key] === null)) {
                $data[$key] = null;
            }
        }

        $record = $this->getRecord();
        $currentEmployeeId = $record instanceof DberpSalesperson && $record->employee_id !== null
            ? (int) $record->employee_id
            : null;

        if (($data['employee_id'] ?? null) !== null) {
            DberpSalesperson::assertEmployeeEligibleForSalespersonLink(
                (int) $data['employee_id'],
                $currentEmployeeId,
            );
            $data = DberpSalesperson::syncSnapshotFieldsFromEmployee($data);
        }

        if ((bool) ($data['is_enabled'] ?? true)) {
            DberpSalesperson::assertUniqueActiveEmployeeLink(
                isset($data['employee_id']) && $data['employee_id'] !== null ? (int) $data['employee_id'] : null,
                (int) $record->getKey(),
            );
        }

        return $data;
    }

    protected function getHeaderActions(): array
    {
        return [
            DberpDeleteRecordAction::configure(DeleteAction::make()),
        ];
    }
}
