<?php

namespace App\Models;

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

class MerchantDeduction extends Model
{
    use HasFactory;

    protected $fillable = [
        'deduction_number',
        'merchant_id',
        'invoice_id',
        'deduction_type',
        'amount',
        'deduction_date',
        'reason',
        'notes',
        'status',
        'approved_by',
        'approved_at',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'deduction_date' => 'date',
        'approved_at' => 'datetime',
    ];

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

        static::creating(function ($deduction) {
            if (empty($deduction->deduction_number)) {
                $deduction->deduction_number = 'DED-' . 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 approvedBy()
    {
        return $this->belongsTo(User::class, 'approved_by');
    }
}
