<?php
/*
 * stripe_event_payment_c.php — Payment intent and payment method event handler
 *
 * Handled event types ($event_json->type):
 *   payment_intent.succeeded
 *   payment_intent.payment_failed
 *   payment_method.attached
 *   payment_method.updated
 *
 * payment_intent.* events handle tenant reporting status and card info only.
 * The actual payment record in StripePayments is written by charge.* events
 * (stripe_event_charge_c.php) using the ch_ ChargeID, which is the single
 * authoritative record for each transaction.
 */

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

$DbObject    = new MySQLDB;
$MyLogger    = new KLogger(STRIPE_LOG_FILE_PAYMENT, KLogger::DEBUG);
$MyRawLogger = STRIPE_RAW_LOGGING ? new KLogger(STRIPE_RAW_LOG_FILE_PAYMENT, 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_PAYMENT);
} 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 == 'payment_intent.succeeded' || $EventJson->type == 'payment_intent.payment_failed') {
    $Handled = true;

    $PaymentIntent   = $EventJson->data->object;
    $PaymentIntentID = $PaymentIntent->id;
    $CustomerID      = $PaymentIntent->customer ?? '';
    $Amount          = ($PaymentIntent->amount  ?? 0) / 100;

    $TenantID = ($CustomerID !== '') ? $DbObject->getTenantIDFromStripeID($CustomerID) : -1;

    // Card details are not resolved here.  payment_method.attached/.updated and
    // charge.succeeded already write the card to the tenant record, so a lookup
    // at this point would only repeat work.

    if ($EventJson->type == 'payment_intent.succeeded') {
        if ($TenantID > 0) {
            $DbObject->resumeTenantReporting($TenantID);
            $DbObject->logUserEvent("PaymentIntent succeeded: " . $PaymentIntentID . " amount: $" . $Amount, $TenantID);
        }
    }

    if ($EventJson->type == 'payment_intent.payment_failed') {
        $LastError      = $PaymentIntent->last_payment_error ?? null;
        $FailureMessage = $LastError->message ?? $LastError->code ?? '';
        if ($TenantID > 0) {
            $DbObject->suspendTenantReporting($TenantID);
            $DbObject->logUserEvent("PaymentIntent failed: " . $PaymentIntentID . " reason: " . $FailureMessage, $TenantID);
        }
    }

    $MyLogger->logDebug("payment_intent event - " . $EventJson->type . " | PI: " . $PaymentIntentID . " | TenantID: " . $TenantID);
}

if ($EventJson->type == 'payment_method.attached' || $EventJson->type == 'payment_method.updated') {
    $Handled = true;

    $Pm         = $EventJson->data->object;
    $CustomerID = $Pm->customer ?? '';

    if ($Pm->type === 'card' && !empty($Pm->card)) {
        $Card = $Pm->card;
        $DbObject->updateTenantCardInfo(
            $CustomerID,
            !empty($Card->funding) ? $Card->funding : 'credit',
            $Card->brand     ?? '',
            $Card->last4     ?? '',
            (int) ($Card->exp_month ?? 0),
            (int) ($Card->exp_year  ?? 0)
        );
        $MyLogger->logDebug("payment_method event - updated card for customer: " . $CustomerID . " | last4: " . ($Card->last4 ?? '') . " | brand: " . ($Card->brand ?? ''));
    } else {
        $MyLogger->logDebug("payment_method event - type '" . $Pm->type . "' has no card fields to update | customer: " . $CustomerID);
    }
}

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