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

require '../includes/db.php'; // Make sure this points correctly

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $txn_id = $_POST['txn_id'] ?? '';

    if (!$txn_id) {
        $message = "Transaction ID is required.";
    } else {
        // Check if txn exists and is still pending
        $stmt = $pdo->prepare("SELECT * FROM transactions WHERE txn_id = ? AND status = 'pending'");
        $stmt->execute([$txn_id]);
        $txn = $stmt->fetch();

        if (!$txn) {
            $message = "Transaction not found or already processed.";
        } else {
            try {
                $pdo->beginTransaction();

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

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

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

                $pdo->commit();

                // Fetch user for webhook
                $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,
                    ];

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

                    // Send webhook
                    $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);
                    $response = curl_exec($ch);
                    $error = curl_error($ch);
                    curl_close($ch);

                    $message = "Transaction marked successful and webhook sent. Response: " . htmlentities($response);
                } else {
                    $message = "Transaction marked successful. No webhook URL configured for user.";
                }

            } catch (Exception $e) {
                $pdo->rollBack();
                $message = "Error updating transaction: " . $e->getMessage();
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Manual Success - Admin</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f9f9f9; padding: 30px; }
        .box { max-width: 500px; margin: auto; background: white; padding: 25px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h2 { text-align: center; }
        input[type="text"], input[type="submit"] {
            width: 100%; padding: 10px; margin: 10px 0; border-radius: 5px; border: 1px solid #ccc;
        }
        .message { padding: 10px; background: #eef; margin-top: 15px; border-radius: 5px; }
    </style>
</head>
<body>

<div class="box">
    <h2>Manual Transaction Success</h2>
    <form method="POST">
        <label for="txn_id">Enter Transaction ID:</label>
        <input type="text" name="txn_id" id="txn_id" required placeholder="e.g. TXN123456789">
        <input type="submit" value="Mark as Success">
    </form>

    <?php if (isset($message)): ?>
        <div class="message"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>
</div>

</body>
</html>
