<?php
include("config/db.php");

/* Verify Paystack signature */
$input = @file_get_contents("php://input");
$event = json_decode($input, true);

if (!$event) {
    http_response_code(400);
    exit();
}

/* Handle transfer success */
if ($event['event'] === 'transfer.success') {

    $transfer_code = $event['data']['transfer_code'];

    $stmt = $conn->prepare("SELECT * FROM withdrawals WHERE transfer_code=?");
    $stmt->bind_param("s", $transfer_code);
    $stmt->execute();
    $withdrawal = $stmt->get_result()->fetch_assoc();

    if ($withdrawal && $withdrawal['status'] === 'pending') {

        /* Deduct wallet */
        $stmt = $conn->prepare("UPDATE wallets SET balance = balance - ? WHERE user_id=?");
        $stmt->bind_param("di", $withdrawal['amount'], $withdrawal['user_id']);
        $stmt->execute();

        /* Mark success */
        $stmt = $conn->prepare("UPDATE withdrawals SET status='success' WHERE transfer_code=?");
        $stmt->bind_param("s", $transfer_code);
        $stmt->execute();
    }
}

/* Handle transfer failure */
if ($event['event'] === 'transfer.failed') {

    $transfer_code = $event['data']['transfer_code'];

    $stmt = $conn->prepare("UPDATE withdrawals SET status='failed' WHERE transfer_code=?");
    $stmt->bind_param("s", $transfer_code);
    $stmt->execute();
}

http_response_code(200);