<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Staudenmeir\EloquentHasManyDeep\HasRelationships;
use App\Classes\ValueObjects\Constants\ApprovalStatus;

class StatementTransaction extends Model
{
    use HasRelationships;

    use HasFactory;

    protected $fillable = [
        'account_statement_id',
        'transaction_date',
        'posting_date',
        'transaction_description',
        'transaction_description_2',
        'transaction_description_3',
        'transaction_description_4',
        'transaction_description_5',
        'transaction_ref',
        'amount',
        'teller_id',
        'branch_channel',
        'transaction_code',
        'end_balance',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'posting_date' => 'datetime',
        ];
    }

    public function account()
    {
        return $this->hasOneDeep(StatementAccount::class, [AccountStatement::class], ['id', 'id'], ['account_statement_id', 'statement_account_id']);
    }

    public function statement()
    {
        return $this->belongsTo(AccountStatement::class, 'account_statement_id', 'id');
    }

    public function owners()
    {
        return $this->hasMany(StatementTransactionOwner::class);
    }

    public function owner_status()
    {
        return $this->owners()->whereIn('status',[ApprovalStatus::APPROVED,ApprovalStatus::COMPLETED,ApprovalStatus::PENDING_VERIFICATION]);
    }

    public function scopeDoesntMapStatement($query)
    {
        $query->whereDoesntHave('owners', function($query){
            return $query->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
        })->orderBy('posting_date');
    }
}
