<?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 App\Models\Concerns\HasOptionalInvoiceAssistantRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class DberpCustomer extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;
    use HasOptionalInvoiceAssistantRelations;

    protected $table = 'dberp_customers';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'customer_category_id',
        'contact_person',
        'mobile',
        'phone',
        'email',
        'address',
        'country_code',
        'region_id',
        'region_name_snapshot',
        'settlement_method',
        'price_level_code',
        'default_payment_term_days',
        'credit_limit_amount',
        'credit_control_note',
        'salesperson_employee_id',
        'source_platform',
        'external_member_id',
        'integration_sync_status',
        'last_integration_synced_at',
        'is_enabled',
        'sort_order',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'customer_category_id' => 'integer',
            'region_id' => 'integer',
            'salesperson_employee_id' => 'integer',
            'default_payment_term_days' => 'integer',
            'credit_limit_amount' => 'decimal:4',
            'is_enabled' => 'boolean',
            'sort_order' => 'integer',
            'last_integration_synced_at' => 'datetime',
        ];
    }

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

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

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

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

    /**
     * 同一职员可能对应多条业务员历史行：取 id 最大的一条，供列表展示「业务员主档」展示名。
     */
    public function latestSalespersonProfile(): HasOne
    {
        return $this->hasOne(DberpSalesperson::class, 'employee_id', 'salesperson_employee_id')
            ->latestOfMany();
    }

    public function customerCategory(): BelongsTo
    {
        return $this->belongsTo(DberpCustomerCategory::class, 'customer_category_id');
    }

    public function region(): BelongsTo
    {
        return $this->belongsTo(DberpRegion::class, 'region_id');
    }

    public function salesOrders(): HasMany
    {
        return $this->hasMany(DberpSalesOrder::class, 'customer_id');
    }

    public function salesQuotes(): HasMany
    {
        return $this->hasMany(DberpSalesQuote::class, 'customer_id');
    }

    public function customerPriceRules(): HasMany
    {
        return $this->hasMany(DberpCustomerPriceRule::class, 'customer_id');
    }

    public function receiptOrders(): HasMany
    {
        return $this->hasMany(DberpReceiptOrder::class, 'customer_id');
    }

    public function settlementEntries(): HasMany
    {
        return $this->hasMany(DberpSettlementEntry::class, 'counterparty_id')
            ->where('counterparty_type', 'customer');
    }

    public function integrationMappings(): MorphMany
    {
        return $this->morphMany(DberpIntegrationMapping::class, 'localModel', 'local_model_type', 'local_model_id');
    }
}
