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

file_put_contents("log.txt", date("Y-m-d H:i:s") . " - Received: " . json_encode($_POST) . "\n", FILE_APPEND);


// LG-Pay credentials
define('LG_APP_SECRET', 'DD3UsTt84Wsf6pQAw9SH5dgbzbVd8xYX'); // LG Pay ka key

// Step 1: Read callback data
$data = $_POST;
if (!$data) {
    echo 'fail'; 
    exit;
}

// Step 2: Extract required fields
$sign = $data['sign'] ?? '';
$order_sn = $data['order_sn'] ?? '';
$status = $data['status'] ?? 0;
$money = $data['money'] ?? 0;

// Step 3: Verify LG-Pay Signature
$verify_data = $data;
unset($verify_data['sign']);
ksort($verify_data);
$sign_string = '';
foreach ($verify_data as $k => $v) {
    $sign_string .= "$k=$v&";
}
$sign_string .= "key=" . LG_APP_SECRET;
$generated_sign = strtoupper(md5($sign_string));

if ($generated_sign !== $sign) {
    echo 'fail'; 
    exit;
}

// Step 4: Process payment if status is success
if ($status == 1) {
    $stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ? AND status = 'pending'");
    $stmt->execute([$order_sn]);
    $txn = $stmt->fetch();

    if ($txn) {
        $user_id = $txn['user_id'];
        $amount = $txn['amount'];
        $txn_id = $txn['txn_id'];

        // Update transaction
        $stmt = $pdo->prepare("UPDATE transactions SET status = 'success', webhook_sent = 1 WHERE txn_id = ?");
        $stmt->execute([$order_sn]);

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

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

        // =========== NEW: Call user's webhook ===============
        // Fetch user's webhook_url and merchant_key from database
$stmt = $pdo->prepare("SELECT webhook_url, merchant_key FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!empty($user['webhook_url']) && !empty($user['merchant_key'])) {
    $webhook_url = $user['webhook_url'];
    $user_secret = $user['merchant_key']; // ✅ now using correct key

    // Payload to send to user's system
    $webhook_data = [
        "txn_id" => $txn_id,
        "status" => "success",
        "amount" => $amount,
        "order_sn" => $order_sn
    ];

    // Generate signature
    $sorted = $webhook_data;
    ksort($sorted);
    $sign_str = '';
    foreach ($sorted as $k => $v) {
        $sign_str .= "$k=$v&";
    }
    $sign_str .= "key=" . $user_secret;
    $user_signature = strtoupper(md5($sign_str));
    $webhook_data['sign'] = $user_signature;

    // Send POST request
    $ch = curl_init($webhook_url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($webhook_data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);

    // Logging
    file_put_contents('webhook_log.txt', date('Y-m-d H:i:s') . " - Sent to: $webhook_url\nPayload: " . json_encode($webhook_data) . "\nResponse: $response\nError: $error\n\n", FILE_APPEND);
}


        echo 'success'; 
        exit;
    }
}

echo 'fail';
