<?php

namespace App\Models;

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

class C2SeedlabBeneficiary extends Model
{
    use SoftDeletes;

    protected $table = 'c2_seedlab_beneficiaries';

    protected $guarded = ['id'];

    protected $casts = [
        'age' => 'integer',
        'woef_connect_participation' => 'integer',
        'sn' => 'integer',
    ];

    /**
     * Optional link back to a VSLA group from Component 1
     */
    public function group(): BelongsTo
    {
        return $this->belongsTo(C1Group::class, 'group_id');
    }

    /**
     * Polymorphic one-to-one relationship with c2_grants
     */
    public function grant(): MorphOne
    {
        return $this->morphOne(C2Grant::class, 'grantable');
    }

    /**
     * Helper: Count how many modules are completed
     */
    public function getCompletedModulesCountAttribute(): int
    {
        $modules = ['module_1', 'module_2', 'module_3', 'module_4', 'module_5', 'module_6', 'module_7', 'module_8'];
        return collect($modules)->filter(fn($m) => $this->$m === 'Completed')->count();
    }

    /**
     * Helper: Check if all 8 modules are completed
     */
    public function getIsFullyTrainedAttribute(): bool
    {
        return $this->completed_modules_count === 8;
    }
}