<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Account extends Model
{
    protected $fillable = [
        'parent_id',
        'code',
        'name',
        'name_ar',
        'type',
        'description',
        'is_system',
        'is_group',
        'is_active',
    ];

    protected $casts = [
        'is_system' => 'boolean',
        'is_group' => 'boolean',
        'is_active' => 'boolean',
    ];

    public function parent(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'parent_id');
    }

    public function children(): HasMany
    {
        return $this->hasMany(Account::class, 'parent_id');
    }

    public function journalEntryLines(): HasMany
    {
        return $this->hasMany(JournalEntryLine::class);
    }

    public function paymentMethods(): HasMany
    {
        return $this->hasMany(PaymentMethod::class);
    }

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

    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }

    public function scopeAssets($query)
    {
        return $query->where('type', 'asset');
    }

    public function scopeLiabilities($query)
    {
        return $query->where('type', 'liability');
    }

    public function scopeEquity($query)
    {
        return $query->where('type', 'equity');
    }

    public function scopeRevenue($query)
    {
        return $query->where('type', 'revenue');
    }

    public function scopeExpenses($query)
    {
        return $query->where('type', 'expense');
    }

    public function scopeRoots($query)
    {
        return $query->whereNull('parent_id');
    }

    /**
     * Get localized name
     */
    public function getLocalizedNameAttribute(): string
    {
        $locale = app()->getLocale();
        
        if ($locale === 'ar' && !empty($this->name_ar)) {
            return $this->name_ar;
        }

        return $this->name;
    }

    /**
     * Get type label
     */
    public function getTypeLabelAttribute(): string
    {
        return match ($this->type) {
            'asset' => __('Asset'),
            'liability' => __('Liability'),
            'equity' => __('Equity'),
            'revenue' => __('Revenue'),
            'expense' => __('Expense'),
            default => $this->type,
        };
    }

    /**
     * Calculate account balance
     */
    public function getBalance(): float
    {
        $debits = $this->journalEntryLines()->sum('debit');
        $credits = $this->journalEntryLines()->sum('credit');

        // For Assets and Expenses: Debit increases balance
        // For Liabilities, Equity, Revenue: Credit increases balance
        return in_array($this->type, ['asset', 'expense'])
            ? $debits - $credits
            : $credits - $debits;
    }

    /**
     * Check if account can be deleted
     */
    public function canDelete(): bool
    {
        return !$this->is_system && 
               $this->children()->count() === 0 && 
               $this->journalEntryLines()->count() === 0;
    }

    /**
     * Get all account types
     */
    public static function types(): array
    {
        return [
            'asset' => __('Asset'),
            'liability' => __('Liability'),
            'equity' => __('Equity'),
            'revenue' => __('Revenue'),
            'expense' => __('Expense'),
        ];
    }
}
