<?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_INVOICE, 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.", event ID: ".$event_json->id);    
//$myLogger->logDebug("  event : ".print_r($event_json,true));    


if ($event_json->type=='invoice.finalized') {
    // dump these to compare data layouts
	$EventID = $event_json->id;
	$InvoiceID = $event_json->data->object->id;
    $myLogger->logDebug("  invoice.finalized event:  - EventID ".$EventID.", invoice: ".$InvoiceID);
    //$myLogger->logDebug("  invoice.finalized event:  - ".print_r($event_json,true));    
    $handled=true;  
}

if ($event_json->type=='invoice.payment_action_required') {
    // dump these to compare data layouts
    $myLogger->logDebug("  invoice.payment_action_required event: ".print_r($event_json,true));
    $handled=true;  
}

if ($event_json->type=='invoice.deleted') {
    // dump these to compare data layouts
	$EventID = $event_json->id;
	$InvoiceID = $event_json->data->object->id;
	$myLogger->logDebug("invoice.deleted.  eventID: ".$EventID.", invoice: ".$InvoiceID);
    $handled=true;  
}


if ($event_json->type=='invoice.marked_uncollectible') {
    // dump these to compare data layouts
	// invoice id 
	$EventID = $event_json->id;
	$InvoiceID = $event_json->data->object->id;
	$myLogger->logDebug("invoice.marked_uncollectible.  eventID: ".$EventID.", invoice: ".$InvoiceID);
    
    $handled=true;  
}

if ($event_json->type=='invoice.upcoming') {
    // dump these to compare data layouts
    //$myLogger->logDebug("  invoice.upcoming event: ".print_r($event_json,true));
    $handled=true;  
    $EventDate = $event_json->created;
    $UpcomingInvoiceObject = $event_json->data->object;
    $EventID = $event_json->id;
	$InvoiceNumber = $UpcomingInvoiceObject->number;
	$InvoiceCustomer = $UpcomingInvoiceObject->customer."/".$UpcomingInvoiceObject->customer_email;
	$myLogger->logDebug("  invoice.upcoming event - EventID ".$EventID.", Number: ".$InvoiceNumber.", Member: ".$InvoiceCustomer);
	
    
    // get the tenant by the customer ID
    $dbObject->saveUpcomingStripeInvoice($UpcomingInvoiceObject, $EventDate);
}

//if ($event_json->type=='invoice.created') {
//    $handled=true;  
//    $myLogger->logDebug("  invoice.created event: ".print_r($event_json,true));
//    $EventID = $event_json->id;
//    $EventDate = $event_json->created;
//    $InvoiceID = $event_json->data->object->id;
//    $StripeCustomerID = $event_json->data->object->customer;
//    $InvoiceObject = $event_json->data->object;
//    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
//    $dbObject->saveStripeInvoice($TenantID, $InvoiceObject, $EventID, $EventDate);
    // save the StripeInvoice
//}

if ($event_json->type=='invoice.updated' || $event_json->type=='invoice.created' || $event_json->type=='invoice.payment_succeeded' || $event_json->type=='invoice.payment_failed' || $event_json->type=='invoice.paid') {
    $handled=true;  
    //$myLogger->logDebug("  invoice.updated event: ".print_r($event_json,true));
    $InvoiceID = $event_json->data->object->id;
    $EventID = $event_json->id;
    $EventDate = $event_json->created;
    
    $StripeCustomerID = $event_json->data->object->customer;
    $InvoiceObject = $event_json->data->object;
    // get the tenant by the customer ID


    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);

    $InvoiceNumber = $InvoiceObject->number;
    $CustomerID = $InvoiceObject->customer;
    $SubscriptionID = $InvoiceObject->subscription;
    $Amount =  floatval(($InvoiceObject->total)/100); 
    $InvoiceStatus = $InvoiceObject->status;
    $ChargeDate = "";
   
    
    if ($InvoiceStatus == 'draft') {
        if ($InvoiceObject->next_payment_attempt != "") {
            $ChargeDate = date('Y-m-d H:i:s', $InvoiceObject->next_payment_attempt);
        } else {            
            $ChargeDate = "null";
        }
    }

    if ($InvoiceStatus == 'open') {
        if (property_exists($InvoiceObject, "hosted_invoice_url") && ($InvoiceObject->hosted_invoice_url !== "")) {
            $myLogger->logDebug("invoice.updated - open invoice payment URL: ".$InvoiceObject->hosted_invoice_url);
        }
    }

    if ($InvoiceObject->date != "") {
        $CreateDate = date('Y-m-d H:i:s', $InvoiceObject->date);
    } else {            
        $CreateDate = date('Y-m-d H:i:s', $EventDate);
    }

    
    if ($InvoiceObject->period_start != "") {
        $InvoiceDate = date('Y-m-d H:i:s', $InvoiceObject->period_start);
    } else {            
        $InvoiceDate = "null";
    }
    if (property_exists($InvoiceObject, "id") && $InvoiceObject->id != "null" && $InvoiceObject->id != "") {
        $InvoiceID = $InvoiceObject->id;
    } else {
        $InvoiceID = ""; //null;
    }
    
    if (property_exists($InvoiceObject, "charge") && $InvoiceObject->charge != "null" && $InvoiceObject->charge != "") {
        $ChargeID = $InvoiceObject->charge;
    } else {
        $ChargeID = "";//null;
    }
    $myLogger->logDebug($event_json->type." event - EventID ".$EventID);
    $myLogger->logDebug($event_json->type." event - Invoice Number ".$InvoiceNumber);
    $myLogger->logDebug($event_json->type." event - CustomerID ".$CustomerID);
    $myLogger->logDebug($event_json->type." event - SubscriptionID ".$SubscriptionID);
    $myLogger->logDebug($event_json->type." event - Amount ".$Amount);
    $myLogger->logDebug($event_json->type." event - Status ".$InvoiceStatus);
    $myLogger->logDebug($event_json->type." event - Create Date ".$CreateDate);
    $myLogger->logDebug($event_json->type." event - Charge Date ".$ChargeDate);
    $myLogger->logDebug($event_json->type." event - Invoice Date ".$InvoiceDate);
    $myLogger->logDebug($event_json->type." event - InvoiceID ".$InvoiceID);
    $myLogger->logDebug($event_json->type." event - ChargeID ".$ChargeID);

       // $dbObject->saveStripeInvoice($TenantID, $InvoiceObject, $EventID, $EventDate);
    $dbObject->updateStripeInvoice($InvoiceNumber, $CustomerID, $SubscriptionID, $Amount, $InvoiceStatus, $CreateDate, $InvoiceDate, $ChargeDate, $InvoiceID, $ChargeID, $InvoiceObject);



    if ($event_json->type=='invoice.payment_succeeded') {
        
        $myLogger->logDebug("  invoice.payment_succeeded ");
        if ($event_json->data->object->lines->data[0]->type == "subscription") {
            $myLogger->logDebug("  subscription event : ".$event_json->type.", customerID: ".$CustomerID.", SubscriptionID :".$SubscriptionID);    
            $dbObject->logUserEvent("Stripe Invoice for $".$Amount." created and paid for Subscription ".$SubscriptionID, $TenantID);
        } else {
            $myLogger->logDebug("  event : ".$event_json->type.", customerID: ".$CustomerID);
            $dbObject->logUserEvent("Stripe Invoice for $".$Amount." created and paid.", $TenantID);
        }
        $dbObject->resumeTenantReporting($TenantID);    
    }
    
    if ($event_json->type=='invoice.payment_failed') {
        
        $myLogger->logDebug("  invoice.payment_failed ");
        
        $dbObject->logUserEvent("Stripe Invoice for ".$Amount." FAILED.", $TenantID);
        $myLogger->logDebug("  event : ".$event_json->type.", customerID: ".$StripeCustomerID);    
        $dbObject->suspendTenantReporting($TenantID);    
    }
    

}


//if ($event_json->type=='invoice.payment_succeeded') {
//    $handled=true;
//    $myLogger->logDebug("  invoice.payment_succeeded event: ".print_r($event_json,true));
//    $invoiceID = $event_json->data->object->id;
//    $invoiceAmountTemp = $event_json->data->object->total;
//    $invoiceAmount = floatval(($invoiceAmountTemp));
//    
//    $StripeCustomerID = $event_json->data->object->customer;
//    // get the tenant by the customer ID
//    /*
//    $this_tenant = $dbObject->getUserInfoByStripeID($StripeCustomerID);
//    $TenantID = $this_tenant["userID"];
//    */
//   
//    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
//    
//    if ($event_json->data->object->lines->data[0]->type == "subscription") {
//        $StripePlanID = $event_json->data->object->lines->data[0]->plan->id;
//        $myLogger->logDebug("  subscription event : ".$event_json->type.", customerID: ".$StripeCustomerID.", planID:".$StripePlanID);    
//        $dbObject->logUserEvent("Stripe Invoice for $".$invoiceAmount." created and paid for Plan ".$StripePlanID, $TenantID);
//    } else {
//        $myLogger->logDebug("  event : ".$event_json->type.", customerID: ".$StripeCustomerID);
//        $dbObject->logUserEvent("Stripe Invoice for $".$invoiceAmount." created and paid.", $TenantID);
//    }
//    $dbObject->resumeTenantReporting($TenantID);    
//}

//if ($event_json->type=='invoice.payment_failed') {
//    $handled=true;
//    $myLogger->logDebug("  invoice.payment_failed event: ".print_r($event_json,true));
//    // this is for a monthly subscription payment that fails.
//    $EventID = $event_json->id;
//    $EventDate = $event_json->created;
//    
//    $InvoiceID = $event_json->data->object->id;
//    $invoiceAmountTemp = $event_json->data->object->total;
//    $invoiceAmount = floatval(($invoiceAmountTemp));
//    
//    $StripeCustomerID = $event_json->data->object->customer;
//    $InvoiceObject = $event_json->data->object;
//    
//    $TenantID = $dbObject->getTenantIDFromStripeID($StripeCustomerID);
//    
//	$dbObject->saveStripeInvoice($TenantID, $InvoiceObject, $EventID, $EventDate);
//    
//
//    $dbObject->logUserEvent("Stripe Invoice for ".$invoiceAmount." FAILED.", $TenantID);
//    $myLogger->logDebug("  event : ".$event_json->type.", customerID: ".$StripeCustomerID);    
//    $dbObject->suspendTenantReporting($TenantID);    
//}



if ($handled == false) {
    $myLogger->logDebug("   unhandled EVENT CONTENTS: ".print_r($event_json, true));
}


?>
