<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\Market\UserInfo;

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

    protected array $fillable = [
        'hashkey', 'name', 'cooperative_id', '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 cooperative()
    {
        return $this->belongsTo(\App\Models\Market\Organization::class, 'cooperative_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');
    }

    /**
     * Find or create a chapter by level + location_key (normalized address field).
     */
    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'     => \Ramsey\Uuid\Uuid::uuid4()->toString(),
                'name'        => ucwords(strtolower($locationKey)),
                'level'       => $level,
                'location_key'=> $key,
                'parent_id'   => $parentId,
                'is_active'   => true,
            ]
        );
    }

    /**
     * Auto-assign a user to the appropriate chapters based on their UserInfo address.
     * Creates chapter records on the fly if they don't exist.
     */
    public static function autoAssignUser(int $userId): void
    {
        $info = UserInfo::where('user_id', $userId)->first();
        if (!$info) {
            return;
        }

        $national = static::firstOrCreate(
            ['level' => 'national', 'location_key' => 'philippines'],
            ['hashkey' => \Ramsey\Uuid\Uuid::uuid4()->toString(), 'name' => 'Philippines', 'level' => 'national', 'location_key' => 'philippines', 'is_active' => true]
        );

        ChapterMember::syncAutoAssignment($userId, $national->id);

        if ($info->region) {
            $region = static::findOrCreateByLocation('region', $info->region, $national->id);
            ChapterMember::syncAutoAssignment($userId, $region->id);

            if ($info->province) {
                $province = static::findOrCreateByLocation('province', $info->province, $region->id);
                ChapterMember::syncAutoAssignment($userId, $province->id);

                if ($info->city) {
                    $city = static::findOrCreateByLocation('city', $info->city, $province->id);
                    ChapterMember::syncAutoAssignment($userId, $city->id);

                    if ($info->barangay) {
                        $barangay = static::findOrCreateByLocation('barangay', $info->barangay, $city->id);
                        ChapterMember::syncAutoAssignment($userId, $barangay->id);
                    }
                }
            }
        }
    }
}
