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

header('Content-Type: application/json');
$villager = requireVillagerToken($pdo);

$orderid = cleanInput($_POST['razorpay_order_id'] ?? '');
$paymentid = cleanInput($_POST['razorpay_payment_id'] ?? '');
$signature = cleanInput($_POST['razorpay_signature'] ?? '');

if ($orderid === '' || $paymentid === '' || $signature === '') {
    jsonOut(false, 'Missing payment verification data');
}

try {
    // Defensive: ensure this order belongs to the authenticated villager
    $stmt = $pdo->prepare("SELECT id FROM paymentorder WHERE razorpayorderid = ? AND villagerid = ? AND isdeleted = 0");
    $stmt->execute([$orderid, $villager['id']]);
    if (!$stmt->fetch()) {
        jsonOut(false, 'Order does not belong to this account');
    }

    if (!razorpayVerifyPaymentSignature($orderid, $paymentid, $signature)) {
        logDebug('[api_paymentverify] Signature mismatch for order ' . $orderid);
        jsonOut(false, 'Payment verification failed. If money was deducted, it will be confirmed automatically.');
    }

    $result = markOrderPaidAndActivatePass($pdo, $orderid, $paymentid, $signature);
    jsonOut($result['success'], $result['message']);
} catch (Exception $e) {
    logDebug('[api_paymentverify] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong while verifying payment');
}
