<?php
    http_response_code(200);
    
date_default_timezone_set('America/Denver');
    require_once 'stripe_database2024.php';
    require_once "KLogger.php";
    
    $dbObject = new MySQLDB;
    $myLogger = new KLogger(STRIPE_LOG_FILE_CHARGE, 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 : ".$event_json->type);    
//$myLogger->logDebug(" event : ".print_r($event_json,true));    


if ($event_json->type=='charge.succeeded') {
    $handled=true;
    
    $randomStuffString = serialize($event_json->data->object->metadata);
    
    $eventResult = 'Paid';
    $chargeObject = $event_json->data->object;
    $chargeID = $chargeObject->id; // $event_json->data->object->id;
    $chargeDate = $chargeObject->created; // $event_json->data->object->created;
    $tempDate = date("Y-m-d H:i:s", substr($chargeDate, 0, 10));
    $chargeAmountTemp = $chargeObject->amount; // $event_json->data->object->amount;
    $chargeAmount = floatval(($chargeAmountTemp)/100);
	
    $StripeCustomerID = $chargeObject->customer; // $event_json->data->object->customer;
    
    $RK_EmailAddress = $chargeObject->receipt_email; // $event_json->data->object->receipt_email;

    $cardBrand = "";
    $lastFour = "";
    $expMonth = "";
    $expYear = "";
    $cardType = "";
    $cardType = GetPaymentMethodFromCharge($chargeObject, $cardType, $cardBrand, $lastFour, $expMonth, $expYear);
    if (property_exists($event_json->data->object->metadata, 'TenantID')) {
        $RK_TenantID = $event_json->data->object->metadata->TenantID;
    } else {
        $RK_TenantID = "";        
        $RK_TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
    }

    if ($RK_TenantID  == "PENDING") {
        // then this is the first charge.  We need the signup page to handle it.
        $myLogger->logDebug(" Ignored stripe charge event because it's for a pending tenant.  Stripe ID: ".$chargeID.", Pending ID:".$event_json->data->object->metadata->SubmissionID);
    } else {
        if ($event_json->data->object->invoice == null) {
            // then this is a one-time charge
            // this means that the registration page is handling this, so we'll ignore it.
            $eventType = "Registration";
            if (property_exists($event_json->data->object->metadata, 'RK_ChargeID')) {
                $RK_ChargeID = $event_json->data->object->metadata->RK_ChargeID;
            } else {
                $RK_ChargeID = "";
            }
            
            $msg = $_SERVER['SCRIPT_NAME']." ".$eventType." chargeID : ".$chargeID.", RK ChargeID:".$RK_ChargeID.", RK UserID:".$RK_TenantID;
            $msg .= " chargeDate: ".$chargeDate.", source charge date:".$tempDate.", amount:".$chargeAmount;
            $msg .= ", source amount:".$chargeAmountTemp.", type:".$cardType.", last4: ".$lastFour;

            $myLogger->logDebug($msg);
            $sql = "select count(*) from StripePayments where StripePaymentID = ?";
        
            $stmt = $dbObject->connection->prepare($sql);
            $stmt->bindParam(1, $RK_ChargeID);
            $stmt->execute();
            $paymentCount = $stmt->fetch(PDO::FETCH_NUM);
            if ($paymentCount[0] == 0) {
                $myLogger->logDebug(" no previous payment found, inserting a new one with the Stripe CustomerID if we can.");
                if ($RK_TenantID > 0 && $RK_TenantID != "") {
                    $dbObject->saveMonthlyStripeResult($RK_TenantID, $StripeCustomerID, $RK_EmailAddress, $eventType, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $randomStuffString, "");
                    $dbObject->resumeTenantReporting($RK_TenantID);
                    $dbObject->logUserEvent("$".$chargeAmount." Stripe charge paid, unknown reason why. ", $RK_TenantID);
                }
            } else {
                $myLogger->logDebug(" FOUND previous payment.");
                $dbObject->updateStripeResult($RK_ChargeID, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $randomStuffString);
                $myLogger->logDebug("saved stripe result.  chargeID : ".$chargeID.", chargeDate: ".$chargeDate.", amount:".$chargeAmount.", type:".$cardType.", last4: ".$lastFour);
                $dbObject->logUserEvent("$".$chargeAmount." Stripe charge paid for registration", $RK_TenantID);
                $dbObject->resumeTenantReporting($RK_TenantID);
            }
        } else {
            $InvoiceID = $event_json->data->object->invoice;
            /* we're going to handle this with an invoice handler */
            $myLogger->logDebug("about to save stripe result.  chargeID : ".$chargeID.", chargeDate: ".$chargeDate.", amount:".$chargeAmount.", type:".$cardType.", last4: ".$lastFour.", invoice: ".$InvoiceID." TenantID: ".$RK_TenantID);
            $eventType = "Subscription";
            
            if ($RK_TenantID > 0 && $RK_TenantID != "") {
                $dbObject->saveMonthlyStripeResult($RK_TenantID, $StripeCustomerID, $RK_EmailAddress, $eventType, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $event_json->data->object->metadata, $InvoiceID);
                $dbObject->logUserEvent("$".$chargeAmount." Stripe charge paid for subscription.  InvoiceID: ".$InvoiceID, $RK_TenantID);
                $dbObject->resumeTenantReporting($RK_TenantID);
                $myLogger->logDebug(" resumed tenant reporting for tenant.  ".$RK_TenantID);
            }
        }     
    }
} 

if ($event_json->type=='charge.refunded') {
    $handled=true;
    
    $randomStuffString = serialize($event_json->data->object->metadata);
    
    $eventType = $event_json->type;
    $eventResult = 'Refunded';
    $chargeObject = $event_json->data->object;
    $chargeID = $chargeObject->id; // $event_json->data->object->id;
    $chargeDate = $chargeObject->created; // $event_json->data->object->created;
    $tempDate = date("Y-m-d H:i:s", substr($chargeDate, 0, 10));
    $chargeAmountTemp = $chargeObject->amount_refunded; // $event_json->data->object->amount_refunded;
    $chargeAmount = floatval(($chargeAmountTemp)/100);
    //$cardType = $event_json->data->object->card->type;
    //$lastFour = $event_json->data->object->card->last4;
    $StripeCustomerID = $chargeObject->customer; //$event_json->data->object->customer;
    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
    $cardBrand = "";
    $lastFour = "";
    $expMonth = "";
    $expYear = "";
    $cardType = GetPaymentMethodFromCharge($chargeObject, $cardType, $cardBrand, $lastFour, $expMonth, $expYear);
    //$myLogger->logDebug("refund event - data object: ".print_r($event_json->data->object, true));
    $RK_EmailAddress = "";
    if (property_exists($event_json->data->object, 'receipt_email')) {
        $RK_EmailAddress = $event_json->data->object->receipt_email;
    }
    // for refunds, we ALWAYS want to save a new record, with a negative amount.
    
    if ($event_json->data->object->invoice == null || $event_json->data->object->invoice == "") {
        // then this is a one-time charge
        if ($event_json->data->object->invoice == null) {
            $myLogger->logDebug(" refund event null invoice");
        } else {
            $myLogger->logDebug(" refund event invoice == ''");
        }
        
        $eventType = "Registration";
        $myLogger->logDebug(" ".$eventType." chargeID : ".$chargeID.", RK UserID:".$TenantID." chargeDate: ".$chargeDate.", source charge date:".$tempDate.", amount:".$chargeAmount.", source amount:".$chargeAmountTemp.", type:".$cardType.", last4: ".$lastFour);
        $myLogger->logDebug(" inserting a new refund item.");
        
        if ($TenantID > 0) {
            $dbObject->saveStripeResultByTenantID($TenantID, $StripeCustomerID, $eventType, $chargeID, $chargeDate, (-1 * $chargeAmount), $cardType, $lastFour, $eventResult, $randomStuffString);
            $dbObject->logUserEvent("$".$chargeAmount." Stripe charge refunded for registration.", $TenantID);
        }
    } else {
        $eventType = "Subscription";
        $InvoiceID = $event_json->data->object->invoice;
        $myLogger->logDebug(" refund event invoice ID:".$InvoiceID);
        
        if ($TenantID > 0) {
            $dbObject->saveMonthlyStripeResult($TenantID, $StripeCustomerID, $RK_EmailAddress, $eventType, $chargeID, $chargeDate, (-1 * $chargeAmount), $cardType, $lastFour, $eventResult, $randomStuffString, $InvoiceID);
            $dbObject->logUserEvent("$".$chargeAmount." Stripe charge refunded for subscription.", $TenantID);
        }   
    }
} 
if ($event_json->type=='charge.failed') {
    // mark the tenant as non-reporting or delete them all together.
    $handled=true;
    $chargeObject = $event_json->data->object;

    $randomStuffString = serialize($chargeObject->metadata);
    //$myLogger->logDebug("charge.failed data structure:".print_r($event_json->data,true));
    $eventType = $event_json->type;
    $chargeID = $chargeObject->id;
    $chargeDate = $event_json->data->object->created;
    $tempDate = date("Y-m-d H:i:s", substr($chargeDate, 0, 10));
    $chargeAmountTemp = $chargeObject->amount;
    $chargeAmount = floatval(($chargeAmountTemp)/100);
	$cardBrand = "";
    $lastFour = "";
    $expMonth = "";
    $expYear = "";
    $cardType = GetPaymentMethodFromCharge($chargeObject, $cardType, $cardBrand, $lastFour, $expMonth, $expYear);
    
    $RK_EmailAddress = "";
    if (property_exists($chargeObject, 'receipt_email')) {
        $RK_EmailAddress = $chargeObject->receipt_email;
    }

    $StripeCustomerID = $chargeObject->customer;
    
    $failureCode = $chargeObject->failure_code;
    if (property_exists($chargeObject, "failure_message") && $chargeObject->failure_message !== "") {
        $eventResult = "Failed: ".$failureCode.", ".$chargeObject->failure_message.".";
    } else {
        $eventResult = 'Failed. '.$failureCode;
    }
    

    if (property_exists($event_json->data->object->metadata, 'TenantID')) {
        $RK_TenantID = $event_json->data->object->metadata->TenantID;
    } else {
        $RK_TenantID = "";        
    }
    if ($RK_TenantID == "PENDING") {
        // pretty much do nothing
        $myLogger->logDebug(" Ignored stripe charge event because it's for a pending tenant.  Pending ID:".$event_json->data->object->metadata->SubmissionID);
    } else {
        
        $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
        if ($event_json->data->object->invoice == null) {
            // then this is a one-time charge
            $eventType = "Registration";
            if (property_exists($event_json->data->object->metadata, 'RK_ChargeID')) {
                $RK_ChargeID = $event_json->data->object->metadata->RK_ChargeID;
            } else {
                $RK_ChargeID = "";
            }
            $myLogger->logDebug(" ".$eventType." chargeID : ".$chargeID.", RK ChargeID:".$RK_ChargeID.", RK UserID:".$TenantID." chargeDate: ".$chargeDate.", source charge date:".$tempDate.", amount:".$chargeAmount.", source amount:".$chargeAmountTemp.", type:".$cardType.", last4: ".$lastFour);
            $sql = "select count(*) from StripePayments where StripePaymentID = ?";
        
            $stmt = $dbObject->connection->prepare($sql);
            $stmt->bindParam(1, $RK_ChargeID);
            $stmt->execute();
            $paymentCount = $stmt->fetch(PDO::FETCH_NUM);
            if ($paymentCount[0] == 0) {
                $myLogger->logDebug(" no previous payment found, inserting a new one with the stripe customer ID if we can.");
                if ($TenantID > 0) {
                    $dbObject->saveStripeResultByTenantID($TenantID, $StripeCustomerID, $eventType, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $randomStuffString);
                    $dbObject->logUserEvent("$".$chargeAmount." Stripe charge FAILED for registration", $TenantID);
                }
            } else {
                $myLogger->logDebug(" FOUND previous payment.");
                $dbObject->updateStripeResult($RK_ChargeID, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $randomStuffString);
                $myLogger->logDebug(" saved stripe result.  chargeID : ".$chargeID.", chargeDate: ".$chargeDate.", amount:".$chargeAmount.", type:".$cardType.", last4: ".$lastFour);
                $dbObject->logUserEvent("$".$chargeAmount." Stripe charge FAILED for registration", $TenantID);    
            }
        } else {
            // get the invoice ID and the month for it.
            $eventType = "Subscription";
            $InvoiceID = $event_json->data->object->invoice;
            $myLogger->logDebug(" FAILED charge event invoice ID:".$InvoiceID);
            
            if ($TenantID > 0) {
                $dbObject->saveMonthlyStripeResult($TenantID, $StripeCustomerID, $RK_EmailAddress, $eventType, $chargeID, $chargeDate, $chargeAmount, $cardType, $lastFour, $eventResult, $randomStuffString, $InvoiceID);
                $dbObject->logUserEvent("$".$chargeAmount." Stripe charge FAILED for subscription.  InvoiceID: ".$InvoiceID, $TenantID);
                // we want to the let the invoice handler take care of this for us.
                //$dbObject->UpdateStripeInvoiceDetails($InvoiceID,"Failed", $chargeAmount, $chargeDate, $chargeID); 
            }
        }
        $dbObject->suspendTenantReporting($TenantID);
    }
} 

if ($event_json->type=='charge.updated') {
    // just want to log it, really.
    $handled=true;
    $eventType = $event_json->type;
    $chargeObject = $event_json->data->object;
    $chargeID = $chargeObject->id;
    $chargeDate = $event_json->data->object->created;
    $tempDate = date("Y-m-d H:i:s", substr($chargeDate, 0, 10));
    $chargeAmountTemp = $event_json->data->object->amount;
    $chargeAmount = floatval(($chargeAmountTemp));
    $lastFour = "";
    $cardBrand = "";
    $cardType = "";
    if (property_exists($event_json->data->object, "card") && $event_json->data->object->card != "") {
        $cardObject = $event_json->data->object->card;
        if (property_exists($cardObject, "funding")) {
            $cardType = $cardObject->funding;
        }
        if (property_exists($cardObject, "last4")) {
            $lastFour = $cardObject->last4;
        }
        if (property_exists($cardObject, "brand")) {
            $cardBrand = $cardObject->brand;
        }
    }
    //$RK_ChargeID = $event_json->data->object->metadata->RK_ChargeID;
    if (property_exists($event_json->data->object->metadata, 'RK_ChargeID')) {
        $RK_ChargeID = $event_json->data->object->metadata->RK_ChargeID;
    } else {
        $RK_ChargeID = "";
    }
    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
    
    //$RK_EmailAddress = $event_json->data->object->receipt_email;
    $myLogger->logDebug(" charge updated.  Not doing anything about it. ChargeID : ".$chargeID.", RK ChargeID:".$RK_ChargeID.", RK UserID:".$TenantID." chargeDate: ".$chargeDate.", source charge date:".$tempDate.", amount:".$chargeAmount.", source amount:".$chargeAmountTemp.", type:".$cardType.", last4: ".$lastFour);
    $dbObject->logUserEvent("$".$chargeAmount." Stripe charge updated for registration. ChargeID : ".$chargeID.", RK ChargeID:".$RK_ChargeID.", RK UserID:".$TenantID." chargeDate: ".$chargeDate.", source charge date:".$tempDate.", amount:".$chargeAmount.", source amount:".$chargeAmountTemp.", type:".$cardType.", last4: ".$lastFour, $TenantID);
    // logUserEvent
} 




if ($handled == false) {
    $myLogger->logDebug(" unhandled EVENT CONTENTS: ".print_r($event_json, true));
}


?>
