<?php

namespace App\Models;

use App\Concerns\RecordsCreator;
use App\Support\ExpenseStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class ExpenseDay extends Model
{
    use RecordsCreator;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'expense_date',
        'branch_id',
        'notes',
        'updated_by',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'expense_date' => 'date',
            'branch_id' => 'integer',
        ];
    }

    /**
     * @return BelongsTo<Branch, $this>
     */
    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    /**
     * @return BelongsTo<User, $this>
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /**
     * @return HasMany<Expense, $this>
     */
    public function expenses(): HasMany
    {
        return $this->hasMany(Expense::class);
    }

    public function activeExpensesCount(): int
    {
        return $this->expenses()
            ->where('status', '!=', ExpenseStatus::CANCELLED)
            ->count();
    }

    public function activeExpensesTotal(): float
    {
        return (float) $this->expenses()
            ->whereIn('status', ExpenseStatus::countableValues())
            ->sum('amount_original');
    }
}
