<?php
/*
 * stripe_event_card_c.php — Card / source event handler
 *
 * Handled event types ($event_json->type):
 *   customer.source.created
 *   customer.source.updated
 */

require_once 'stripe_database.php';
require_once 'KLogger.php';

$DbObject    = new MySQLDB;
$MyLogger    = new KLogger(STRIPE_LOG_FILE_CARD, KLogger::DEBUG);
$MyRawLogger = STRIPE_RAW_LOGGING ? new KLogger(STRIPE_RAW_LOG_FILE_CARD, KLogger::DEBUG) : null;
require_once STRIPE_INIT_LOCATION;

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$Handled   = false;
$Body      = @file_get_contents('php://input');
$SigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

try {
    $EventJson = \Stripe\Webhook::constructEvent($Body, $SigHeader, STRIPE_WEBHOOK_SECRET_CARD);
} catch (\UnexpectedValueException $E) {
    $MyLogger->logDebug("Rejected request: invalid payload");
    http_response_code(400);
    exit;
} catch (\Stripe\Exception\SignatureVerificationException $E) {
    $MyLogger->logDebug("Rejected request: invalid signature");
    http_response_code(400);
    exit;
}
http_response_code(200);
if ($MyRawLogger) $MyRawLogger->logDebug("RAW_EVENT_JSON: " . $Body);
$MyLogger->logDebug("event: " . $EventJson->type);

if ($EventJson->type == 'customer.source.created' || $EventJson->type == 'customer.source.updated') {
    $Handled = true;

    $Source     = $EventJson->data->object;
    $SourceType = $Source->object ?? '';

    $MyLogger->logDebug("card event - source object type: " . $SourceType . " | id: " . ($Source->id ?? ''));

    if ($SourceType === 'card') {
        // Legacy card_ object attached directly to the customer — existing method handles this shape
        $DbObject->updateStripeCardInfo($Source);
        $MyLogger->logDebug("card event - updated card via updateStripeCardInfo | id: " . $Source->id);
    } elseif ($SourceType === 'source' && ($Source->type ?? '') === 'card') {
        // Legacy Source object with nested card details
        $Card = $Source->card;
        $DbObject->updateTenantCardInfo(
            $Source->customer,
            !empty($Card->funding) ? $Card->funding : 'credit',
            $Card->brand    ?? '',
            $Card->last4    ?? '',
            (int) ($Card->exp_month ?? 0),
            (int) ($Card->exp_year  ?? 0)
        );
        $MyLogger->logDebug("card event - updated card via updateTenantCardInfo from src_ | id: " . $Source->id);
    } else {
        // ACH or other non-card source — log but no card fields to save
        $MyLogger->logDebug("card event - non-card source type '" . ($Source->type ?? $SourceType) . "', skipping card update | id: " . ($Source->id ?? ''));
    }
}

if ($Handled == false) {
    $MyLogger->logDebug("unhandled EVENT CONTENTS: " . print_r($EventJson, true));
}
?>
