<?php

namespace App\Models;

use App\Enums\DocumentStatus;
use App\Models\Concerns\HasPublicId;
use App\Models\Concerns\ImmutableWhenPosted;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;

final class DriverAdvance extends Model
{
    use HasPublicId, ImmutableWhenPosted;

    protected $table = 'driver_advances';
    protected array $mutableAfterPosting = ['settled_amount'];
    protected $fillable = ['public_id','company_id','branch_id','driver_id','trip_id','advance_number','advance_date','advance_type','amount','settled_amount','advance_account_id','cash_bank_account_id','status','description','approved_by','approved_at','posted_at','created_by'];
    protected function casts(): array { return ['advance_date'=>'date','amount'=>'decimal:4','settled_amount'=>'decimal:4','status'=>DocumentStatus::class,'approved_at'=>'datetime','posted_at'=>'datetime']; }
    public function company(): BelongsTo { return $this->belongsTo(Company::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function driver(): BelongsTo { return $this->belongsTo(Driver::class); }
    public function trip(): BelongsTo { return $this->belongsTo(Trip::class); }
    public function advanceAccount(): BelongsTo { return $this->belongsTo(Account::class,'advance_account_id'); }
    public function cashBankAccount(): BelongsTo { return $this->belongsTo(Account::class,'cash_bank_account_id'); }
    public function settlements(): HasMany { return $this->hasMany(DriverSettlement::class); }
    public function journal(): MorphOne { return $this->morphOne(JournalEntry::class,'source'); }
}
