<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberKinModel extends Model
{
    protected $table = 'member_kin';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'member_id', 'full_name', 'gender', 'relationship', 'date_of_birth',
        'benefits', 'installment_one_amount', 'installment_one_selected',
        'installment_two_amount', 'installment_two_selected',
        'address', 'phone', 'email', 'created_at', 'updated_at',
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    protected $validationRules = [
        'member_id' => 'required|numeric',
        'full_name' => 'required',
        'relationship' => 'required',
        'benefits' => 'permit_empty|numeric|greater_than_equal_to[0]|less_than_equal_to[100]',
    ];

    public function getByMember($memberId)
    {
        return $this->where('member_id', $memberId)
            ->orderBy('installment_one_selected', 'DESC')
            ->orderBy('installment_two_selected', 'DESC')
            ->orderBy('full_name', 'ASC')
            ->findAll();
    }

    public function getTotalBenefitsByMember($memberId)
    {
        $result = $this->selectSum('benefits')
            ->where('member_id', $memberId)
            ->first();

        return (float) ($result['benefits'] ?? 0);
    }

    public function getSelectedInstallmentBeneficiaryByMember($memberId, int $installmentNumber): ?array
    {
        $selectionColumn = $installmentNumber === 2 ? 'installment_two_selected' : 'installment_one_selected';

        $selected = $this->where('member_id', $memberId)
            ->where($selectionColumn, 1)
            ->first();

        if ($selected !== null) {
            return $selected;
        }

        return $this->where('member_id', $memberId)
            ->where('benefits', $installmentNumber)
            ->first();
    }
}
