<?php

namespace App\Models;

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

class Organization extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'short_name',
        'country',
        'city',
        'postal_address',
        'postal_code',
        'physical_address',
        'email',
        'hotline',
        'year_of_formation',
        'social_media_links',
    ];

    protected $casts = [
        'social_media_links' => 'array',
        'year_of_formation' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function leadershipPositions()
    {
        return $this->hasMany(LeadershipPosition::class);
    }

    public function electionCycles()
    {
        return $this->hasMany(ElectionCycle::class);
    }

    public function votingProcedures()
    {
        return $this->hasMany(VotingProcedure::class);
    }

    public function leadershipHistories()
    {
        return $this->hasMany(LeadershipHistory::class);
    }

    public function staffHistories()
    {
        return $this->hasMany(StaffHistory::class);
    }

    public function rootLeadershipPositions()
    {
        return $this->hasMany(LeadershipPosition::class)->whereNull('parent_position_id');
    }

    public function getCurrentLeadershipAssignments()
    {
        return LeadershipAssignment::whereHas('leadershipPosition', function ($query) {
            $query->where('organization_id', $this->id);
        })->where('is_current', true)->with(['user', 'leadershipPosition'])->get();
    }

    public function getFullAddressAttribute(): string
    {
        return "{$this->physical_address}, {$this->city}, {$this->country}";
    }

    public function getSocialMediaLink(string $platform): ?string
    {
        return $this->social_media_links[$platform] ?? null;
    }

    public function getAgeAttribute(): int
    {
        return now()->year - $this->year_of_formation;
    }
}
