<?php
// Mirrors the original app's validateCwsnForm() logic field-for-field, so
// the PHP version enforces exactly the same rules. Returns an assoc array
// of field => error message; empty array means fully valid/complete.

const NAME_PATTERN = '/^\S+(?: \S+)*$/';           // no leading/trailing or double spaces
const ADDRESS_PATTERN = '/^[a-zA-Z0-9\s.()-]+$/';
const PIN_PATTERN = '/^[1-9][0-9]{5}$/';
const CONTACT_PATTERN = '/^[6789][0-9]{9}$/';
const AADHAAR_PATTERN = '/^[0-9]{12}$/';
const DOB_MIN_AGE_YEARS = 2;
const DOB_MAX_AGE_YEARS = 30;
const NOT_APPLICABLE = 'NOT APPLICABLE';

function isBlank($v): bool {
    return $v === null || trim((string)$v) === '';
}

/** @param array $f the posted/loaded CWSN fields (associative) */
function validateCwsn(array $f): array {
    $errors = [];
    $REQUIRED = 'This field is required.';
    $YN_REQUIRED = 'Please select Yes or No.';

    if (isBlank($f['clucd'] ?? null)) $errors['clucd'] = 'Please select a school / cluster.';
    if (isBlank($f['cwsn_name'] ?? null)) $errors['cwsn_name'] = $REQUIRED;
    if (isBlank($f['dob'] ?? null)) $errors['dob'] = $REQUIRED;
    if (isBlank($f['gender'] ?? null)) $errors['gender'] = $REQUIRED;
    if (isBlank($f['cwsn_f_name'] ?? null)) $errors['cwsn_f_name'] = $REQUIRED;
    if (isBlank($f['cwsn_m_name'] ?? null)) $errors['cwsn_m_name'] = $REQUIRED;
    if (isBlank($f['add1'] ?? null)) $errors['add1'] = $REQUIRED;
    if (isBlank($f['add2'] ?? null)) $errors['add2'] = $REQUIRED;
    if (isBlank($f['add3'] ?? null)) $errors['add3'] = $REQUIRED;
    if (isBlank($f['pin'] ?? null)) $errors['pin'] = $REQUIRED;
    if (isBlank($f['contact_no'] ?? null)) $errors['contact_no'] = $REQUIRED;
    if (isBlank($f['disability_id'] ?? null)) $errors['disability_id'] = 'Please select a disability type.';
    if (isBlank($f['dis_certi_yn'] ?? null)) $errors['dis_certi_yn'] = $YN_REQUIRED;
    if (isBlank($f['therapy_reqd_yn'] ?? null)) $errors['therapy_reqd_yn'] = $YN_REQUIRED;
    if (isBlank($f['manabik_yn'] ?? null)) $errors['manabik_yn'] = $YN_REQUIRED;
    if (isBlank($f['in_school_yn'] ?? null)) $errors['in_school_yn'] = $YN_REQUIRED;

    if (!isBlank($f['cwsn_name'] ?? null)) {
        if (!preg_match(NAME_PATTERN, $f['cwsn_name'])) $errors['cwsn_name'] = 'No leading/trailing or repeated spaces allowed.';
        elseif (strlen($f['cwsn_name']) > 75) $errors['cwsn_name'] = 'Maximum 75 characters.';
    }
    if (!isBlank($f['cwsn_f_name'] ?? null)) {
        if (!preg_match(NAME_PATTERN, $f['cwsn_f_name'])) $errors['cwsn_f_name'] = 'No leading/trailing or repeated spaces allowed.';
        elseif (strlen($f['cwsn_f_name']) > 75) $errors['cwsn_f_name'] = 'Maximum 75 characters.';
    }
    if (!isBlank($f['cwsn_m_name'] ?? null)) {
        if (!preg_match(NAME_PATTERN, $f['cwsn_m_name'])) $errors['cwsn_m_name'] = 'No leading/trailing or repeated spaces allowed.';
        elseif (strlen($f['cwsn_m_name']) > 75) $errors['cwsn_m_name'] = 'Maximum 75 characters.';
    }
    if (!isBlank($f['add1'] ?? null)) {
        if (!preg_match(ADDRESS_PATTERN, $f['add1'])) $errors['add1'] = 'Only letters, numbers, spaces, . ( ) - are allowed.';
        elseif (strlen($f['add1']) > 100) $errors['add1'] = 'Maximum 100 characters.';
    }
    if (!isBlank($f['add2'] ?? null)) {
        if (!preg_match(ADDRESS_PATTERN, $f['add2'])) $errors['add2'] = 'Only letters, numbers, spaces, . ( ) - are allowed.';
        elseif (strlen($f['add2']) > 100) $errors['add2'] = 'Maximum 100 characters.';
    }
    if (!isBlank($f['add3'] ?? null)) {
        if (!preg_match(ADDRESS_PATTERN, $f['add3'])) $errors['add3'] = 'Only letters, numbers, spaces, . ( ) - are allowed.';
        elseif (strlen($f['add3']) > 60) $errors['add3'] = 'Maximum 60 characters.';
    }
    if (!isBlank($f['pin'] ?? null) && !preg_match(PIN_PATTERN, $f['pin'])) {
        $errors['pin'] = 'Enter a valid 6-digit PIN code (cannot start with 0).';
    }
    if (!isBlank($f['contact_no'] ?? null) && !preg_match(CONTACT_PATTERN, $f['contact_no'])) {
        $errors['contact_no'] = 'Enter a valid 10-digit mobile number starting with 6, 7, 8, or 9.';
    }
    if (!isBlank($f['aadhaar'] ?? null) && !preg_match(AADHAAR_PATTERN, $f['aadhaar'])) {
        $errors['aadhaar'] = 'Aadhaar number must be exactly 12 digits.';
    }

    if (!isBlank($f['dob'] ?? null)) {
        $dob = DateTime::createFromFormat('Y-m-d', $f['dob']);
        if (!$dob) {
            $errors['dob'] = 'Invalid date.';
        } else {
            $today = new DateTime();
            $minDob = (clone $today)->modify('-' . DOB_MAX_AGE_YEARS . ' years');
            $maxDob = (clone $today)->modify('-' . DOB_MIN_AGE_YEARS . ' years');
            if ($dob < $minDob || $dob > $maxDob) {
                $errors['dob'] = 'CWSN age must be between ' . DOB_MIN_AGE_YEARS . ' and ' . DOB_MAX_AGE_YEARS . ' years.';
            }
        }
    }

    if (($f['dis_certi_yn'] ?? '') === 'YES' && isBlank($f['dis_certi_valid_yn'] ?? null)) {
        $errors['dis_certi_valid_yn'] = $YN_REQUIRED;
    }
    if (($f['therapy_reqd_yn'] ?? '') === 'YES' && isBlank($f['therapy_provide_yn'] ?? null)) {
        $errors['therapy_provide_yn'] = $YN_REQUIRED;
    }
    if (($f['in_school_yn'] ?? '') === 'YES' && isBlank($f['school_awc'] ?? null)) {
        $errors['school_awc'] = 'Please select School or AWC.';
    }
    if (($f['school_awc'] ?? '') === 'SCHOOL') {
        if (isBlank($f['schcd'] ?? null)) $errors['schcd'] = 'Please select the school from the list.';
        if (isBlank($f['class'] ?? null)) $errors['class'] = 'Please select the class.';
    }
    if (($f['school_awc'] ?? '') === 'AWC' && isBlank($f['awc_no'] ?? null)) {
        $errors['awc_no'] = 'Please select the AWC from the list.';
    }

    if (!isBlank($f['ifsc'] ?? null)) {
        if (isBlank($f['bank_id'] ?? null)) $errors['ifsc'] = 'Please select a valid IFSC from the list.';
        if (isBlank($f['branch_name'] ?? null)) $errors['branch_name'] = 'Please select your specific branch.';
        if (isBlank($f['acno'] ?? null)) $errors['acno'] = 'Account number is required once an IFSC is selected.';
        if (isBlank($f['ac_holder'] ?? null)) $errors['ac_holder'] = 'Please choose the account holder.';
    }
    if (!isBlank($f['ac_holder'] ?? null)) {
        $holder = strtoupper(trim($f['ac_holder']));
        $candidates = array_map(fn($n) => strtoupper(trim($n ?? '')), [
            $f['cwsn_name'] ?? '', $f['cwsn_f_name'] ?? '', $f['cwsn_m_name'] ?? '',
        ]);
        if (!in_array($holder, $candidates, true)) {
            $errors['ac_holder'] = "Account holder name must match the CWSN's, father's, or mother's name.";
        }
    }

    return $errors;
}

/** Applies the NOT APPLICABLE sentinel to sub-answers whose parent was 'NO'. Call after validation passes. */
function applyNotApplicableDefaults(array $f): array {
    if (($f['dis_certi_yn'] ?? '') === 'NO') $f['dis_certi_valid_yn'] = NOT_APPLICABLE;
    if (($f['therapy_reqd_yn'] ?? '') === 'NO') $f['therapy_provide_yn'] = NOT_APPLICABLE;
    return $f;
}
