<?php
/*
 * stripe_event_refund_c.php — Refund event handler
 *
 * Handled event types ($event_json->type):
 *   refund.created
 *   refund.updated
 *
 * Refunds are stored in StripeRefunds (NOT StripePayments) to prevent the
 * duplication issues that occurred when refunds were previously saved there.
 * Amounts are stored as negative numbers.
 */

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

$DbObject    = new MySQLDB;
$MyLogger    = new KLogger(STRIPE_LOG_FILE_REFUND, KLogger::DEBUG);
$MyRawLogger = STRIPE_RAW_LOGGING ? new KLogger(STRIPE_RAW_LOG_FILE_REFUND, 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_REFUND);
} 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 == 'refund.created' || $EventJson->type == 'refund.updated') {
    $Handled = true;

    $Refund      = $EventJson->data->object;
    $RefundID    = $Refund->id      ?? '';
    $ChargeID    = $Refund->charge  ?? '';
    $NegAmount   = - (($Refund->amount ?? 0) / 100);
    $Status      = $Refund->status  ?? '';
    $Reason      = $Refund->reason  ?? '';
    $CustomerID  = '';
    $TenantID    = -1;

    // Retrieve the associated charge to find the customer and invoice
    if ($ChargeID !== '') {
        try {
            $MyStripeClient = new \Stripe\StripeClient(STRIPE_SECRET_KEY);
            $ChargeObject   = $MyStripeClient->charges->retrieve($ChargeID);
            $CustomerID     = $ChargeObject->customer ?? '';
            if ($CustomerID !== '') {
                $TenantID = $DbObject->getTenantIDFromStripeID($CustomerID);
            }
        } catch (\Exception $Ex) {
            $MyLogger->logError("refund event - failed to retrieve charge " . $ChargeID . ": " . $Ex->getMessage());
        }
    }

    $DbObject->saveStripeRefund($RefundID, $ChargeID, $NegAmount, $Status, $Reason, $TenantID);

    $MyLogger->logDebug("refund event - " . $EventJson->type . " | RefundID: " . $RefundID . " | ChargeID: " . $ChargeID . " | NegAmount: " . $NegAmount . " | Status: " . $Status . " | TenantID: " . $TenantID);
}

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