<?php
// webhook.php

require 'require/conn.php'; // Your DB connection file

$secret = "Aspfiy-8fcf1b2ecf84e2dffa3388e4ded9c48a"; // Webhook secret/API key

// Get the raw POST data
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// OPTIONAL: Log raw input for debugging
file_put_contents('webhook_log.txt', $input . PHP_EOL, FILE_APPEND);

// Validate essential fields in the payload
if (!isset($data['status']) || !isset($data['phone']) || !isset($data['amount'])) {
    http_response_code(400);
    echo json_encode(['message' => 'Invalid payload']);
    exit();
}

$status = $data['status'];
$phone = $data['phone'];
$amount = floatval($data['amount']); // Incoming amount (e.g. 1000)

// Validate webhook signature (if Aspfiy sends one)
$headers = getallheaders();
$signature = isset($headers['X-Aspfiy-Signature']) ? $headers['X-Aspfiy-Signature'] : '';

$computedSignature = hash_hmac('sha256', $input, $secret);

if ($signature !== $computedSignature) {
    http_response_code(403);
    echo json_encode(['message' => 'Invalid signature']);
    exit();
}

// Only process successful transactions
if ($status === 'success') {

    // Deduct ₦50 per transfer
    $fee = 50;
    $creditedAmount = $amount - $fee;

    // Safety check: Don't credit negative amounts
    if ($creditedAmount < 0) $creditedAmount = 0;

    // Fetch user's user_id + current wallet_balance by phone
    $stmt = $conn->prepare("SELECT id, wallet_balance FROM jamaa WHERE phone = ?");
    $stmt->bind_param("s", $phone);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows !== 1) {
        http_response_code(404);
        echo json_encode(['message' => 'User not found']);
        exit();
    }

    $user = $result->fetch_assoc();
    $user_id = intval($user['id']);
    $currentBalance = floatval($user['wallet_balance']);

    // Add the credited amount to the current balance
    $newBalance = $currentBalance + $creditedAmount;

    // Update user's wallet_balance
    $updateStmt = $conn->prepare("UPDATE jamaa SET wallet_balance = ? WHERE id = ?");
    $updateStmt->bind_param("di", $newBalance, $user_id);

    if ($updateStmt->execute()) {

        // Log the transaction (with user_id)
        $logStmt = $conn->prepare("
            INSERT INTO transactions (user_id, phone, amount, fee, credited, status) 
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $logStmt->bind_param("isddds", $user_id, $phone, $amount, $fee, $creditedAmount, $status);
        $logStmt->execute();

        http_response_code(200);
        echo json_encode([
            'message' => 'Wallet updated successfully',
            'user_id' => $user_id,
            'credited_amount' => $creditedAmount,
            'new_balance' => $newBalance
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['message' => 'Failed to update wallet']);
    }

} else {
    // For failed transactions, do nothing but return 200
    http_response_code(200);
    echo json_encode(['message' => 'No action for failed transaction']);
}

?>
