<?php
require '../api//includes/db.php';

$secret = 'xKuo03pRgaTMU6nIzdt0hkgd'; // same as webhook dashboard

// Get raw POST body and verify signature
$body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_RAZORPAY_SIGNATURE'] ?? '';

$expected = hash_hmac('sha256', $body, $secret);

if ($signature !== $expected) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid signature']);
    exit;
}

// Decode payload
$data = json_decode($body, true);
if (!$data) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Invalid payload']);
    exit;
}

// Get details
$payment_id = $data['payload']['payment']['entity']['id'] ?? '';
$order_id = $data['payload']['payment']['entity']['order_id'] ?? '';
$status = $data['event'];

// Get txn_id from notes (set during checkout)
$txn_id = $data['payload']['payment']['entity']['notes']['txn_id'] ?? '';

if (!$txn_id) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'txn_id missing']);
    exit;
}

// Get user & payin request by txn_id
$stmt = $pdo->prepare("SELECT * FROM payin_requests WHERE txn_id = ? AND status = 'pending'");
$stmt->execute([$txn_id]);
$request = $stmt->fetch();

if (!$request) {
    http_response_code(404);
    echo json_encode(['status' => 'error', 'message' => 'Request not found or already processed']);
    exit;
}

$user_id = $request['user_id'];
$amount = $request['converted_amount']; // Or raw amount
$currency = $request['currency'];

// Update user balance
$stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
$stmt->execute([$amount, $user_id]);

// Update payin_requests status
$stmt = $pdo->prepare("UPDATE payin_requests SET status = 'approved', updated_at = NOW() WHERE txn_id = ?");
$stmt->execute([$txn_id]);

// Insert into transactions table
$stmt = $pdo->prepare("INSERT INTO transactions (txn_id, user_id, type, amount, status, payment_gateway, reference, created_at, currency) VALUES (?, ?, 'payin', ?, 'success', 'razorpay', ?, NOW(), ?)");
$stmt->execute([$txn_id, $user_id, $amount, $payment_id, $currency]);

http_response_code(200);
echo json_encode(['status' => 'success']);
