<?php
/**
 * agent_coin_panel.php
 * Agent → User কে Coin পাঠানোর পূর্ণ পেজ
 * ফাইলটা রাখো: OwnarJRred98/agent_coin_panel.php
 * teacher_nav.php তে link যোগ করো
 */
session_start();
if (!isset($_SESSION['teacher_id'])) {
    header("Location: teacher_login.php");
    exit;
}
include('conn.php');
$agent_id = (int)$_SESSION['teacher_id'];
$message = '';
$message_type = '';

// Agent wallet balance আনো
$bal_q = mysqli_query($conn,
    "SELECT CAST(motta AS DECIMAL(15,2)) as balance FROM shonu_kaichila WHERE balakedara='$agent_id'"
);
$bal_row = mysqli_fetch_assoc($bal_q);
$agent_balance = $bal_row ? (float)$bal_row['balance'] : 0;

// Coin পাঠানোর action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_id'], $_POST['amount'])) {
    $user_id = (int)$_POST['user_id'];
    $amount  = (float)$_POST['amount'];

    do {
        if ($amount <= 0) { $message = 'Amount must be positive.'; $message_type = 'danger'; break; }
        if ($agent_balance < $amount) { $message = "Insufficient balance. Your balance: ₹$agent_balance"; $message_type = 'danger'; break; }

        // User exist ও আমার downline কিনা check
        $uq = mysqli_prepare($conn,
            "SELECT ss.id, ss.mobile FROM shonu_subjects ss
             WHERE ss.id = ? AND ss.status = 1"
        );
        mysqli_stmt_bind_param($uq, "i", $user_id);
        mysqli_stmt_execute($uq);
        $ur = mysqli_stmt_get_result($uq)->fetch_assoc();
        mysqli_stmt_close($uq);

        if (!$ur) { $message = 'User not found or inactive.'; $message_type = 'danger'; break; }

        // Agent balance কমাও
        $dec = mysqli_prepare($conn,
            "UPDATE shonu_kaichila
             SET motta = CAST(CAST(motta AS DECIMAL(15,2)) - ? AS CHAR)
             WHERE balakedara = ? AND CAST(motta AS DECIMAL(15,2)) >= ?"
        );
        mysqli_stmt_bind_param($dec, "did", $amount, $agent_id, $amount);
        mysqli_stmt_execute($dec);
        $aff = mysqli_stmt_affected_rows($dec);
        mysqli_stmt_close($dec);

        if ($aff === 0) { $message = 'Balance deduction failed (race condition).'; $message_type = 'danger'; break; }

        // User balance বাড়াও
        $inc = mysqli_prepare($conn,
            "UPDATE shonu_kaichila
             SET motta = CAST(CAST(motta AS DECIMAL(15,2)) + ? AS CHAR)
             WHERE balakedara = ?"
        );
        mysqli_stmt_bind_param($inc, "di", $amount, $user_id);
        mysqli_stmt_execute($inc);
        $uaff = mysqli_stmt_affected_rows($inc);
        mysqli_stmt_close($inc);

        // User wallet না থাকলে তৈরি করো
        if ($uaff === 0) {
            $ins = mysqli_prepare($conn,
                "INSERT INTO shonu_kaichila (balakedara, motta, rebet, spin, bonus) VALUES (?, ?, '0', 0, '0')"
            );
            $amt_str = (string)$amount;
            mysqli_stmt_bind_param($ins, "is", $user_id, $amt_str);
            mysqli_stmt_execute($ins);
            mysqli_stmt_close($ins);
        }

        // Balance refresh
        $agent_balance -= $amount;
        $message = "✅ ₹$amount successfully sent to user #{$user_id} ({$ur['mobile']})";
        $message_type = 'success';

    } while (false);
}

// আমার downline users (শুধু যারা আমার invitation code দিয়ে join করেছে)
$owncode_q = mysqli_query($conn,
    "SELECT owncode FROM shonu_subjects WHERE id='$agent_id'"
);
$owncode_row = mysqli_fetch_assoc($owncode_q);
$owncode = $owncode_row['owncode'] ?? '';

$users = [];
if ($owncode) {
    $ulist = mysqli_query($conn,
        "SELECT ss.id, ss.mobile,
                COALESCE(CAST(sk.motta AS DECIMAL(15,2)),0) as balance
         FROM shonu_subjects ss
         LEFT JOIN shonu_kaichila sk ON sk.balakedara = ss.id
         WHERE ss.code = '$owncode' AND ss.status = 1
         ORDER BY ss.id DESC
         LIMIT 200"
    );
    while ($u = mysqli_fetch_assoc($ulist)) {
        $users[] = $u;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Agent - Send Coin to User</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<style>
.balance-box { background:#001f3f; color:#fff; border-radius:12px; padding:20px; margin-bottom:24px; }
.balance-box h6 { opacity:.7; margin-bottom:4px; }
.balance-box h2 { font-size:2rem; font-weight:700; margin:0; }
.user-row:hover { background:#f0f4ff; cursor:pointer; }
.badge-bal { background:#e8f5e9; color:#2e7d32; padding:3px 10px; border-radius:20px; font-size:13px; }
</style>
</head>
<body class="bg-light">
<?php include 'teacher_nav.php'; ?>

<div class="container py-4">
  <h3 class="mb-4">💸 User কে Coin পাঠাও</h3>

  <!-- Agent Balance -->
  <div class="balance-box">
    <h6><span class="material-icons" style="font-size:16px;vertical-align:middle">account_balance_wallet</span> তোমার বর্তমান Coin Balance</h6>
    <h2>₹<?= number_format($agent_balance, 2) ?></h2>
  </div>

  <?php if ($message): ?>
  <div class="alert alert-<?= $message_type ?> alert-dismissible fade show">
    <?= htmlspecialchars($message) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
  </div>
  <?php endif; ?>

  <!-- Coin পাঠানোর Form -->
  <div class="card shadow-sm mb-4">
    <div class="card-body">
      <h5 class="card-title">Coin পাঠাও</h5>
      <form method="POST">
        <div class="row g-3">
          <div class="col-md-5">
            <label class="form-label">User ID</label>
            <input type="number" name="user_id" id="user_id_input" class="form-control" placeholder="User এর ID" required min="1">
          </div>
          <div class="col-md-5">
            <label class="form-label">Amount (₹)</label>
            <input type="number" name="amount" class="form-control" placeholder="পরিমাণ" required min="1" step="0.01" max="<?= $agent_balance ?>">
          </div>
          <div class="col-md-2 d-flex align-items-end">
            <button type="submit" class="btn btn-success w-100">পাঠাও</button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- আমার User List -->
  <div class="card shadow-sm">
    <div class="card-body">
      <h5 class="card-title">আমার Users (<?= count($users) ?>)</h5>
      <?php if (empty($users)): ?>
      <p class="text-muted">এখনো কোনো user তোমার invitation code দিয়ে join করেনি।</p>
      <?php else: ?>
      <div class="table-responsive">
        <table class="table table-bordered table-hover">
          <thead class="table-dark">
            <tr>
              <th>#</th>
              <th>User ID</th>
              <th>Mobile</th>
              <th>User Balance</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php $i = 1; foreach ($users as $u): ?>
            <tr class="user-row">
              <td><?= $i++ ?></td>
              <td><strong><?= $u['id'] ?></strong></td>
              <td><?= htmlspecialchars($u['mobile']) ?></td>
              <td><span class="badge-bal">₹<?= number_format($u['balance'], 2) ?></span></td>
              <td>
                <button class="btn btn-sm btn-primary"
                  onclick="fillUser(<?= $u['id'] ?>)">
                  <span class="material-icons" style="font-size:16px;vertical-align:middle">send</span>
                  Coin দাও
                </button>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
function fillUser(id) {
  document.getElementById('user_id_input').value = id;
  window.scrollTo({top:0, behavior:'smooth'});
}
</script>
</body>
</html>
