<?php
/**
 * EXAMPLE: mipl-webhook.php (on the merchant's website)
 * MIPL Payment Gateway POSTs here when a payment succeeds. Credit the wallet here.
 */
require __DIR__ . '/../php/MiplPay.php';
$pg = new MiplPay('mipl_live_xxxxxxxx', 'sk_xxxxxxxxxxxxxxxx', 'https://pay.moldable.in');

$raw = file_get_contents('php://input');
$event = $pg->verifyWebhook($raw, $_SERVER['HTTP_X_MIPL_SIGNATURE'] ?? '');
if (!$event) { http_response_code(401); exit('invalid signature'); }

if ($event['event'] === 'payment.success') {
    $p = $event['data'];
    $pdo = new PDO('mysql:host=localhost;dbname=yourdb;charset=utf8mb4', 'user', 'pass');

    // Idempotent: only mark 'pending' top-ups as 'paid' (duplicate webhooks will not double-credit)
    $st = $pdo->prepare("UPDATE wallet_topups SET status = 'paid', utr = ? WHERE order_id = ? AND status = 'pending' AND amount = ?");
    $st->execute([$p['utr'], $p['order_id'], $p['amount']]);

    if ($st->rowCount() === 1) {
        $pdo->prepare('UPDATE users u JOIN wallet_topups t ON t.user_id = u.id SET u.wallet = u.wallet + t.amount WHERE t.order_id = ?')
            ->execute([$p['order_id']]);
    }
}
http_response_code(200);
echo 'OK';
