<?php
/**
 * Member date validation – used by main app and PWA when saving members.
 * Baptism date cannot be earlier than date of birth.
 * Date of death (if any) cannot be earlier than date of birth.
 */

/**
 * Validate member dates. Returns array of error messages (empty if valid).
 *
 * @param string|null $dateOfBirth
 * @param string|null $baptismDate
 * @param string|null $dateOfDeath
 * @param string|null $confirmationDate
 * @return string[]
 */
function validateMemberDates($dateOfBirth, $baptismDate, $dateOfDeath = null, $confirmationDate = null) {
    $errors = [];

    if ($baptismDate !== null && $baptismDate !== '' && $dateOfBirth !== null && $dateOfBirth !== '') {
        $dob = DateTime::createFromFormat('Y-m-d', $dateOfBirth);
        $bap = DateTime::createFromFormat('Y-m-d', $baptismDate);
        if ($dob && $bap && $bap < $dob) {
            $errors[] = 'Baptism date cannot be earlier than date of birth.';
        }
    }

    if ($confirmationDate !== null && $confirmationDate !== '' && $dateOfBirth !== null && $dateOfBirth !== '') {
        $dob = DateTime::createFromFormat('Y-m-d', $dateOfBirth);
        $conf = DateTime::createFromFormat('Y-m-d', $confirmationDate);
        if ($dob && $conf && $conf < $dob) {
            $errors[] = 'Confirmation date cannot be earlier than date of birth.';
        }
    }

    if ($dateOfDeath !== null && $dateOfDeath !== '' && $dateOfBirth !== null && $dateOfBirth !== '') {
        $dob = DateTime::createFromFormat('Y-m-d', $dateOfBirth);
        $dod = DateTime::createFromFormat('Y-m-d', $dateOfDeath);
        if ($dob && $dod && $dod < $dob) {
            $errors[] = 'Date of death cannot be earlier than date of birth.';
        }
    }

    return $errors;
}
