<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Account extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'account_number',
        'type',
        'bank_name',
        'branch',
        'currency',
        'opening_balance',
        'current_balance',
        'is_active',
        'is_default',
        'description',
    ];

    protected $casts = [
        'opening_balance' => 'decimal:2',
        'current_balance' => 'decimal:2',
        'is_active' => 'boolean',
        'is_default' => 'boolean',
    ];

    /**
     * Transactions in this account
     */
    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class);
    }

    /**
     * Calculate current balance from transactions
     */
    public function calculateBalance(): float
    {
        $credits = $this->transactions()
            ->where('direction', 'credit')
            ->where('status', 'completed')
            ->sum('amount');

        $debits = $this->transactions()
            ->where('direction', 'debit')
            ->where('status', 'completed')
            ->sum('amount');

        return $this->opening_balance + $credits - $debits;
    }

    /**
     * Update current balance
     */
    public function updateBalance(): void
    {
        $this->current_balance = $this->calculateBalance();
        $this->save();
    }

    /**
     * Get the default account
     */
    public static function getDefault(): ?Account
    {
        return self::where('is_default', true)
            ->where('is_active', true)
            ->first();
    }

    /**
     * Scope for active accounts
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
