<?php
require './conn.php'; // assumes $mysqli is defined here

// Ensure the request is coming over HTTPS
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
    error_log("Insecure connection: request must use HTTPS");
    http_response_code(400);
    exit;
}

$rawPayload = file_get_contents("php://input");
$payload = json_decode($rawPayload, true);

// Check if the payload is valid
if (!$payload || !isset($payload['data'])) {
    error_log("Invalid webhook payload received");
    http_response_code(400);
    exit;
}

if (isset($payload['type']) && $payload['type'] === 'transfer') {
    $data = $payload['data'];

    // Validate the transaction status
    if ($data['isReversed'] !== false || $data['status'] !== 'Completed') {
        error_log("Payment not completed or was reversed.");
        http_response_code(400);
        exit;
    }

    // Ignore outward payments or transfers to your main account
    if ($data['type'] !== 'Inwards' || $data['creditAccountNumber'] === '0119824672') {
        error_log("Not an inward payment to a user account.");
        http_response_code(400);
        exit;
    }

    $accountNumber = $data['creditAccountNumber'];
    $amount = floatval($data['amount']);
    $reference = $data['paymentReference'];

    // Validate amount (positive and reasonable)
    if ($amount <= 0) {
        error_log("Invalid amount received: $amount");
        http_response_code(400);
        exit;
    }

    // Validate the payment reference (ensure it's not empty and reasonable)
    if (empty($reference)) {
        error_log("Invalid payment reference: $reference");
        http_response_code(400);
        exit;
    }

    // Prevent duplicate transactions using payment reference
    $check = $mysqli->prepare("SELECT id FROM transactions WHERE ref = ?");
    $check->bind_param("s", $reference);
    $check->execute();
    $check->store_result();
    if ($check->num_rows > 0) {
        error_log("Duplicate transaction detected.");
        http_response_code(209);
        exit;
    }

    // Find user by deposit_account number
    $stmt = $mysqli->prepare("SELECT id FROM users WHERE deposit_account = ?");
    $stmt->bind_param("s", $accountNumber);
    $stmt->execute();
    $stmt->store_result();
    if ($stmt->num_rows === 0) {
        error_log("No user found for account number.");
        http_response_code(404);
        exit;
    }
    $stmt->bind_result($userId);
    $stmt->fetch();

    // Use a transaction to ensure atomic operations
    $mysqli->begin_transaction();
    try {
        // Lock user record to prevent race condition during balance update
        $stmt = $mysqli->prepare("SELECT ngn_balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->bind_param("i", $userId);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows === 0) {
            throw new Exception("User not found");
        }
        
        // Update user balance
        $update = $mysqli->prepare("UPDATE users SET ngn_balance = ngn_balance + ? WHERE id = ?");
        $update->bind_param("di", $amount, $userId);
        if (!$update->execute()) {
            throw new Exception("Failed to update balance");
        }

        // Log transaction
        $time = time();
        $log = $mysqli->prepare("INSERT INTO transactions (flow, title, description, date, amount, ref, status, our_ref, email, user_id, payload) VALUES ('in', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $title = 'Wallet Funding';
        $desc = 'Funding NGN wallet balance';
        $status = 'Complete';
        $u = getUserInfo($userId);  // Fetch user info for email
        $log->bind_param("sssdssssis", $title, $desc, $time, $amount, $reference, $status, $reference, $u['email'], $userId, $rawPayload);
        $log->execute();

        // Send email
        $subject = "NGN Wallet Credited";
        $message = "
            Hello {$u['first_name']},<br><br>
            Your NGN wallet has been credited with <strong>₦" . number_format($amount, 2) . "</strong>.<br>
            <br><strong>Reference:</strong> $reference<br>
            <strong>Description:</strong> Wallet funding<br>
            <strong>Date:</strong> " . date('Y-m-d H:i:s', $time) . "
            <br><br>
            Thank you for funding with us.";

        sendMail($u['email'], $subject, $message);

        // Commit the transaction
        $mysqli->commit();
        error_log("User balance updated.");
        http_response_code(200);
    } catch (Exception $e) {
        // Rollback in case of error
        $mysqli->rollback();
        error_log("Error processing transaction: " . $e->getMessage());
        http_response_code(500);
    }
} else {
    error_log("Unhandled webhook type: " . $payload['type']);
    http_response_code(200); // or 400 depending on provider expectations
    exit;
}
?>
