<?php
header("Content-Type: application/json");
require '../includes/db.php';

$razorpay_secret = 'xKuo03pRgaTMU6nIzdt0hkgd';
$input = file_get_contents("php://input");
$data = json_decode($input, true);

// Validate signature
$order_id = $data['razorpay_order_id'] ?? '';
$payment_id = $data['razorpay_payment_id'] ?? '';
$signature = $data['razorpay_signature'] ?? '';
$expected_signature = hash_hmac('sha256', "$order_id|$payment_id", $razorpay_secret);

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

// Get Razorpay order details
$ch = curl_init("https://api.razorpay.com/v1/orders/$order_id");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, "rzp_test_t0n7zauFE1LiI7:$razorpay_secret");
$response = curl_exec($ch);
curl_close($ch);

$orderData = json_decode($response, true);
$txn_id = $orderData['receipt'];
$amount = $orderData['amount'] / 100;
$currency = $orderData['currency'];

// Lookup DB
$stmt = $pdo->prepare("SELECT * FROM payin_requests WHERE txn_id = ? LIMIT 1");
$stmt->execute([$txn_id]);
$payin = $stmt->fetch();

if (!$payin || $payin['status'] === 'approved') {
    echo json_encode(["status" => "error", "message" => "Already processed"]);
    exit;
}

$user_id = $payin['user_id'];

$stmt = $pdo->prepare("SELECT * FROM user_currencies WHERE user_id = ? AND currency_code = ?");
$stmt->execute([$user_id, $currency]);
$rate_data = $stmt->fetch();
$rate = $rate_data['payin_rate'];
$fee_percent = $rate_data['payin_fee_percent'] ?? 0;

$converted = $amount * $rate;
$fee = ($converted * $fee_percent) / 100;
$final_amount = $converted - $fee;

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

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

// Insert transaction
$stmt = $pdo->prepare("INSERT INTO transactions (
    txn_id, user_id, type, amount, status, payment_gateway,
    reference, created_at, admin_id, user_note,
    currency, fee, from_currency, to_currency,
    conversion_rate, webhook_sent
) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?)");

$stmt->execute([
    $txn_id, $user_id, 'payin', $final_amount, 'success', 'razorpay',
    $payment_id, null, null, $currency, $fee,
    $currency, 'INR', $rate, 0
]);

echo json_encode(["status" => "success", "message" => "Verified and balance updated"]);
