<?php

namespace App\Models;

use CodeIgniter\Model;

class ClaimBeneficiaryModel extends Model
{
    protected $table = 'claim_beneficiaries';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'claim_id', 'beneficiary_id', 'amount', 'status',
        'payment_date', 'payment_method'
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    protected $validationRules = [
        'claim_id' => 'required|numeric',
        'beneficiary_id' => 'required|numeric',
        'amount' => 'required|numeric|greater_than[0]',
    ];

    public function getBeneficiariesByClaimWithDetails($claimId)
    {
        return $this->select('claim_beneficiaries.*, beneficiaries.name, beneficiaries.phone, beneficiaries.email')
            ->join('beneficiaries', 'beneficiaries.id = claim_beneficiaries.beneficiary_id')
            ->where('claim_id', $claimId)
            ->findAll();
    }

    public function getTotalClaimBeneficiaryAmount($claimId)
    {
        $result = $this->selectSum('amount')
            ->where('claim_id', $claimId)
            ->first();
        
        return $result['amount'] ?? 0;
    }

    public function getPaidBeneficiaryAmount($claimId)
    {
        $result = $this->selectSum('amount')
            ->where('claim_id', $claimId)
            ->where('status', 'paid')
            ->first();
        
        return $result['amount'] ?? 0;
    }

    public function getUnpaidBeneficiaries($claimId)
    {
        return $this->where('claim_id', $claimId)
            ->whereIn('status', ['pending', 'approved'])
            ->findAll();
    }
}
