<?php

namespace App\Models;

use CodeIgniter\Model;

class ClaimModel extends Model
{
    protected $table = 'claims';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = [
        'member_id', 'claim_type', 'claim_no', 'date_reported',
        'date_of_incident', 'total_amount', 'status', 'submitted_by',
        'reviewed_by', 'approved_at', 'paid_at', 'rejection_reason',
        'documents', 'notes'
    ];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    protected $validationRules = [
        'member_id' => 'required|numeric',
        'claim_type' => 'required|in_list[death,disability,other]',
        'date_reported' => 'required|valid_date[Y-m-d]',
    ];

    public function generateClaimNo()
    {
        $timestamp = time();
        $random = mt_rand(100000, 999999);
        return "CLM" . date('Y') . $timestamp . $random;
    }

    public function getClaimsByMember($memberId)
    {
        return $this->where('member_id', $memberId)
            ->orderBy('date_reported', 'DESC')
            ->findAll();
    }

    public function getPendingClaims()
    {
        return $this->where('status', 'submitted')
            ->orWhere('status', 'under_review')
            ->findAll();
    }

    public function getApprovedClaims()
    {
        return $this->where('status', 'approved')
            ->findAll();
    }

    public function getPaidClaims()
    {
        return $this->where('status', 'paid')
            ->findAll();
    }

    public function getTotalClaimAmount($status = null)
    {
        $query = $this->selectSum('total_amount');
        if ($status) {
            $query = $query->where('status', $status);
        }
        $result = $query->first();
        return $result['total_amount'] ?? 0;
    }

    public function getClaimsByStatus($status)
    {
        return $this->where('status', $status)
            ->orderBy('date_reported', 'DESC')
            ->findAll();
    }

    public function getRecentClaims($limit = 10)
    {
        return $this->orderBy('date_reported', 'DESC')
            ->limit($limit)
            ->findAll();
    }
}
