<?php

function paymentMethodOptions() {
    return [
        'cash' => 'Cash',
        'cheque' => 'Cheque',
        'mobile_money' => 'Mobile Money',
        'bank_transfer' => 'Bank Transfer',
        'card' => 'Card',
        'pos' => 'POS',
        'other' => 'Other',
    ];
}

function normalizePaymentMethodValue($value, $default = 'cash') {
    $value = strtolower(trim((string)$value));
    $value = str_replace(['-', ' '], '_', $value);

    $aliases = [
        'check' => 'cheque',
        'mobile' => 'mobile_money',
        'momo' => 'mobile_money',
        'mobilemoney' => 'mobile_money',
        'bank' => 'bank_transfer',
        'transfer' => 'bank_transfer',
        'banktransfer' => 'bank_transfer',
        'wire' => 'bank_transfer',
        'credit_card' => 'card',
        'debit_card' => 'card',
        'swipe' => 'pos',
        'terminal' => 'pos',
    ];

    $value = $aliases[$value] ?? $value;
    return array_key_exists($value, paymentMethodOptions()) ? $value : $default;
}

function paymentMethodLabel($value) {
    $normalized = normalizePaymentMethodValue($value);
    $options = paymentMethodOptions();
    return $options[$normalized] ?? $options['cash'];
}

function paymentMethodSelectOptions($selected = 'cash') {
    $selected = normalizePaymentMethodValue($selected);
    $html = '';
    foreach (paymentMethodOptions() as $value => $label) {
        $isSelected = $value === $selected ? ' selected' : '';
        $html .= '<option value="' . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . '"' . $isSelected . '>'
            . htmlspecialchars($label, ENT_QUOTES, 'UTF-8') . '</option>';
    }
    return $html;
}

function paymentMethodToEis($value, $default = 'CASH') {
    $map = [
        'cash' => 'CASH',
        'cheque' => 'CHEQUE',
        'mobile_money' => 'MOBILE_MONEY',
        'bank_transfer' => 'BANK_TRANSFER',
        'card' => 'CARD',
        'pos' => 'CARD',
    ];
    $normalized = normalizePaymentMethodValue($value, 'other');
    return $map[$normalized] ?? $default;
}
