<?php

namespace App\Models;

class MemberModel extends BaseModel
{
    protected $table      = 'members';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'uuid', 'church_id', 'user_id', 'first_name', 'last_name', 'email',
        'phone', 'address', 'date_of_birth', 'gender', 'marital_status',
        'membership_type', 'membership_date', 'is_active', 'is_committee',
        'occupation', 'notes', 'photo',
    ];

    public function getStats(int $churchId): array
    {
        $db = \Config\Database::connect();

        $base = $db->table('members')
                   ->where('church_id', $churchId)
                   ->where('deleted_at IS NULL');

        $total    = (clone $base)->countAllResults();
        $active   = (clone $base)->where('is_active', 1)->countAllResults();
        $inactive = (clone $base)->where('is_active', 0)->countAllResults();

        $byType = $db->table('members')
                     ->select('membership_type, COUNT(*) as count')
                     ->where('church_id', $churchId)
                     ->where('deleted_at IS NULL')
                     ->groupBy('membership_type')
                     ->get()->getResultArray();

        return [
            'total'          => $total,
            'active'         => $active,
            'inactive'       => $inactive,
            'by_type'        => $byType,
        ];
    }
}
