<?php
declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/lib/db.php';
require_once dirname(__DIR__, 2) . '/lib/tenant.php';
require_once dirname(__DIR__, 2) . '/lib/payments.php';

$provider = strtolower((string) ($_GET['provider'] ?? ''));
$tenantParam = tenant_param();
$_GET['tenant'] = $tenantParam;
$tenant = resolve_tenant_from_host();
if (!$tenant) {
    http_response_code(404);
    echo 'not found';
    exit;
}
$tenantId = (int) $tenant['id'];
$settings = payment_settings($tenantId);
$payload = file_get_contents('php://input') ?: '';
$json = json_decode($payload, true);

try {
    if ($provider === 'stripe') {
        // Lightweight verify: if webhook secret set, require Stripe-Signature header presence (full HMAC can be added with Stripe SDK).
        $sig = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
        if (!empty($settings['stripe_webhook_secret']) && $sig === '') {
            http_response_code(400);
            echo 'missing signature';
            exit;
        }
        $type = (string) ($json['type'] ?? '');
        $obj = $json['data']['object'] ?? [];
        if ($type === 'checkout.session.completed' && !empty($obj['id'])) {
            $pay = payment_find_by_external('stripe', (string) $obj['id']);
            if ($pay && (int) $pay['tenant_id'] === $tenantId) {
                payment_mark_paid((int) $pay['id'], (string) $obj['id'], is_array($obj) ? $obj : null);
            }
        }
        echo 'ok';
        exit;
    }

    if ($provider === 'paypal') {
        $event = (string) ($json['event_type'] ?? '');
        $resource = $json['resource'] ?? [];
        $orderId = (string) ($resource['id'] ?? ($resource['supplementary_data']['related_ids']['order_id'] ?? ''));
        if (in_array($event, ['CHECKOUT.ORDER.APPROVED', 'PAYMENT.CAPTURE.COMPLETED', 'CHECKOUT.ORDER.COMPLETED'], true) && $orderId !== '') {
            $pay = payment_find_by_external('paypal', $orderId);
            if ($pay && (int) $pay['tenant_id'] === $tenantId) {
                if ($event === 'CHECKOUT.ORDER.APPROVED') {
                    $gw = payment_gateway($tenantId, 'paypal');
                    $status = $gw->fetchStatus($orderId);
                    if (($status['status'] ?? '') === 'paid') {
                        payment_mark_paid((int) $pay['id'], $orderId, $status['raw'] ?? $resource);
                    }
                } else {
                    payment_mark_paid((int) $pay['id'], $orderId, is_array($resource) ? $resource : null);
                }
            }
        }
        echo 'ok';
        exit;
    }

    http_response_code(400);
    echo 'unknown provider';
} catch (Throwable $e) {
    http_response_code(500);
    echo 'error';
}
