<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require '../includes/db.php'; // PDO connection assumed here

// Log function
function logCallback($msg) {
    file_put_contents("callback_logm.txt", date("Y-m-d H:i:s") . " - $msg\n", FILE_APPEND);
}

// Set JSON response header
header("Content-Type: application/json");

// New gateway secret key (update as per your config)
define('SECRET_KEY', 'b208669f0d6fc2e262786a8a523a61bc');

// Step 1: Get raw POST JSON input
$inputJSON = file_get_contents('php://input');
$data = json_decode($inputJSON, true);

if (!$data) {
    logCallback("No JSON data received.");
    echo json_encode(['message' => 'fail', 'reason' => 'No input data']);
    exit;
}

logCallback("Received callback: " . json_encode($data));

// Step 2: Verify required fields
$required = ['merchant_code', 'order_no', 'order_amount', 'status', 'sign'];
foreach ($required as $field) {
    if (!isset($data[$field])) {
        logCallback("Missing field: $field");
        echo json_encode(['message' => 'fail', 'reason' => "Missing $field"]);
        exit;
    }
}

// Step 3: Verify signature
$sign = $data['sign'];
$verify_data = $data;
unset($verify_data['sign']);
ksort($verify_data);

$sign_str = '';
foreach ($verify_data as $k => $v) {
    if ($v !== '') {
        $sign_str .= "$k=$v&";
    }
}
$sign_str .= "key=" . SECRET_KEY;

$generated_sign = strtoupper(md5($sign_str));

if ($generated_sign !== strtoupper($sign)) {
    logCallback("Signature mismatch. Expected: $generated_sign, Got: $sign");
    echo json_encode(['message' => 'fail', 'reason' => 'Signature mismatch']);
    exit;
}

// Step 4: Check payment status (assuming '1' means success)
if ((string)$data['status'] !== '1') {
    logCallback("Payment not successful, status: " . $data['status']);
    echo json_encode(['message' => 'fail', 'reason' => 'Payment not successful']);
    exit;
}

// Step 5: Find transaction by txn_id (order_no)
$txn_id = $data['order_no'];

$stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ? AND status = 'pending'");
$stmt->execute([$txn_id]);
$txn = $stmt->fetch();

if (!$txn) {
    logCallback("No pending transaction found for txn_id: $txn_id");
    // Return success to avoid retries by gateway
    echo json_encode(['message' => 'success', 'reason' => 'No pending transaction']);
    exit;
}

// Step 6: Update transaction and user balance
try {
    $pdo->beginTransaction();

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

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

    // Add amount to user balance (amount is stored in database in converted currency)
    $stmt = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
    $stmt->execute([$txn['amount'], $txn['user_id']]);

    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    logCallback("DB transaction failed: " . $e->getMessage());
    echo json_encode(['message' => 'fail', 'reason' => 'DB error']);
    exit;
}

// Step 7: Send webhook to user if configured
$stmt = $pdo->prepare("SELECT webhook_url, merchant_key FROM users WHERE id = ?");
$stmt->execute([$txn['user_id']]);
$user = $stmt->fetch();

if (!empty($user['webhook_url']) && !empty($user['merchant_key'])) {
    $webhook_url = $user['webhook_url'];
    $user_secret = $user['merchant_key'];

    $webhook_data = [
        "txn_id" => $txn_id,
        "status" => "success",
        "amount" => $txn['amount'],
        "order_sn" => $txn_id,
    ];

    // Sign webhook payload (uppercase MD5)
    $sorted = $webhook_data;
    ksort($sorted);
    $sign_str = '';
    foreach ($sorted as $k => $v) {
        $sign_str .= "$k=$v&";
    }
    $sign_str .= "key=" . $user_secret;
    $webhook_data['sign'] = strtoupper(md5($sign_str));

    // Log webhook
    file_put_contents("webhook_user_logm.txt", date("Y-m-d H:i:s") . " - Sending webhook to: $webhook_url\nPayload: " . json_encode($webhook_data) . "\n", FILE_APPEND);

    // Send webhook 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);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $response = curl_exec($ch);
    $error = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $log_msg = date("Y-m-d H:i:s") . " - Webhook response: HTTP $http_code, Response: $response, Curl error: $error\n\n";
    file_put_contents("webhook_user_logm.txt", $log_msg, FILE_APPEND);
}

echo json_encode(['message' => 'success']);
exit;
