<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('con.php');

$msg   = "";
$error = "";

/* ================= UPDATE BALANCE ================= */
if(isset($_POST['submit'])){

    $username = trim($_POST['username']);
    $amount   = floatval($_POST['amount']);

    if(empty($username)){

        $error = "Please enter username.";

    }elseif($amount <= 0){

        $error = "Please enter valid amount.";

    }else{

        /* ===== FETCH USER ===== */
        $stmt = $ahk_conn->prepare(
            "SELECT * FROM commissionuser WHERE username=?"
        );

        $stmt->bind_param("s", $username);
        $stmt->execute();

        $result = $stmt->get_result();

        if($result->num_rows == 0){

            $error = "Username not found.";

        }else{

            $user = $result->fetch_assoc();

            $old_balance = floatval($user['balance']);
            $new_balance = $old_balance + $amount;

            $orderid = "ORD" . rand(100000,999999);

            $ahk_conn->begin_transaction();

            try{

                /* ===== UPDATE BALANCE ===== */
                $stmt1 = $ahk_conn->prepare(
                    "UPDATE commissionuser 
                     SET balance=? 
                     WHERE username=?"
                );

                $stmt1->bind_param(
                    "ds",
                    $new_balance,
                    $username
                );

                $stmt1->execute();

                /* ===== INSERT WALLET HISTORY ===== */
                $purpose = "Insurance Commission";
                $status  = 1;
                $type    = "Credit";

                $stmt2 = $ahk_conn->prepare("
                    INSERT INTO wallethistory
                    (userid, amount, balance, purpose, status, type, orderid)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");

                $stmt2->bind_param(
                    "sddsiss",
                    $username,
                    $amount,
                    $new_balance,
                    $purpose,
                    $status,
                    $type,
                    $orderid
                );

                $stmt2->execute();

                $ahk_conn->commit();

                $msg = "Balance updated successfully.";

            }catch(Exception $e){

                $ahk_conn->rollback();

                $error = "Transaction failed.";

            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Update Commission Balance</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>

<body class="bg-light">

<div class="container py-5">

<div class="row justify-content-center">

<div class="col-lg-5">

<div class="card shadow p-4">

<h4 class="text-center text-primary mb-4">
Update Commission Balance
</h4>

<form method="POST">

<!-- SEARCH USERNAME -->
<div class="mb-3">

<label class="form-label">
Search Username / Number
</label>

<input type="text"
name="username"
class="form-control"
placeholder="Enter Username"
list="userlist"
autocomplete="off"
required>

<datalist id="userlist">

<?php
$userQuery = mysqli_query(
    $ahk_conn,
    "SELECT username 
     FROM commissionuser
     WHERE username IS NOT NULL
     AND username != ''
     ORDER BY username ASC"
);

while($u = mysqli_fetch_assoc($userQuery)){
?>

<option value="<?= htmlspecialchars($u['username']); ?>">

<?php } ?>

</datalist>

</div>

<!-- ENTER AMOUNT -->
<div class="mb-3">

<label class="form-label">
Enter Amount
</label>

<input type="number"
step="0.01"
name="amount"
class="form-control"
placeholder="Enter Amount"
required>

</div>

<!-- BUTTON -->
<button type="submit"
name="submit"
class="btn btn-success w-100">

Update Balance

</button>

</form>

</div>

</div>

</div>

</div>

<!-- SUCCESS MESSAGE -->
<?php if($msg): ?>

<script>
Swal.fire({
    icon:'success',
    title:'Success',
    text:'<?= $msg; ?>'
});
</script>

<?php endif; ?>

<!-- ERROR MESSAGE -->
<?php if($error): ?>

<script>
Swal.fire({
    icon:'error',
    title:'Error',
    text:'<?= $error; ?>'
});
</script>

<?php endif; ?>

</body>
</html>