<?php
declare(strict_types=1);

require_once __DIR__ . '/paystack_common.php';

$secret = ld_paystack_secret();
$rawBody = file_get_contents('php://input') ?: '';
$signature = $_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] ?? '';

$expected = hash_hmac('sha512', $rawBody, $secret);

if (!$signature || !hash_equals($expected, $signature)) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Invalid Paystack signature.']);
    exit;
}

$event = json_decode($rawBody, true);

if (!is_array($event)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON.']);
    exit;
}

// Acknowledge non-payment events safely.
if (($event['event'] ?? '') !== 'charge.success') {
    http_response_code(200);
    echo json_encode(['success' => true, 'ignored' => true]);
    exit;
}

$reference = $event['data']['reference'] ?? '';

if (!$reference) {
    http_response_code(200);
    echo json_encode(['success' => true, 'ignored' => true, 'reason' => 'Missing reference.']);
    exit;
}

try {
    $pdo = ld_pdo();

    // Always verify from Paystack before crediting.
    $verify = ld_paystack_request('GET', '/transaction/verify/' . rawurlencode($reference));

    if (($verify['status'] ?? false) && (($verify['data']['status'] ?? '') === 'success')) {
        $result = ld_process_successful_deposit($pdo, $reference, $verify);
        http_response_code(200);
        echo json_encode($result, JSON_UNESCAPED_SLASHES);
        exit;
    }

    http_response_code(200);
    echo json_encode(['success' => true, 'paid' => false, 'status' => $verify['data']['status'] ?? 'unknown']);
    exit;
} catch (Throwable $e) {
    // Return 200 to avoid endless webhook retries after a handled internal issue.
    http_response_code(200);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    exit;
}
