<?php
require '../db.php';
require '../functions.php';

$rawbody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE'] ?? '';

$logstmt = $pdo->prepare("INSERT INTO paymentwebhooklog (payload, receivedat) VALUES (?, NOW())");
$logstmt->execute([$rawbody]);
$webhooklogid = $pdo->lastInsertId();

if ($rawbody === '' || $signature === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing payload or signature']);
    exit;
}

if (!razorpayVerifyWebhookSignature($rawbody, $signature)) {
    logDebug('[api_paymentwebhook] Invalid webhook signature');
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid signature']);
    exit;
}

$data = json_decode($rawbody, true);
$eventtype = $data['event'] ?? '';

$upd = $pdo->prepare("UPDATE paymentwebhooklog SET eventtype = ? WHERE id = ?");
$upd->execute([$eventtype, $webhooklogid]);

try {
    if ($eventtype === 'payment.captured' || $eventtype === 'order.paid') {
        $paymententity = $data['payload']['payment']['entity'] ?? null;
        if ($paymententity) {
            $razorpayorderid = $paymententity['order_id'] ?? '';
            $razorpaypaymentid = $paymententity['id'] ?? '';

            $updlog = $pdo->prepare("UPDATE paymentwebhooklog SET razorpayorderid = ?, razorpaypaymentid = ? WHERE id = ?");
            $updlog->execute([$razorpayorderid, $razorpaypaymentid, $webhooklogid]);

            if ($razorpayorderid !== '') {
                markOrderPaidAndActivatePass($pdo, $razorpayorderid, $razorpaypaymentid, null);
            }
        }
    } elseif ($eventtype === 'payment.failed') {
        $paymententity = $data['payload']['payment']['entity'] ?? null;
        if ($paymententity && !empty($paymententity['order_id'])) {
            $stmt = $pdo->prepare("UPDATE paymentorder SET status = 'failed' WHERE razorpayorderid = ? AND status != 'paid'");
            $stmt->execute([$paymententity['order_id']]);
        }
    }

    $markprocessed = $pdo->prepare("UPDATE paymentwebhooklog SET processed = 1 WHERE id = ?");
    $markprocessed->execute([$webhooklogid]);

    http_response_code(200);
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    logDebug('[api_paymentwebhook] ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Internal error']);
}
