<?php

namespace App\Models;

use CodeIgniter\Model;

class BeneficiaryModel extends Model
{
    protected $table = 'beneficiaries';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'member_id', 'name', 'relationship', 'percentage', 
        'phone', 'email', 'address', 'date_of_birth', 'status'
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    protected $validationRules = [
        'member_id' => 'required|numeric',
        'name' => 'required',
        'relationship' => 'required',
        'percentage' => 'required|numeric|greater_than[0]|less_than_equal_to[100]',
    ];

    public function getBeneficiariesByMember($memberId)
    {
        return $this->where('member_id', $memberId)
            ->where('status', 'active')
            ->findAll();
    }

    public function validatePercentageDistribution($memberId)
    {
        $result = $this->selectSum('percentage')
            ->where('member_id', $memberId)
            ->first();
        
        return isset($result['percentage']) && $result['percentage'] == 100;
    }

    public function getTotalPercentageByMember($memberId)
    {
        $result = $this->selectSum('percentage')
            ->where('member_id', $memberId)
            ->first();
        
        return $result['percentage'] ?? 0;
    }
}
