<?php
/**
 * Fellowship categorisation by age and gender
 * 0-12: Children's Service
 * 12-18: Junior Youth
 * 18-30: YPG
 * 30-40: YAF
 * 40+: Men's Fellowship (M) / Women's Fellowship (F)
 */

function getMemberAge($dateOfBirth, $dateOfDeath = null) {
    if (empty($dateOfBirth)) return null;
    $dob = new DateTime($dateOfBirth);
    $endDate = !empty($dateOfDeath) ? new DateTime($dateOfDeath) : new DateTime();
    return $dob->diff($endDate)->y;
}

function getMemberFellowship($dateOfBirth, $gender) {
    $age = getMemberAge($dateOfBirth);
    if ($age === null) return null;

    if ($age < 12) return "Children's Service";
    if ($age < 18) return 'Junior Youth';
    if ($age < 30) return 'YPG';
    if ($age < 40) return 'YAF';

    $g = strtoupper(trim($gender ?? ''));
    if ($g === 'MALE' || $g === 'M') return "Men's Fellowship";
    if ($g === 'FEMALE' || $g === 'F') return "Women's Fellowship";
    return 'Fellowship (40+)';
}

/**
 * Whether a member can belong to a ministry.
 * Only YPG and above (18+) can belong to ministries; children and junior youth cannot.
 */
function canBelongToMinistry($dateOfBirth) {
    $age = getMemberAge($dateOfBirth);
    if ($age === null) return true; // No DOB: allow (e.g. adult without DOB on file)
    return $age >= 18;
}

function getFellowshipOrder() {
    return [
        "Children's Service",
        'Junior Youth',
        'YPG',
        'YAF',
        "Men's Fellowship",
        "Women's Fellowship",
        'Fellowship (40+)',
        null,  // Unknown
    ];
}
