<?php
include 'config.php';

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

    // STEP 0: Check Add Money status
    $psp = $conn->query("SELECT addmoney_open FROM appinfo WHERE id = 1 LIMIT 1");
    if (!$psp || $psp->num_rows == 0) {
        echo "Payment System Error";
        exit;
    }

    $pspData = $psp->fetch_assoc();
    $addmoneyOpen = intval($pspData['addmoney_open']);
    if ($addmoneyOpen === 1) {
        echo "Add Money Service is Currently Closed";
        exit;
    }

    $token  = $_POST["token"];
    $method = $_POST["method"];
    $trxid  = $_POST["trxid"];

    if (empty($token)) {
        echo "Token Missing";
        exit;
    }

    date_default_timezone_set('Asia/Dhaka');
    $date = date("d-M-Y");
    $time = date("h:i:s A");

    // USER BY TOKEN
    $username = '';
    $email = '';
    $fcm_key = '';

    $getUser = $conn->prepare("SELECT username, email, fcm_key FROM users WHERE token = ?");
    $getUser->bind_param("s", $token);
    $getUser->execute();
    $resultUser = $getUser->get_result();

    if ($resultUser->num_rows > 0) {
        $userData = $resultUser->fetch_assoc();
        $username = $userData['username'];
        $email = $userData['email'];
        $fcm_key = $userData['fcm_key'];
    } else {
        echo "Invalid Token";
        exit;
    }
    $getUser->close();

    // TRANSACTION CHECK (same as before)
    $stmt = $conn->prepare("SELECT amount, sender, status FROM ShuvoPays WHERE trnxid = ? AND `from` = ?");
    $stmt->bind_param("ss", $trxid, $method);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {

        $row = $result->fetch_assoc();
        $amount = intval($row["amount"]);
        $sender = $row["sender"];
        $status = intval($row["status"]);

        if ($status === 0) {

            $conn->begin_transaction();
            try {

                // 🔥 FIXED: atomic update (race condition solved)
                $update = $conn->prepare(
                    "UPDATE ShuvoPays 
                     SET status = 1, username = ? 
                     WHERE trnxid = ? AND status = 0"
                );
                $update->bind_param("ss", $username, $trxid);
                $update->execute();

                // 🔥 CRITICAL CHECK
                if ($update->affected_rows === 0) {
                    throw new Exception("Transaction Already Used");
                }

                // ===== REST SAME =====

                $sql = $conn->prepare(
                    "INSERT INTO addmoney 
                    (username, email, fcm, method, number, amount, trxid, status, date, time) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'Success', ?, ?)"
                );
                $sql->bind_param("sssssdsss",
                    $username, $email, $fcm_key, $method, $sender, $amount, $trxid, $date, $time
                );
                $sql->execute();

                // Bonus
                $bonus = 0;

                $checkBonus = $conn->prepare(
                    "SELECT bonus_amount FROM deposits WHERE deposit_amount = ? LIMIT 1"
                );
                $checkBonus->bind_param("i", $amount);
                $checkBonus->execute();
                $bonusRes = $checkBonus->get_result();

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

                $totalAdd = $amount + $bonus;

                $update2 = $conn->prepare(
                    "UPDATE users SET balance = balance + ? WHERE username = ?"
                );
                $update2->bind_param("is", $totalAdd, $username);
                $update2->execute();

                // Referral
                $checkReferral = $conn->prepare(
                    "SELECT referred_by, first_deposit_done FROM users WHERE username = ?"
                );
                $checkReferral->bind_param("s", $username);
                $checkReferral->execute();
                $resultRef = $checkReferral->get_result();

                $bonusGiven = false;

                if ($resultRef->num_rows > 0) {

                    $refData = $resultRef->fetch_assoc();
                    $referred_by = $refData['referred_by'];
                    $firstDone = intval($refData['first_deposit_done']);

                    $query = $conn->query(
                        "SELECT min_firstdp, referral_bonus FROM appinfo WHERE id = 1"
                    );
                    $rowData = $query->fetch_assoc();

                    $minDepAmount = intval($rowData['min_firstdp']);
                    $bonusAmount = intval($rowData['referral_bonus']);

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

                        // ✅ ONLY CHANGE: total_refer & refer_earn যোগ করা হয়েছে
                        $addBonus = $conn->prepare(
                            "UPDATE users 
                             SET balance = balance + ?, 
                                 total_refer = total_refer + 1, 
                                 refer_earn = refer_earn + ? 
                             WHERE username = ?"
                        );
                        $addBonus->bind_param("iis", $bonusAmount, $bonusAmount, $referred_by);
                        $addBonus->execute();
                        $bonusGiven = true;
                    }

                    if ($firstDone === 0) {
                        $markDone = $conn->prepare(
                            "UPDATE users SET first_deposit_done = 1 WHERE username = ?"
                        );
                        $markDone->bind_param("s", $username);
                        $markDone->execute();
                    }
                }

                $conn->commit();

                echo $bonusGiven
                    ? "Add Money + Referral Bonus Successfully"
                    : "Add Money Successfully";

            } catch (Exception $e) {
                $conn->rollback();
                echo "Add Money Failed";
            }

        } else {
            echo "Transaction ID Already Success";
        }

    } else {
        echo "Invalid Transaction ID";
    }

    $stmt->close();
    $conn->close();

} else {
    echo "Invalid Request Method";
}
?>