<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class C1Member extends Model
{
    use SoftDeletes;

    protected $table = 'c1_members';

    protected $fillable = [
        'group_id',
        'serial_no',
        'name',
        'gender',
        'age',
        'active',
        'exec_committee',
        'disability_status',
        'marital_status',
        'head_household',
        'num_hh_members_total',
        'num_hh_female_adult',
        'num_hh_female_adol',
        'num_hh_male_adult',
        'num_hh_male_adol',
        'completed_core_1',
        'completed_core_2',
        'completed_core_3',
        'completed_core_4',
        'received_specialized_1',
        'specialized_1_details',
        'received_in_kind',
        'in_kind_source',
        'received_productive_equip',
        'equip_source',
        'started_new_business',
        'actively_saving_monthly',
        'total_savings',
        'outstanding_loan',
        'month'
    ];

    protected $casts = [
        'month' => 'date:Y-m', // Store as first day of the month
        'gender' => 'string',
        'marital_status' => 'string',
        'active' => 'boolean',
        'exec_committee' => 'boolean',
        'disability_status' => 'boolean',
        'head_household' => 'boolean',
        'completed_core_1' => 'boolean',
        'completed_core_2' => 'boolean',
        'completed_core_3' => 'boolean',
        'completed_core_4' => 'boolean',
        'received_specialized_1' => 'boolean',
        'received_in_kind' => 'boolean',
        'received_productive_equip' => 'boolean',
        'started_new_business' => 'boolean',
        'actively_saving_monthly' => 'boolean',
        'total_savings' => 'decimal:2',
        'outstanding_loan' => 'decimal:2',
    ];

    // === Relationships ===

    /**
     * The VSLA/Community group this member belongs to
     */
    public function group(): BelongsTo
    {
        return $this->belongsTo(C1Group::class, 'group_id');
    }

    /**
     * Supports received by this member (in-kind, equipment, etc.)
     */
    public function supports(): MorphMany
    {
        return $this->morphMany(C1Support::class, 'supportable');
    }

    // === Scopes ===

    /**
     * Scope: Active members only
     */
    public function scopeActive($query)
    {
        return $query->where('active', true);
    }

    /**
     * Scope: Female members
     */
    public function scopeFemale($query)
    {
        return $query->where('gender', 'female');
    }

    /**
     * Scope: Male members
     */
    public function scopeMale($query)
    {
        return $query->where('gender', 'male');
    }

    /**
     * Scope: Adolescent members (14–24 years)
     */
    public function scopeAdolescent($query)
    {
        return $query->whereBetween('age', [14, 24]);
    }

    /**
     * Scope: GBV-vulnerable members
     */
    public function scopeGbvVulnerable($query)
    {
        return $query->where(function ($q) {
            $q->where('disability_status', true)
              ->orWhere('head_household', true)
              ->orWhereIn('marital_status', ['widowed', 'divorced']);
        });
    }

    /**
     * Scope: Members who completed all core trainings
     */
    public function scopeCompletedAllCoreTrainings($query)
    {
        return $query->where('completed_core_1', true)
                     ->where('completed_core_2', true)
                     ->where('completed_core_3', true)
                     ->where('completed_core_4', true);
    }

    /**
     * Scope: Members with active savings
     */
    public function scopeActivelySaving($query)
    {
        return $query->where('actively_saving_monthly', true)
                     ->where('total_savings', '>', 0);
    }

    // === Accessors ===

    /**
     * Total household members (fallback to sum if num_hh_members_total is 0)
     */
    public function getTotalHouseholdMembersAttribute(): int
    {
        return $this->num_hh_members_total > 0
            ? $this->num_hh_members_total
            : ($this->num_hh_female_adult + $this->num_hh_female_adol + $this->num_hh_male_adult + $this->num_hh_male_adol);
    }

    /**
     * Total female adolescents + adults in household
     */
    public function getTotalFemaleHhAttribute(): int
    {
        return $this->num_hh_female_adult + $this->num_hh_female_adol;
    }

    /**
     * Total male adolescents + adults in household
     */
    public function getTotalMaleHhAttribute(): int
    {
        return $this->num_hh_male_adult + $this->num_hh_male_adol;
    }

    /**
     * Is this member a GBV risk? (disability, widow, head of household)
     */
    public function getIsGbvVulnerableAttribute(): bool
    {
        return $this->disability_status || $this->head_household || in_array($this->marital_status, ['widowed', 'divorced']);
    }

    /**
     * Count of completed core trainings
     */
    public function getCoreTrainingsCompletedCountAttribute(): int
    {
        return collect([
            $this->completed_core_1,
            $this->completed_core_2,
            $this->completed_core_3,
            $this->completed_core_4,
        ])->filter()->count();
    }

    /**
     * Formatted savings for display
     */
    public function getFormattedSavingsAttribute(): string
    {
        return number_format($this->total_savings, 2);
    }
}