<?php

session_start();

include "../includes/admin_auth.php";
include "../config/database.php";

if ($_SERVER["REQUEST_METHOD"] != "POST") {

    header("Location: members.php");
    exit();

}

$user_id = (int) $_POST['user_id'];
$amount  = (float) $_POST['amount'];

if ($amount <= 0) {

    $_SESSION['error'] = "Invalid amount.";
    header("Location: members.php");
    exit();

}

/* Get Current Wallet */

$stmt = $pdo->prepare("SELECT wallet_balance FROM users WHERE id=?");
$stmt->execute([$user_id]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {

    $_SESSION['error'] = "Member not found.";
    header("Location: members.php");
    exit();

}

$before = $user['wallet_balance'];
$after  = $before + $amount;

try {

    $pdo->beginTransaction();

    /* Update Wallet */

    $stmt = $pdo->prepare("
        UPDATE users
        SET wallet_balance=?
        WHERE id=?
    ");

    $stmt->execute([$after, $user_id]);

    /* Record Transaction */

    $reference = "FUND-" . strtoupper(uniqid());

    $stmt = $pdo->prepare("
        INSERT INTO wallet_transactions
        (
            user_id,
            transaction_type,
            amount,
            balance_before,
            balance_after,
            reference,
            description,
            status
        )

        VALUES
        (
            ?,?,?,?,?,?,?,?
        )
    ");

    $stmt->execute([

        $user_id,
        'funding',
        $amount,
        $before,
        $after,
        $reference,
        'Wallet funded by admin',
        'successful'

    ]);

    $pdo->commit();

    $_SESSION['success']="Wallet funded successfully.";

} catch(PDOException $e){

    $pdo->rollBack();

    $_SESSION['error']=$e->getMessage();

}

header("Location: members.php");

exit();