<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Database\Eloquent\SoftDeletes;

class Organization extends Model
{
    use HasFactory, Auditable, SoftDeletes;

    protected $fillable = [
        'level_id',
        'parent_id',
        'name',
        'code',
        'location',
    ];

    /**
     * The level of this organization (National, Jimbo, Zonal, Local).
     */
    public function level(): BelongsTo
    {
        return $this->belongsTo(Level::class);
    }

    /**
     * Parent organization (for hierarchy).
     */
    public function parent(): BelongsTo
    {
        return $this->belongsTo(Organization::class, 'parent_id');
    }

    /**
     * Child organizations.
     */
    public function children(): HasMany
    {
        return $this->hasMany(Organization::class, 'parent_id');
    }

    /**
     * Users belonging to this organization.
     */
    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

    /**
     * Members registered under this organization.
     */
    public function members(): HasMany
    {
        return $this->hasMany(Member::class);
    }

    /**
     * Leadership board for this organization.
     */
    public function leaders(): HasMany
    {
        return $this->hasMany(OrganizationLeader::class);
    }

    /**
     * Current (active) leaders only.
     */
    public function currentLeaders(): HasMany
    {
        return $this->hasMany(OrganizationLeader::class)
            ->whereNull('ended_at');
    }

    /**
     * Get all descendant organization IDs (recursive).
     */
    public function getDescendantIds(): Collection
    {
        $ids = collect();
        $this->collectDescendantIds($this->id, $ids);
        return $ids;
    }

    protected function collectDescendantIds($parentId, &$ids): void
    {
        $childIds = Organization::where('parent_id', $parentId)->pluck('id');
        foreach ($childIds as $childId) {
            $ids->push($childId);
            $this->collectDescendantIds($childId, $ids);
        }
    }

    /**
     * Get total member count (including all descendants).
     */
    public function getTotalMemberCountAttribute(): int
    {
        $orgIds = $this->getDescendantIds();
        $orgIds->push($this->id);
        return Member::whereIn('organization_id', $orgIds)->count();
    }

    /**
     * Get direct member count (this org only).
     */
    public function getDirectMemberCountAttribute(): int
    {
        return $this->members()->count();
    }

    /**
     * Get total contributions (including all descendants).
     */
    public function getTotalContributionsAttribute(): float
    {
        $orgIds = $this->getDescendantIds();
        $orgIds->push($this->id);
        
        return Contribution::whereHas('member', function ($q) use ($orgIds) {
            $q->whereIn('organization_id', $orgIds);
        })->sum('amount');
    }

    /**
     * Get breadcrumb path from root to this org.
     */
    public function getBreadcrumbAttribute(): Collection
    {
        $path = collect([$this]);
        $current = $this;
        
        while ($current->parent_id) {
            $current = $current->parent;
            $path->prepend($current);
        }
        
        return $path;
    }

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

    /**
     * Get full hierarchy name (e.g., "ATAPE Tanzania > East Zone > Dar Jimbo").
     */
    public function getFullPathAttribute(): string
    {
        return $this->breadcrumb->pluck('name')->implode(' > ');
    }
}

