<?php
// Prevent direct access
if (count(get_included_files()) === 1) {
    http_response_code(403);
    exit('Forbidden');
}

// Stripe webhook — POST /webhook/stripe
// Sin sesión. Verifica firma HMAC, procesa evento, responde 200.

require_once dirname(__DIR__) . '/services/billing.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$rawBody   = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

try {
    $db      = DB::connect();
    $handled = BillingService::handleStripeWebhook($db, $rawBody, $sigHeader);
    http_response_code(200);
    echo json_encode(['ok' => true, 'handled' => $handled]);
} catch (RuntimeException $e) {
    error_log('[Stripe Webhook] ' . $e->getMessage());
    http_response_code(400);
    echo json_encode(['error' => $e->getMessage()]);
}
