<?php

declare(strict_types=1);

namespace App\Models;

class Chapter extends Model
{
    protected ?string $table = 'chapters';

    protected array $fillable = [
        'hashkey', 'name', 'level', 'parent_id', 'location_key',
        'lat', 'lng', 'is_active', 'created_by', 'updated_by',
    ];

    protected array $casts = [
        'is_active' => 'boolean',
        'lat'       => 'float',
        'lng'       => 'float',
    ];

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

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

    public function chapterMembers()
    {
        return $this->hasMany(ChapterMember::class, 'chapter_id');
    }

    public function activeMembers()
    {
        return $this->chapterMembers()->where('is_active', true);
    }

    public function leaders()
    {
        return $this->activeMembers()->whereNotNull('position');
    }

    public static function findOrCreateByLocation(string $level, string $locationKey, ?int $parentId = null): self
    {
        $key = strtolower(trim($locationKey));
        return static::firstOrCreate(
            ['level' => $level, 'location_key' => $key],
            [
                'hashkey'      => hash('sha256', uniqid((string) now(), true)),
                'name'         => ucwords(strtolower($locationKey)),
                'level'        => $level,
                'location_key' => $key,
                'parent_id'    => $parentId,
                'is_active'    => true,
            ]
        );
    }
}
