<?php
require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/Billing/PaymentManager.php';

// Get the webhook payload
$payload = file_get_contents('php://input');
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

// For now, we'll skip signature verification in development
// In production, you should verify the signature using Stripe's webhook secret

// Log the webhook for debugging
error_log('Stripe Webhook received: ' . $payload);

try {
    // Process the webhook
    $success = PaymentManager::processStripeWebhook();
    
    if ($success) {
        http_response_code(200);
        echo json_encode(['status' => 'success']);
    } else {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Webhook processing failed']);
    }
    
} catch (Exception $e) {
    error_log('Stripe Webhook error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
