<?php
require_once 'element/connection.php';
require_once 'element/header.php';
require_once 'element/sidebar.php';
require_once 'element/tree_rewards.php';

$userId = $_SESSION['user_id'] ?? 1;

$levelAmounts = [
    1 => 250, 2 => 350, 3 => 500, 4 => 800, 5 => 1200, 6 => 1900,
    7 => 3200, 8 => 5100, 9 => 7500, 10 => 10000, 11 => 0
];

// 1. Process the reward system
$rewardsGiven = processLevelPayments($conn, $userId, $levelAmounts);

// 2. Calculate wallet balances
$walletRes = mysqli_query($conn, "SELECT wallet FROM users WHERE user_id = '$userId'");
$walletData = mysqli_fetch_assoc($walletRes);
$wallet = $walletData['wallet'] ?? 0;

// 3. Withdrawal request form
?>
<div class="container">
    <h4>Wallet Balance: ₹<?= $wallet ?></h4>

    <?php if (!empty($rewardsGiven)): ?>
        <div class="alert alert-success">
            <?php foreach ($rewardsGiven as $reward): ?>
                ✅ Level <?= $reward['level'] ?> completed! ₹<?= $reward['amount'] ?> credited.<br>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="element/redirect.php">
        <input type="hidden" name="withdrawl_request" value="1">
        <input type="hidden" name="user_id" value="<?= $userId ?>">
        <input type="number" name="amount" max="<?= $wallet ?>" required placeholder="Enter withdrawal amount">
        <button type="submit" class="btn btn-primary">Request Withdrawal</button>
    </form>

    <br><hr><br>

    <form action="element/redirect.php" method="POST">
        <input type="hidden" name="user_registration" value="1">
        <label>Sponsor ID:</label><input type="number" name="sponsor_id" required>
        <label>PIN:</label><input type="text" name="pin" required>
        <label>Name:</label><input type="text" name="user_name" required>
        <label>Position:</label>
        <select name="position">
            <option value="0">Left</option>
            <option value="1">Right</option>
        </select>
        <label>Mobile:</label><input type="text" name="user_mob" required>
        <label>Password:</label><input type="password" name="password" required>
        <button type="submit">Add Member</button>
    </form>
</div>
