<?php

declare(strict_types=1);

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

namespace App\Models;

use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class DberpSettlementStatement extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_settlement_statements';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'settlement_side',
        'counterparty_type',
        'counterparty_id',
        'counterparty_name',
        'statement_date',
        'period_start_date',
        'period_end_date',
        'opening_balance',
        'period_increase_amount',
        'period_decrease_amount',
        'closing_balance',
        'item_count',
        'statement_status',
        'handler_employee_id',
        'confirmed_at',
        'voided_at',
        'last_exported_at',
        'last_exported_by',
        'source_system',
        'external_document_no',
        'external_reference_id',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'counterparty_id' => 'integer',
            'statement_date' => 'date',
            'period_start_date' => 'date',
            'period_end_date' => 'date',
            'opening_balance' => 'decimal:4',
            'period_increase_amount' => 'decimal:4',
            'period_decrease_amount' => 'decimal:4',
            'closing_balance' => 'decimal:4',
            'item_count' => 'integer',
            'handler_employee_id' => 'integer',
            'confirmed_at' => 'datetime',
            'voided_at' => 'datetime',
            'last_exported_at' => 'datetime',
            'last_exported_by' => 'integer',
        ];
    }

    public function getDberpNumberScope(): string
    {
        return 'settlement_statement';
    }

    public function getDberpAuditActionPrefix(): string
    {
        return 'dberp.settlement_statement';
    }

    /**
     * @return list<string>
     */
    public function getDberpAuditFields(): array
    {
        return $this->getFillable();
    }

    public function handlerEmployee(): BelongsTo
    {
        return $this->belongsTo(DberpEmployee::class, 'handler_employee_id');
    }

    public function exportedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'last_exported_by');
    }

    public function items(): HasMany
    {
        return $this->hasMany(DberpSettlementStatementItem::class, 'statement_id');
    }
}