<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class BankAccount extends Model
{
    use HasFactory, SoftDeletes, LogsActivity;

    protected $fillable = [
        'company_id',
        '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',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($account) {
            // If this is the first account for the company, make it primary
            if (!$account->is_primary) {
                $existingAccounts = self::where('company_id', $account->company_id)->count();
                if ($existingAccounts === 0) {
                    $account->is_primary = true;
                }
            }

            // If setting as primary, unset primary on other accounts
            if ($account->is_primary) {
                self::where('company_id', $account->company_id)
                    ->where('is_primary', true)
                    ->update(['is_primary' => false]);
            }
        });

        static::updating(function ($account) {
            // If setting as primary, unset primary on other accounts
            if ($account->isDirty('is_primary') && $account->is_primary) {
                self::where('company_id', $account->company_id)
                    ->where('id', '!=', $account->id)
                    ->where('is_primary', true)
                    ->update(['is_primary' => false]);
            }
        });
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['account_name', 'bank_name', 'account_number', 'current_balance', 'is_active'])
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function expenses()
    {
        return $this->hasMany(Expense::class);
    }

    public function invoices()
    {
        return $this->hasMany(Invoice::class);
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    public function scopeForCompany($query, $companyId)
    {
        return $query->where('company_id', $companyId);
    }

    // Update balance when money is added (receivable invoice paid)
    public function credit($amount)
    {
        $this->current_balance += $amount;
        $this->save();
    }

    // Update balance when money is deducted (expense)
    public function debit($amount)
    {
        $this->current_balance -= $amount;
        $this->save();
    }
}
