<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SuperAdminBankAccount extends Model
{
    use HasFactory;

    protected $fillable = [
        'account_name',
        'bank_name',
        'account_number',
        'account_type',
        'currency',
        'opening_balance',
        'current_balance',
        'is_primary',
        'is_active',
        'notes',
    ];

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

    /**
     * Credit (add money to) the account
     */
    public function credit(float $amount): void
    {
        $this->current_balance += $amount;
        $this->save();
    }

    /**
     * Debit (subtract money from) the account
     */
    public function debit(float $amount): void
    {
        if ($this->current_balance < $amount) {
            throw new \Exception('Insufficient balance');
        }
        $this->current_balance -= $amount;
        $this->save();
    }

    /**
     * Get the primary bank account
     */
    public static function getPrimary(): ?self
    {
        return self::where('is_primary', true)->where('is_active', true)->first();
    }

    /**
     * Get all active accounts
     */
    public static function getActive()
    {
        return self::where('is_active', true)->get();
    }
}
