<?php

namespace App\Models;

use App\Models\Concerns\BelongsToBranch;
use App\Models\Concerns\HasAuditColumns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class JournalEntry extends Model
{
    use BelongsToBranch;
    use HasAuditColumns;
    use SoftDeletes;

    protected $fillable = [
        'branch_id', 'entry_number', 'date', 'type', 'reference', 'description',
        'source_type', 'source_id',
    ];

    protected function casts(): array
    {
        return ['date' => 'date'];
    }

    public function lines(): HasMany
    {
        return $this->hasMany(JournalLine::class);
    }

    public function source(): MorphTo
    {
        return $this->morphTo();
    }

    public function getTotalDebitAttribute(): float
    {
        return (float) $this->lines->sum('debit');
    }

    public function getTotalCreditAttribute(): float
    {
        return (float) $this->lines->sum('credit');
    }

    public static function nextNumber(int $branchId): string
    {
        $count = static::withoutGlobalScopes()->where('branch_id', $branchId)->withTrashed()->count();

        return 'JV-'.date('Y').'-'.str_pad((string) ($count + 1), 5, '0', STR_PAD_LEFT);
    }
}
