<?php
session_start();
if ($_SESSION['unohs'] == null) {
    header("location:index.php?msg=unauthorized");
}
date_default_timezone_set("Asia/Kolkata");
?>

<?php
include("conn.php");

// Bonus type mapping
$bonusTypes = [
    3   => "Red envelope",
    8   => "Agent red envelope recharge",
    10  => "Recharge gift",
    13  => "Bonus recharge",
    14  => "First full gift",
    20  => "Invite bonus",
    25  => "Card binding gift",
    107 => "Weekly Awards",
    124 => "Agent Bonus",
    118 => "Daily Awards",
    117 => "New members get bonuses by playing games",
    115 => "Return Awards",
];

// Function to add bonus and update wallet
function addBonus($userId, $type, $amount, $remark, $conn, $bonusTypes) {
    $tableNames = [
        3   => "hodike_balakedara",
        8   => "agent_red_envelope_recharge_table",
        10  => "recharge_gift_table",
        13  => "bonus_recharge_table",
        14  => "first_full_gift_table",
        20  => "invite_bonus_table",
        25  => "card_binding_gift_table",
        107 => "weekly_awards_table",
        124 => "agent_bonus_table",
        118 => "daily_awards_table",
        117 => "new_members_bonus_table",
        115 => "return_awards_table",
    ];

    if (!isset($tableNames[$type])) {
        return "❌ Invalid bonus type selected.";
    }

    $tableName = $tableNames[$type];
    $date = date("Y-m-d H:i:s");
    $serial = "Imitator";

    // Insert into the specific bonus table
    $stmt = $conn->prepare("INSERT INTO $tableName (userkani, price, serial, shonu, remark) VALUES (?, ?, ?, ?, ?)");
    if (!$stmt) {
        return "❌ Error preparing bonus insert: " . $conn->error;
    }

    $stmt->bind_param("idsss", $userId, $amount, $serial, $date, $remark);
    if (!$stmt->execute()) {
        $stmt->close();
        return "❌ Bonus insert failed: " . $stmt->error;
    }
    $stmt->close();

    // Update wallet balance in shonu_kaichila
    $updateWallet = $conn->prepare("UPDATE shonu_kaichila SET motta = motta + ? WHERE balakedara = ?");
    if (!$updateWallet) {
        return "⚠️ Bonus added, but error preparing wallet update: " . $conn->error;
    }

    $updateWallet->bind_param("di", $amount, $userId);
    if ($updateWallet->execute()) {
        $updateWallet->close();
        return "✅ Bonus added and ₹" . number_format($amount, 2) . " updated to wallet.";
    } else {
        $updateWallet->close();
        return "⚠️ Bonus added, but wallet update failed: " . $updateWallet->error;
    }
}

// Input handling
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = intval($_POST['user_id']);
    $type = intval($_POST['type']);
    $amount = floatval($_POST['amount']);
    $remark = htmlspecialchars($_POST['remark'] ?? '');

    // Validate inputs
    if ($userId > 0 && $type > 0 && $amount > 0) {
        $result = addBonus($userId, $type, $amount, $remark, $conn, $bonusTypes);
        echo "<div class='result'>" . htmlspecialchars($result) . "</div>";
    } else {
        echo "<div class='result error'>❌ Please provide valid inputs for all required fields: user_id, type, and amount.</div>";
    }
}
?>


<?php include 'header.php'; ?>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="row justify-content-center">
            <div class="col-lg-6 col-md-8">
                <div class="card shadow-sm p-4">
                    <h4 class="font-weight-bold text-dark mb-3">
                        🎁 Assign Bonus to User
                    </h4>

                    <?php if (isset($result)): ?>
                        <div class="alert alert-<?php echo (strpos($result, '✅') !== false) ? 'success' : 'danger'; ?>">
                            <?= htmlspecialchars($result) ?>
                        </div>
                    <?php endif; ?>

                    <form method="POST">
                        <div class="mb-3">
                            <label for="user_id" class="form-label">👤 User ID</label>
                            <input type="number" class="form-control" name="user_id" id="user_id" required>
                        </div>

                        <div class="mb-3">
                            <label for="type" class="form-label">📦 Bonus Type</label>
                            <select class="form-select" name="type" id="type" required>
                                <option value="" disabled selected>Select bonus type</option>
                                <?php foreach ($bonusTypes as $typeId => $typeName): ?>
                                    <option value="<?= $typeId ?>"><?= htmlspecialchars($typeName) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="amount" class="form-label">💰 Bonus Amount</label>
                            <input type="number" class="form-control" step="0.01" name="amount" id="amount" required>
                        </div>

                        <div class="mb-3">
                            <label for="remark" class="form-label">📝 Remark (optional)</label>
                            <textarea class="form-control" name="remark" id="remark" rows="3" placeholder="e.g. First recharge reward"></textarea>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-success btn-lg">
                                ✅ Assign Bonus
                            </button>
                        </div>
                    </form>

                </div>
            </div>
        </div>
    </div>
</div>


         </form>
                </div>
            </div>
        </div>
    </div>

    <footer style="
  width: 100%;
  background: linear-gradient(90deg, #3b82f6, #10b981, #22c55e);
  color: white;
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  position: relative;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  font-family: 'Segoe UI', sans-serif;
  animation: rgbflow 8s ease infinite;
  background-size: 300% 300%;
  border-top: 2px solid rgba(255, 255, 255, 0.15);
">
  © <?= date('Y') ?> HYPER DEVELOPER Private Limited. All rights reserved. | <span style="color: #e0ffe0;">Patented & Protected</span>.
</footer>
</div>

      </div>
    </div>
  </div>
  
  <script>	
	if ( window.history.replaceState ) {
        window.history.replaceState( null, null, window.location.href );
    }
  </script>
</html>
