<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/db.php';
use App\Order;

$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
$env = parse_ini_file(__DIR__ . '/../.env', INI_SCANNER_RAW) ?: [];
$webhook_secret = $env['STRIPE_WEBHOOK_SECRET'] ?? getenv('STRIPE_WEBHOOK_SECRET');

try {
    if ($webhook_secret) {
        $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $webhook_secret);
    } else {
        // If no webhook secret configured, attempt to parse without verification (NOT recommended)
        $event = json_decode($payload);
    }
} catch (\UnexpectedValueException $e) {
    http_response_code(400);
    echo 'Invalid payload';
    exit;
} catch (\Stripe\Exception\SignatureVerificationException $e) {
    http_response_code(400);
    echo 'Invalid signature';
    exit;
}

// Handle the event
if (is_object($event) && ($event->type ?? null) === 'checkout.session.completed') {
    $session = $event->data->object;
    $sessionId = $session->id ?? null;
    if ($sessionId) {
        Order::updateStatusBySession($sessionId, 'paid');
    }
}

http_response_code(200);
echo 'ok';
