<?php
/**
 * updatewalbalNow.php
 * Agent-এর wallet balance আপডেট করে।
 *
 * Table: shonu_kaichila
 *   - balakedara = user id (shonu_subjects.id)
 *   - motta      = balance (varchar, কিন্তু numeric value রাখে)
 *
 * POST params:
 *   editid  → agent-এর userid (shonu_subjects.id)
 *   amount  → যত টাকা add করবে (numeric)
 */

session_start();

// ─── 1. Auth check ─────────────────────────────────────────────────────────
if (!isset($_SESSION['unohs'])) {
    echo "0"; // Unauthorized
    exit;
}

// ─── 2. DB connection ───────────────────────────────────────────────────────
include('conn.php');

// ─── 3. Request check ───────────────────────────────────────────────────────
if (!isset($_POST['editid'], $_POST['amount'])) {
    echo "0";
    exit;
}

// ─── 4. Input validation ────────────────────────────────────────────────────
if (!ctype_digit((string) $_POST['editid'])) {
    echo "0"; // editid অবশ্যই positive integer হতে হবে
    exit;
}

if (!is_numeric($_POST['amount'])) {
    echo "0"; // amount অবশ্যই numeric হতে হবে
    exit;
}

$roleid = (int)   $_POST['editid'];
$amount = (float) $_POST['amount'];

if ($amount <= 0) {
    echo "0"; // শুধু positive amount allow
    exit;
}

// ─── 5. Agent exist কিনা যাচাই করো ────────────────────────────────────────
$chk = mysqli_prepare($conn, "SELECT userid FROM tb_agent WHERE userid = ? AND status = 1");
mysqli_stmt_bind_param($chk, "i", $roleid);
mysqli_stmt_execute($chk);
mysqli_stmt_store_result($chk);
if (mysqli_stmt_num_rows($chk) === 0) {
    mysqli_stmt_close($chk);
    echo "0"; // Agent পাওয়া যায়নি বা inactive
    exit;
}
mysqli_stmt_close($chk);

// ─── 6. Wallet balance update (shonu_kaichila) ─────────────────────────────
// NOTE: motta কলামটা varchar কিন্তু numeric value রাখে,
//       তাই CAST করে add করতে হচ্ছে।
$stmt1 = mysqli_prepare($conn,
    "UPDATE shonu_kaichila 
     SET motta = CAST(CAST(motta AS DECIMAL(15,2)) + ? AS CHAR)
     WHERE balakedara = ?"
);
mysqli_stmt_bind_param($stmt1, "di", $amount, $roleid);
$r1 = mysqli_stmt_execute($stmt1);
mysqli_stmt_close($stmt1);

// ─── 7. dailysalary status আপডেট ──────────────────────────────────────────
$stmt2 = mysqli_prepare($conn,
    "UPDATE dailysalary SET status = 1 WHERE userid = ?"
);
mysqli_stmt_bind_param($stmt2, "i", $roleid);
$r2 = mysqli_stmt_execute($stmt2);
mysqli_stmt_close($stmt2);

// ─── 8. Response ────────────────────────────────────────────────────────────
if ($r1 && mysqli_affected_rows($conn) >= 0) {
    echo "1"; // Success
} else {
    echo "0"; // Failed
}
?>
