<?php
include 'config.php';

// Get app settings
function getAppSettings($conn) {
    $settings = [
        "min_firstdp" => 0,
        "referral_bonus" => 0
    ];

    $query = "SELECT min_firstdp, referral_bonus FROM appinfo LIMIT 1";
    $result = $conn->query($query);

    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $settings["min_firstdp"] = (int)$row["min_firstdp"];
        $settings["referral_bonus"] = (int)$row["referral_bonus"];
    }
    return $settings;
}

$appSettings = getAppSettings($conn);
$min_firstdp = $appSettings["min_firstdp"];
$referral_bonus = $appSettings["referral_bonus"];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $type = $_POST['type'];

    // Admin auth
    $admin_username = $_POST['admin_username'];
    $admin_password = $_POST['admin_password'];

    $admin_stmt = $conn->prepare("SELECT 1 FROM admin WHERE username = ? AND password = ?");
    $admin_stmt->bind_param("ss", $admin_username, $admin_password);
    $admin_stmt->execute();
    $admin_result = $admin_stmt->get_result();

    if ($admin_result->num_rows === 0) {
        http_response_code(403);
        echo json_encode(["status" => "error", "message" => "Access Denied"]);
        exit();
    }
    $admin_stmt->close();

    // 1. Request
    if ($type === 'requestxstrong') {

        $name = $_POST['name'];
        $email = $_POST['email'];
        $method = $_POST['method'];
        $number = $_POST['number'];
        $amount = $_POST['amount'];
        $trxid = $_POST['trxid'];
        $fcm = $_POST['fcm'];
        $date = date("d-M-Y");
        $time = date("h:i:s A");

        $sql = "INSERT INTO addmoney (name, email, method, number, amount, trxid, date, time, fcm)
                VALUES ('$name','$email','$method','$number','$amount','$trxid','$date','$time','$fcm')";

        echo ($conn->query($sql)) ? "Request Successfully" : "Error Requesting";
    }

    // 2. Pending
    if ($type === 'pending') {

        $result = $conn->query("SELECT * FROM addmoney WHERE status='Pending'");
        $data = [];

        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $data[] = $row;
            }
            echo !empty($data) ? json_encode($data) : "No Unpaid Request Found";
        }
    }

    // 3. SUCCESS (BONUS LOGIC ADDED HERE ONLY)
    if ($type === 'success') {

        $amount = (int)$_POST['amount'];
        $email = $_POST['email'];
        $id = $_POST['id'];

        // 🔹 Deposit bonus check (NEW)
        $bonus = 0;
        $checkBonus = $conn->query(
            "SELECT bonus_amount FROM deposits WHERE deposit_amount = $amount LIMIT 1"
        );

        if ($checkBonus && $checkBonus->num_rows > 0) {
            $bonusRow = $checkBonus->fetch_assoc();
            $bonus = (int)$bonusRow['bonus_amount'];
        }

        $totalAdd = $amount + $bonus;

        // 🔹 Balance update (unchanged line, just value changed)
        $sql = "UPDATE users SET balance = balance + $totalAdd WHERE email = '$email'";
        $update = "UPDATE addmoney SET status='Success' WHERE id='$id'";

        if ($conn->query($sql) && $conn->query($update)) {

            // Referral logic (UNCHANGED except total_refer)
            $check = $conn->query("SELECT username, first_deposit_done, referred_by FROM users WHERE email='$email'");
            if ($check->num_rows > 0) {

                $userData = $check->fetch_assoc();
                $firstDone = $userData['first_deposit_done'];
                $referred_by = $userData['referred_by'];

                if ($firstDone == 0 && !empty($referred_by)) {

                    if ($amount >= $min_firstdp) {

                        // ✅ ONLY CHANGE: total_refer + 1 যোগ করা হয়েছে
                        $conn->query(
                            "UPDATE users 
                             SET refer_earn = refer_earn + $referral_bonus,
                                 total_refer = total_refer + 1,
                                 balance = balance + $referral_bonus
                             WHERE username = '$referred_by'"
                        );

                        $conn->query("UPDATE users SET first_deposit_done=1 WHERE email='$email'");
                        echo "Add Money + Referral Bonus Successfully";

                    } else {
                        $conn->query("UPDATE users SET first_deposit_done=1 WHERE email='$email'");
                        echo "Add Money Successfully (No Bonus)";
                    }

                } else {
                    echo "Add Money Successfully";
                }

            } else {
                echo "Add Money Successfully";
            }

        } else {
            echo "Error Add Money";
        }
    }

    // 4. Failed
    if ($type === 'failed') {
        $id = $_POST['Id'];
        echo ($conn->query("UPDATE addmoney SET status='Failed' WHERE id='$id'"))
            ? "Add Money Failed Success"
            : "Error Add Money";
    }

    $conn->close();
} else {
    echo "Invalid Request Method";
}
?>