<?php
/**
 * merchant_lib.php
 * Decides WHICH connected merchant (Paytm, PhonePe, BharatPe, GooglePay,
 * SBI, FreeCharge, Mobikwik, HDFC, FamPay...) should be used to generate
 * the next payment link for a given user, based on users.merchant_mode.
 */

/**
 * $connected must be an associative array like:
 *   ['hdfc' => 'Yes', 'phonepe' => 'No', 'paytm' => 'Yes', ...]
 * (exactly the *_connected columns from the users table, keyed by the
 * short merchant type name used elsewhere in the codebase, e.g. Method
 * names / folder routing keys).
 *
 * $mode is users.merchant_mode: 'specific' | 'all' | 'random'
 * $activeType is users.active_merchant_type (used only for 'specific')
 *
 * Returns the merchant type key to use, or null if none are connected.
 */
function pickMerchantType($connected, $mode, $activeType) {
    // Build list of types that are actually connected ("Yes")
    $activeTypes = [];
    foreach ($connected as $type => $status) {
        if ($status === 'Yes') {
            $activeTypes[] = $type;
        }
    }

    if (empty($activeTypes)) {
        return null;
    }

    if ($mode === 'specific') {
        // Use the explicitly chosen merchant, but only if it's still connected.
        if ($activeType && in_array($activeType, $activeTypes, true)) {
            return $activeType;
        }
        // Fall back to the first connected one if the chosen one got disconnected.
        return $activeTypes[0];
    }

    if ($mode === 'random') {
        return $activeTypes[array_rand($activeTypes)];
    }

    // 'all' (default): keep existing behaviour - use whichever is connected,
    // first match wins if more than one is somehow marked Yes at once.
    return $activeTypes[0];
}

/**
 * Convenience: pull the *_connected columns + merchant_mode + active_merchant_type
 * for a user row (as already fetched from `users`) into the shape pickMerchantType needs.
 */
function buildConnectedMapFromUserRow($user) {
    return [
        'hdfc'       => $user['hdfc_connected']       ?? 'No',
        'phonepe'    => $user['phonepe_connected']    ?? 'No',
        'paytm'      => $user['paytm_connected']      ?? 'No',
        'bharatpe'   => $user['bharatpe_connected']   ?? 'No',
        'googlepay'  => $user['googlepay_connected']  ?? 'No',
        'freecharge' => $user['freecharge_connected'] ?? 'No',
        'sbi'        => $user['sbi_connected']        ?? 'No',
        'mobikwik'   => $user['mobikwik_connected']   ?? 'No',
        'fampay'     => $user['fampay_connected']     ?? 'No',
    ];
}
