<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Income extends Model
{
    use BelongsToTenant;

    public const STATUS_POSTED = 'posted';
    public const STATUS_CANCELED = 'canceled';

    protected $fillable = [
        'tenant_id',
        'recorded_by',
        'canceled_by',
        'category',
        'amount',
        'received_at',
        'canceled_at',
        'payer',
        'method',
        'status',
        'notes',
        'canceled_reason',
        'reference',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'received_at' => 'date',
            'canceled_at' => 'datetime',
        ];
    }

    public function scopePosted(Builder $query): Builder
    {
        return $query->where(function (Builder $query): void {
            $query->where('status', self::STATUS_POSTED)
                ->orWhereNull('status');
        });
    }

    public function recordedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'recorded_by');
    }

    public function canceledBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'canceled_by');
    }
}
