<?php

namespace App\Models;

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

class DeliveryEarning extends Model
{
    use HasFactory;

    protected $fillable = [
        'delivery_assignment_id',
        'delivery_agent_id',
        'delivery_fee',
        'bonus',
        'penalty',
        'total_amount',
        'status',
        'credited_at',
        'withdrawn_at',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'delivery_fee' => 'decimal:2',
            'bonus' => 'decimal:2',
            'penalty' => 'decimal:2',
            'total_amount' => 'decimal:2',
            'credited_at' => 'datetime',
            'withdrawn_at' => 'datetime',
        ];
    }

    public function assignment(): BelongsTo
    {
        return $this->belongsTo(DeliveryAssignment::class);
    }

    public function deliveryAgent(): BelongsTo
    {
        return $this->belongsTo(DeliveryAgent::class);
    }

    protected static function boot(): void
    {
        parent::boot();

        static::creating(function ($earning) {
            $earning->total_amount = 
                ($earning->delivery_fee ?? 0) + 
                ($earning->bonus ?? 0) - 
                ($earning->penalty ?? 0);
        });
    }
}
