<?php

require_once '../../core/api_bootstrap.php';

$payload = file_get_contents("php://input");

$signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE'];

$expected = hash_hmac(
'sha256',
$payload,
RAZORPAY_WEBHOOK_SECRET
);

if($expected !== $signature){

http_response_code(400);
exit("Invalid webhook signature");

}

$data = json_decode($payload,true);

$event = $data['event'];

if($event == "payment.captured"){

$payment = $data['payload']['payment']['entity'];

$order_id = $payment['order_id'];
$payment_id = $payment['id'];

$db = new Database();
$conn = $db->connect();

/* update payment */

$conn->prepare("

UPDATE payments
SET
razorpay_payment_id=:payment,
status='paid'

WHERE razorpay_order_id=:order

")->execute([

':payment'=>$payment_id,
':order'=>$order_id

]);

}

http_response_code(200);
echo "Webhook processed";
