<?php
require_once "KLogger.php";
$UtilLogger = new KLogger(STRIPE_LOG_FILE, KLogger::DEBUG);

function GetPaymentMethod(string $CustomerID, string $SubscriptionID, string &$CardType, string &$CardBrand, string &$CardLastFour, string &$CardExpMonth, string &$CardExpYear): string
{
    global $UtilLogger;

    $CardType     = '';
    $CardBrand    = '';
    $CardLastFour = '';
    $CardExpMonth = '';
    $CardExpYear  = '';

    require_once STRIPE_INIT_LOCATION;
    $myStripeClient = new \Stripe\StripeClient(STRIPE_SECRET_KEY);

    $PaymentMethodID = '';

    try {
        // --- Resolve the payment method ID using the same precedence as GetSubscriptionPaymentDefaultID ---
        $myCustomer = null;
        if (trim($CustomerID) != '') {
            $myCustomer = $myStripeClient->customers->retrieve($CustomerID);
        }

        if ($myCustomer != null) {
            if (trim($SubscriptionID) != '') {
                $mySubscription = $myStripeClient->subscriptions->retrieve($SubscriptionID);
                if ($mySubscription != null) {
                    // 1. Subscription-level default payment method (modern)
                    if (!empty($mySubscription->default_payment_method)) {
                        $PaymentMethodID = is_string($mySubscription->default_payment_method)
                            ? $mySubscription->default_payment_method
                            : $mySubscription->default_payment_method->id;
                        $UtilLogger->LogDebug("GetPaymentMethod: source=subscription.default_payment_method | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
                    }
                    // 2. Subscription-level default source (legacy)
                    elseif (!empty($mySubscription->default_source)) {
                        $PaymentMethodID = is_string($mySubscription->default_source)
                            ? $mySubscription->default_source
                            : $mySubscription->default_source->id;
                        $UtilLogger->LogDebug("GetPaymentMethod: source=subscription.default_source | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
                    }
                }
            }

            if ($PaymentMethodID == '') {
                // 3. Customer invoice settings default payment method (modern)
                if (!empty($myCustomer->invoice_settings->default_payment_method)) {
                    $PaymentMethodID = is_string($myCustomer->invoice_settings->default_payment_method)
                        ? $myCustomer->invoice_settings->default_payment_method
                        : $myCustomer->invoice_settings->default_payment_method->id;
                    $UtilLogger->LogDebug("GetPaymentMethod: source=customer.invoice_settings.default_payment_method | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
                }
                // 4. Customer default source (legacy)
                elseif (!empty($myCustomer->default_source)) {
                    $PaymentMethodID = is_string($myCustomer->default_source)
                        ? $myCustomer->default_source
                        : $myCustomer->default_source->id;
                    $UtilLogger->LogDebug("GetPaymentMethod: source=customer.default_source | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
                }
            }
        }

        if ($PaymentMethodID == '') {
            return '';
        }

        // --- Resolve the ID to an object and extract type/card details ---

        if (substr($PaymentMethodID, 0, 3) === 'pm_') {
            // Modern PaymentMethod object
            $UtilLogger->LogDebug("GetPaymentMethod: id_type=pm_ (modern PaymentMethod) | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
            $pm = $myStripeClient->paymentMethods->retrieve($PaymentMethodID);

            if ($pm->type === 'card') {
                $card       = $pm->card;
                $walletType = !empty($card->wallet) ? $card->wallet->type : '';

                if ($walletType === 'apple_pay') {
                    $CardType = 'ApplePay';
                } elseif ($walletType === 'google_pay') {
                    $CardType = 'GooglePay';
                } else {
                    $CardType = $card->funding; // credit, debit, prepaid, unknown
                }

                $CardBrand    = $card->brand;
                $CardLastFour = $card->last4;
                $CardExpMonth = $card->exp_month;
                $CardExpYear  = $card->exp_year;

            } elseif ($pm->type === 'us_bank_account') {
                $CardType = 'ACH';
            } elseif ($pm->type === 'amazon_pay') {
                $CardType = 'AmazonPay';
            } else {
                $CardType = $pm->type;
            }

        } elseif (substr($PaymentMethodID, 0, 4) === 'src_') {
            // Legacy Source object
            $UtilLogger->LogDebug("GetPaymentMethod: id_type=src_ (legacy Source) | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
            $source = $myStripeClient->sources->retrieve($PaymentMethodID);

            if ($source->type === 'card') {
                $card         = $source->card;
                $CardType     = !empty($card->funding) ? $card->funding : 'credit';
                $CardBrand    = $card->brand;
                $CardLastFour = $card->last4;
                $CardExpMonth = $card->exp_month;
                $CardExpYear  = $card->exp_year;
            } elseif ($source->type === 'ach_debit' || $source->type === 'ach_credit_transfer') {
                $CardType = 'ACH';
            } else {
                $CardType = $source->type;
            }

        } elseif (substr($PaymentMethodID, 0, 5) === 'card_') {
            // Legacy Card object attached directly to the customer
            $UtilLogger->LogDebug("GetPaymentMethod: id_type=card_ (legacy Card on customer) | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
            $card         = $myStripeClient->customers->retrieveSource($CustomerID, $PaymentMethodID);
            $CardType     = !empty($card->funding) ? $card->funding : 'credit';
            $CardBrand    = $card->brand;
            $CardLastFour = $card->last4;
            $CardExpMonth = $card->exp_month;
            $CardExpYear  = $card->exp_year;

        } elseif (substr($PaymentMethodID, 0, 3) === 'ba_') {
            // Legacy BankAccount object attached directly to the customer
            $UtilLogger->LogDebug("GetPaymentMethod: id_type=ba_ (legacy BankAccount on customer) | customer=$CustomerID | subscription=$SubscriptionID | id=$PaymentMethodID");
            $CardType = 'ACH';
        }

    } catch (Exception $ex) {
        $UtilLogger->LogError("GetPaymentMethod error (customer=$CustomerID / subscription=$SubscriptionID): " . $ex->getMessage());
        while ($ex->getPrevious() != null) {
            $ex = $ex->getPrevious();
            $UtilLogger->LogError("  Inner error: " . $ex->getMessage());
        }
        return '';
    }

    return $CardType;
}


function GetPaymentMethodFromCharge(\Stripe\Charge $ChargeObject, string &$CardType, string &$CardBrand, string &$CardLastFour, string &$CardExpMonth, string &$CardExpYear): string
{
    global $UtilLogger;

    $CardType     = '';
    $CardBrand    = '';
    $CardLastFour = '';
    $CardExpMonth = '';
    $CardExpYear  = '';

    $ChargeID = !empty($ChargeObject->id) ? $ChargeObject->id : '(unknown)';

    try {
        // 1. Modern: payment_method_details (embedded on all recent charges)
        if (!empty($ChargeObject->payment_method_details)) {
            $pmd  = $ChargeObject->payment_method_details;
            $type = $pmd->type;
            $UtilLogger->LogDebug("GetPaymentMethodFromCharge: source=payment_method_details | charge=$ChargeID | type=$type");

            if ($type === 'card') {
                $card       = $pmd->card;
                $walletType = !empty($card->wallet) ? $card->wallet->type : '';

                if ($walletType === 'apple_pay') {
                    $CardType = 'ApplePay';
                } elseif ($walletType === 'google_pay') {
                    $CardType = 'GooglePay';
                } else {
                    $CardType = !empty($card->funding) ? $card->funding : 'credit';
                }

                $CardBrand    = $card->brand;
                $CardLastFour = $card->last4;
                $CardExpMonth = $card->exp_month;
                $CardExpYear  = $card->exp_year;

            } elseif ($type === 'ach_debit' || $type === 'us_bank_account') {
                $CardType = 'ACH';
            } elseif ($type === 'amazon_pay') {
                $CardType = 'AmazonPay';
            } else {
                $CardType = $type;
            }

            return $CardType;
        }

        // 2. Legacy: charge->source (older charges before payment_method_details existed)
        if (!empty($ChargeObject->source)) {
            $source    = $ChargeObject->source;
            $sourceObj = !empty($source->object) ? $source->object : '';
            $UtilLogger->LogDebug("GetPaymentMethodFromCharge: source=charge.source | charge=$ChargeID | object=$sourceObj");

            if ($sourceObj === 'card') {
                // Direct legacy Card object
                $UtilLogger->LogDebug("GetPaymentMethodFromCharge: id_type=card_ (legacy Card on charge.source) | charge=$ChargeID | id={$source->id}");
                $CardType     = !empty($source->funding) ? $source->funding : 'credit';
                $CardBrand    = $source->brand;
                $CardLastFour = $source->last4;
                $CardExpMonth = $source->exp_month;
                $CardExpYear  = $source->exp_year;

            } elseif ($sourceObj === 'source') {
                // Legacy Source object — card details are nested under source->card
                $sourceType = !empty($source->type) ? $source->type : '';
                $UtilLogger->LogDebug("GetPaymentMethodFromCharge: id_type=src_ (legacy Source on charge.source) | charge=$ChargeID | id={$source->id} | type=$sourceType");

                if ($sourceType === 'card') {
                    $card         = $source->card;
                    $CardType     = !empty($card->funding) ? $card->funding : 'credit';
                    $CardBrand    = $card->brand;
                    $CardLastFour = $card->last4;
                    $CardExpMonth = $card->exp_month;
                    $CardExpYear  = $card->exp_year;
                } elseif ($sourceType === 'ach_debit' || $sourceType === 'ach_credit_transfer') {
                    $CardType = 'ACH';
                } else {
                    $CardType = $sourceType;
                }

            } elseif ($sourceObj === 'bank_account') {
                $UtilLogger->LogDebug("GetPaymentMethodFromCharge: id_type=ba_ (legacy BankAccount on charge.source) | charge=$ChargeID | id={$source->id}");
                $CardType = 'ACH';
            }
        }

    } catch (Exception $ex) {
        $UtilLogger->LogError("GetPaymentMethodFromCharge error (charge=$ChargeID): " . $ex->getMessage());
        while ($ex->getPrevious() != null) {
            $ex = $ex->getPrevious();
            $UtilLogger->LogError("  Inner error: " . $ex->getMessage());
        }
        return '';
    }

    return $CardType;
}

?>
