<?php
    http_response_code(200);
    
date_default_timezone_set('America/Denver');
    require_once 'testdb_stripe_database2024.php';
    require_once "KLogger.php";
    
    $dbObject = new MySQLDB;
    $myLogger = new KLogger(STRIPE_LOG_FILE_CARD, KLogger::DEBUG);
    require_once STRIPE_INIT_LOCATION;
        
\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

$handled=false;
// Retrieve the request's body and parse it as JSON
$body = @file_get_contents('php://input');
$event_json = json_decode($body);

//$myLogger->logDebug(" event : ".print_r($event_json,true));    


if ($event_json->type=='customer.card.created' || $event_json->type=='customer.card.updated' || $event_json->type=='customer.card.deleted') {
    $handled=true;
    $myLogger->logDebug(" event : ".$event_json->type);    
    $Action = substr($event_json->type, 14);
    $CardObject = $event_json->data->object;
    $StripeCustomerID = $CardObject->customer;
    $LastFour = "";
    $CardType = "";
    $CardBrand = "";
    if (property_exists($CardObject, "brand") && $CardObject->brand !== null) {
        $CardBrand = $CardObject->brand;
    }
    if (property_exists($CardObject, "last4") && $CardObject->last4 !== null) {
        $CardLastFour = $CardObject->last4;
    }
    if (property_exists($CardObject, "funding") && $CardObject->funding !== null) {
        $CardType = " (".$CardObject->funding.")";
    }
    
    
    
    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
    $dbObject->updateStripeCardInfo($CardObject);
    if (isset($TenantID)) {
        $dbObject->logUserEvent("Stripe ".$Action." card (".$CardType."/".$CardBrand.") ending in ".$LastFour." to customer.", $TenantID);
    } else {
        $myLogger->logDebug(" unable to find tenant for event: ".$event_json->type.", Stripe CustomerID: ".$StripeCustomerID);    
    }
}



if ($handled == false) {
    $myLogger->logDebug(" unhandled EVENT CONTENTS: ".print_r($event_json, true));
}


?>
