<?php

namespace App\Models;

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

class Ledger extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function scopeIsTransaction($query)
    {
        return $query->whereNotNull('transaction_id');
    }

    public function scopeIsJournal($query)
    {
        return $query->whereNull('transaction_id');
    }

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

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

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

    public function scopeDateCreatedFilter(Builder $query, $date) : Builder
    {
        $dates = explode(' to ',$date);
        if (isset($dates[1])) {
            return $query->whereHas('transaction', function ($transaction) use ($dates) {
                $transaction->whereBetween('happened_on' ,[$dates[0], $dates[1]]);
            });
        }
        return $query->whereHas('transaction', function ($transaction) use ($dates) {
            $transaction->where('created_at', $dates[0]);
        });
    }

    /**
     * Get all of the balances for the Ledger
     *
     * @return HasMany
     */
    public function balances(): HasMany
    {
        return $this->hasMany(Balance::class);
    }

}
