<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MerchantDispute extends Model
{
    use HasFactory;

    protected $fillable = [
        'dispute_number',
        'merchant_id',
        'invoice_id',
        'payment_id',
        'deduction_id',
        'dispute_type',
        'subject',
        'description',
        'disputed_amount',
        'priority',
        'status',
        'resolution',
        'assigned_to',
        'resolved_by',
        'resolved_at',
    ];

    protected $casts = [
        'disputed_amount' => 'decimal:2',
        'resolved_at' => 'datetime',
    ];

    // Auto-generate dispute number
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($dispute) {
            if (empty($dispute->dispute_number)) {
                $dispute->dispute_number = 'DIS-' . date('Y') . '-' . str_pad(static::count() + 1, 4, '0', STR_PAD_LEFT);
            }
        });
    }

    public function merchant()
    {
        return $this->belongsTo(User::class, 'merchant_id');
    }

    public function invoice()
    {
        return $this->belongsTo(MerchantInvoice::class, 'invoice_id');
    }

    public function payment()
    {
        return $this->belongsTo(MerchantPayment::class, 'payment_id');
    }

    public function deduction()
    {
        return $this->belongsTo(MerchantDeduction::class, 'deduction_id');
    }

    public function assignedTo()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

    public function resolvedBy()
    {
        return $this->belongsTo(User::class, 'resolved_by');
    }
}
