<?php
/*
 * stripe_event_subscription_c.php — Subscription event handler
 *
 * Handled event types ($event_json->type):
 *   customer.subscription.created
 *   customer.subscription.updated
 *   customer.subscription.deleted
 */

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

$DbObject    = new MySQLDB;
$MyLogger    = new KLogger(STRIPE_LOG_FILE_SUBSCRIPTION, KLogger::DEBUG);
$MyRawLogger = STRIPE_RAW_LOGGING ? new KLogger(STRIPE_RAW_LOG_FILE_SUBSCRIPTION, 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_SUBSCRIPTION);
} 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 == 'customer.subscription.created' || $EventJson->type == 'customer.subscription.updated') {
    $Handled = true;

    $Subscription = $EventJson->data->object;
    $CustomerID   = $Subscription->customer ?? '';
    $TenantID     = ($CustomerID !== '') ? $DbObject->getTenantIDFromStripeID($CustomerID) : -1;

    $PlanID   = $Subscription->items->data[0]->price->id ?? '';
    $PlanName = $DbObject->getPlanNameByPlanID($PlanID);
    if ($PlanName === null) {
        $MyLogger->logDebug("subscription event - PlanID '" . $PlanID . "' not found in StripePlans; using raw PlanID as plan name");
        $PlanName = $PlanID;
    }

    if ($TenantID > 0) {
        $DbObject->setTenantMUPrice($TenantID, $PlanName);
    }
    $DbObject->saveStripeSubscription($TenantID, $Subscription);

    $MyLogger->logDebug("subscription event - " . $EventJson->type . " | CustomerID: " . $CustomerID . " | TenantID: " . $TenantID . " | SubscriptionID: " . $Subscription->id . " | PlanID: " . $PlanID . " | PlanName: " . $PlanName);
}

if ($EventJson->type == 'customer.subscription.deleted') {
    $Handled = true;

    $Subscription = $EventJson->data->object;
    $CustomerID   = $Subscription->customer ?? '';
    $TenantID     = ($CustomerID !== '') ? $DbObject->getTenantIDFromStripeID($CustomerID) : -1;

    if ($TenantID > 0) {
        $DbObject->removeStripeSubscription($TenantID);
        $DbObject->logUserEvent("Subscription cancelled: " . $Subscription->id, $TenantID);
    }
    $DbObject->deleteStripeSubscription($Subscription->id);

    $MyLogger->logDebug("subscription event - deleted | CustomerID: " . $CustomerID . " | TenantID: " . $TenantID . " | SubscriptionID: " . $Subscription->id);
}

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