<?php
/**
 * admin_create_agent.php
 * Admin এখান থেকে সরাসরি Agent তৈরি করবে — নিজে mobile ও password ঠিক করে দেবে।
 * আগের agentuser.php-এর মতো existing user promote করার দরকার নেই।
 *
 * রাখো: Adminxxx78/admin_create_agent.php
 */
session_start();
if (!isset($_SESSION['unohs'])) {
    header("location:index.php?msg=unauthorized");
    exit;
}
include("conn.php");

/* ══════════════════════════════════════════════════════════
   নতুন যোগ — tb_agent টেবিলে commission_rate কলাম না থাকলে
   নিজে থেকেই তৈরি হয়ে যাবে (প্রতি Agent-এর GGR Commission %)
   ══════════════════════════════════════════════════════════ */
$colCheck = mysqli_query($conn, "SHOW COLUMNS FROM tb_agent LIKE 'commission_rate'");
if ($colCheck && mysqli_num_rows($colCheck) === 0) {
    mysqli_query($conn, "ALTER TABLE tb_agent ADD COLUMN commission_rate DECIMAL(5,2) NOT NULL DEFAULT 30.00");
}
$colCheck2 = mysqli_query($conn, "SHOW COLUMNS FROM tb_agent LIKE 'commission_type'");
if ($colCheck2 && mysqli_num_rows($colCheck2) === 0) {
    mysqli_query($conn, "ALTER TABLE tb_agent ADD COLUMN commission_type VARCHAR(20) NOT NULL DEFAULT 'ggr'");
}

$message = '';
$message_type = '';
$created_credentials = null;

// ─────────────────────────────────────────────────────────────
// ACTION 1: নতুন Agent তৈরি করো (mobile + password সরাসরি set)
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_agent'])) {
    $mobile_raw = trim($_POST['mobile'] ?? '');
    // ── 880 (Bangladesh) prefix সবসময় consistent রাখো ──
    $mobile_digits = preg_replace('/^(\+?880|\+?91|0)/', '', $mobile_raw);
    $mobile = ($mobile_digits !== '') ? '880' . $mobile_digits : '';
    $agent_email = trim($_POST['email'] ?? ''); // ✅ নতুন যোগ — Email (Login Verification-এর জন্য)
    $password = $_POST['password'] ?? '';
    $name     = trim($_POST['agent_name'] ?? '');
    $initial_coin = isset($_POST['initial_coin']) ? (float)$_POST['initial_coin'] : 0;
    $commission_rate = isset($_POST['commission_rate']) ? (float)$_POST['commission_rate'] : 30.0;
    if ($commission_rate < 0) { $commission_rate = 0; }
    if ($commission_rate > 100) { $commission_rate = 100; }
    $commission_type = (isset($_POST['commission_type']) && $_POST['commission_type'] === 'deposit') ? 'deposit' : 'ggr';

    if (!preg_match('/^880[0-9]{7,12}$/', $mobile)) {
        $message = 'সঠিক Mobile Number দাও (কমপক্ষে ৭ ডিজিট, 880 prefix সহ/ছাড়া দুটোই চলবে)।';
        $message_type = 'danger';
    } elseif (strlen($password) < 4) {
        $message = 'Password অন্তত ৪ অক্ষরের হতে হবে।';
        $message_type = 'danger';
    } else {
        // এই mobile আগে থেকেই আছে কিনা চেক করো
        $chk = mysqli_prepare($conn, "SELECT id FROM shonu_subjects WHERE mobile = ?");
        mysqli_stmt_bind_param($chk, "s", $mobile);
        mysqli_stmt_execute($chk);
        mysqli_stmt_store_result($chk);

        if (mysqli_stmt_num_rows($chk) > 0) {
            $message = "এই Mobile Number ($mobile) দিয়ে আগে থেকেই একটা account আছে। ভিন্ন number দাও, অথবা নিচের 'Password Reset' অংশ ব্যবহার করো।";
            $message_type = 'danger';
        } else {
            mysqli_stmt_close($chk);

            $custom_code = trim($_POST['custom_owncode'] ?? '');
            $code_error  = false;

            if ($custom_code !== '') {
                // Custom code দিলে সেটা আগে থেকে ব্যবহৃত কিনা চেক করো
                $codeChk = mysqli_prepare($conn, "SELECT id FROM shonu_subjects WHERE owncode = ?");
                mysqli_stmt_bind_param($codeChk, "s", $custom_code);
                mysqli_stmt_execute($codeChk);
                mysqli_stmt_store_result($codeChk);
                if (mysqli_stmt_num_rows($codeChk) > 0) {
                    $message = "এই Invitation Code ('$custom_code') আগে থেকেই অন্য কারো ব্যবহারে আছে। ভিন্ন code দাও।";
                    $message_type = 'danger';
                    $code_error = true;
                }
                mysqli_stmt_close($codeChk);
                $owncode = $custom_code;
            } else {
                $owncode = strtoupper(substr(md5(uniqid((string)mt_rand(), true)), 0, 8));
            }

            $md5pass    = md5($password);
            $now        = date('Y-m-d H:i:s');
            $ip         = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';

            if ($code_error) {
                // custom code আগে থেকে থাকলে এখানেই থেমে যাও, agent তৈরি হবে না
            } else {

            // ── ধাপ ১: shonu_subjects এ নতুন user তৈরি ──
            $ins = mysqli_prepare($conn,
                "INSERT INTO shonu_subjects
                 (mobile, email, password, code, code1, code2, code3, code4, code5,
                  owncode, privacy, status, createdate, ip, ishonup, pwd, shonullgnt,
                  tnegaresunohs, codechorkamukala)
                 VALUES (?, ?, ?, '', '', '', '', '', '', ?, 'on', '1', ?, ?, ?, ?, ?, 'admin-created', '')"
            );
            mysqli_stmt_bind_param($ins, "sssssssss",
                $mobile, $agent_email, $md5pass, $owncode, $now, $ip, $ip, $password, $now
            );

            if (mysqli_stmt_execute($ins)) {
                $new_id = mysqli_insert_id($conn);
                mysqli_stmt_close($ins);

                // ── ধাপ ২: tb_agent এ Agent হিসেবে যোগ করো ──
                // ✅ নতুন যোগ — কোন Admin এই Agent তৈরি করলো, তা Save করা
                $creatingAdminId = $_SESSION['unohs'];
                $ins2 = mysqli_prepare($conn,
                    "INSERT INTO tb_agent
                     (userid, mobile, status, type, salary, salarypercent, minrecharge, minbet, minreferrals, teacherid, createdate, created_by_admin, commission_rate, commission_type)
                     VALUES (?, ?, 1, 'day', 0, 0, 300, 300, 3, 0, ?, ?, ?, ?)"
                );
                mysqli_stmt_bind_param($ins2, "issids", $new_id, $mobile, $now, $creatingAdminId, $commission_rate, $commission_type);
                mysqli_stmt_execute($ins2);
                mysqli_stmt_close($ins2);

                // ── ধাপ ৩ (ঐচ্ছিক): শুরুতে কিছু coin দিয়ে দাও ──
                /* ══════════════════════════════════════════════════════════
                   ✅ নতুন যোগ — Admin-এর নিজের Balance Check করা। এখন
                   Admin আর "শূন্য থেকে" নতুন Agent-কে Coin দিতে পারবে
                   না — তার নিজের Balance-এ যা আছে, শুধু ততটাই দিতে
                   পারবে, আর দিলে তার নিজের Balance থেকেও কমে যাবে
                   (ঠিক admin_coin_generate.php-এর মতোই একই নীতি)।
                   ══════════════════════════════════════════════════════════ */
                if ($initial_coin > 0) {
                    $myUnohs = $_SESSION['unohs'];
                    $adminBalStmt = mysqli_prepare($conn, "SELECT motta FROM nirvahaka_shonu WHERE unohs = ?");
                    mysqli_stmt_bind_param($adminBalStmt, "s", $myUnohs);
                    mysqli_stmt_execute($adminBalStmt);
                    mysqli_stmt_bind_result($adminBalStmt, $adminBalanceRaw);
                    mysqli_stmt_fetch($adminBalStmt);
                    mysqli_stmt_close($adminBalStmt);
                    $adminBalance = floatval($adminBalanceRaw ?? 0);

                    if ($adminBalance < $initial_coin) {
                        // ✅ যথেষ্ট Balance নেই — Coin না দিয়েই এগিয়ে যাওয়া
                        // (Agent তবুও তৈরি হবে, শুধু Initial Coin ছাড়া)
                        $initial_coin_blocked_message = "⚠️ Agent তৈরি হয়েছে, কিন্তু তোমার নিজের Balance (৳" . number_format($adminBalance, 2) . ") অপর্যাপ্ত হওয়ায় Initial Coin দেওয়া যায়নি।";
                    } else {
                        // ✅ Admin-এর নিজের Balance থেকে কমানো
                        $deductStmt = mysqli_prepare($conn, "UPDATE nirvahaka_shonu SET motta = motta - ? WHERE unohs = ?");
                        mysqli_stmt_bind_param($deductStmt, "ds", $initial_coin, $myUnohs);
                        mysqli_stmt_execute($deductStmt);
                        mysqli_stmt_close($deductStmt);

                        $ins3 = mysqli_prepare($conn,
                            "INSERT INTO shonu_kaichila (balakedara, motta, rebet, spin, bonus) VALUES (?, ?, '0', 0, '0')"
                        );
                        $coin_str = (string)$initial_coin;
                        mysqli_stmt_bind_param($ins3, "is", $new_id, $coin_str);
                        mysqli_stmt_execute($ins3);
                        mysqli_stmt_close($ins3);
                    }
                }

                $created_credentials = [
                    'id' => $new_id,
                    'mobile' => $mobile,
                    'password' => $password,
                    'name' => $name,
                    'owncode' => $owncode,
                    'commission_rate' => $commission_rate,
                    'commission_type' => $commission_type,
                ];
                $message = "✅ Agent সফলভাবে তৈরি হয়েছে!";
                $message_type = 'success';
            } else {
                $message = 'Agent তৈরি করতে সমস্যা হয়েছে: ' . mysqli_error($conn);
                $message_type = 'danger';
            }
            } // code_error else বন্ধ
        }
    }
}

// ─────────────────────────────────────────────────────────────
// ACTION 2: Existing Agent-এর Password Reset করো
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['reset_password'])) {
    $reset_id  = (int)($_POST['reset_agent_id'] ?? 0);
    $new_pass  = $_POST['new_password'] ?? '';

    if ($reset_id <= 0 || strlen($new_pass) < 4) {
        $message = 'সঠিক Agent ID ও অন্তত ৪ অক্ষরের নতুন Password দাও।';
        $message_type = 'danger';
    } else {
        $chk = mysqli_prepare($conn,
            "SELECT ss.id, ss.mobile FROM shonu_subjects ss
             JOIN tb_agent ta ON ta.userid = ss.id
             WHERE ss.id = ?"
        );
        mysqli_stmt_bind_param($chk, "i", $reset_id);
        mysqli_stmt_execute($chk);
        $row = mysqli_stmt_get_result($chk)->fetch_assoc();
        mysqli_stmt_close($chk);

        if (!$row) {
            $message = "Agent ID $reset_id দিয়ে কোনো Agent পাওয়া যায়নি।";
            $message_type = 'danger';
        } else {
            $md5new = md5($new_pass);
            $upd = mysqli_prepare($conn, "UPDATE shonu_subjects SET password = ?, status = '1' WHERE id = ?");
            mysqli_stmt_bind_param($upd, "si", $md5new, $reset_id);
            mysqli_stmt_execute($upd);
            mysqli_stmt_close($upd);

            $upd2 = mysqli_prepare($conn, "UPDATE tb_agent SET status = '1' WHERE userid = ?");
            mysqli_stmt_bind_param($upd2, "i", $reset_id);
            mysqli_stmt_execute($upd2);
            mysqli_stmt_close($upd2);

            $created_credentials = [
                'id' => $reset_id,
                'mobile' => $row['mobile'],
                'password' => $new_pass,
                'name' => '(password reset)',
            ];
            $message = "✅ Password reset হয়ে গেছে।";
            $message_type = 'success';
        }
    }
}

// ─────────────────────────────────────────────────────────────
// ACTION 3: সমস্যাযুক্ত (খালি/duplicate) Invitation Code ঠিক করো
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fix_code'])) {
    $fix_id = (int)($_POST['fix_agent_id'] ?? 0);

    if ($fix_id > 0) {
        // নতুন, নিশ্চিতভাবে unique একটা code বানাও
        do {
            $new_code = strtoupper(substr(md5(uniqid((string)mt_rand(), true)), 0, 8));
            $dup = mysqli_prepare($conn, "SELECT id FROM shonu_subjects WHERE owncode = ?");
            mysqli_stmt_bind_param($dup, "s", $new_code);
            mysqli_stmt_execute($dup);
            mysqli_stmt_store_result($dup);
            $is_dup = mysqli_stmt_num_rows($dup) > 0;
            mysqli_stmt_close($dup);
        } while ($is_dup);

        $fixupd = mysqli_prepare($conn, "UPDATE shonu_subjects SET owncode = ? WHERE id = ?");
        mysqli_stmt_bind_param($fixupd, "si", $new_code, $fix_id);
        mysqli_stmt_execute($fixupd);
        mysqli_stmt_close($fixupd);

        $message = "✅ Agent #$fix_id এর নতুন Invitation Code: $new_code";
        $message_type = 'success';
    }
}

// ─────────────────────────────────────────────────────────────
// ACTION 4: Existing Agent-এর Mobile Number পরিবর্তন করো
// ─────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_mobile'])) {
    $cm_id       = (int)($_POST['cm_agent_id'] ?? 0);
    $cm_mobile_raw = trim($_POST['new_mobile'] ?? '');
    $cm_digits   = preg_replace('/^(\+?880|\+?91|0)/', '', $cm_mobile_raw);
    $cm_mobile   = ($cm_digits !== '') ? '880' . $cm_digits : '';

    if ($cm_id <= 0 || !preg_match('/^880[0-9]{7,12}$/', $cm_mobile)) {
        $message = 'সঠিক Agent ID ও সঠিক format-এর নতুন Mobile Number দাও।';
        $message_type = 'danger';
    } else {
        // নতুন mobile আগে থেকেই অন্য কারো কিনা চেক করো
        $mchk = mysqli_prepare($conn, "SELECT id FROM shonu_subjects WHERE mobile = ? AND id != ?");
        mysqli_stmt_bind_param($mchk, "si", $cm_mobile, $cm_id);
        mysqli_stmt_execute($mchk);
        mysqli_stmt_store_result($mchk);

        if (mysqli_stmt_num_rows($mchk) > 0) {
            $message = "এই Mobile Number ($cm_mobile) আগে থেকেই অন্য কারো account-এ আছে।";
            $message_type = 'danger';
        } else {
            mysqli_stmt_close($mchk);

            $mu1 = mysqli_prepare($conn, "UPDATE shonu_subjects SET mobile = ? WHERE id = ?");
            mysqli_stmt_bind_param($mu1, "si", $cm_mobile, $cm_id);
            mysqli_stmt_execute($mu1);
            mysqli_stmt_close($mu1);

            $mu2 = mysqli_prepare($conn, "UPDATE tb_agent SET mobile = ? WHERE userid = ?");
            mysqli_stmt_bind_param($mu2, "si", $cm_mobile, $cm_id);
            mysqli_stmt_execute($mu2);
            mysqli_stmt_close($mu2);

            $message = "✅ Agent #$cm_id এর নতুন Mobile Number: $cm_mobile";
            $message_type = 'success';
        }
    }
}

// সব agent-এর list — প্রতিটার code সমস্যাযুক্ত কিনা চেক সহ
$agents = mysqli_query($conn,
    "SELECT ta.userid, ss.mobile, ta.status, ta.createdate, ss.owncode,
            (SELECT COUNT(*) FROM shonu_subjects s2 WHERE s2.owncode = ss.owncode) as code_count
     FROM tb_agent ta
     JOIN shonu_subjects ss ON ss.id = ta.userid
     ORDER BY ta.userid DESC"
);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Admin - Create Agent</title>
<link rel="stylesheet" href="vendors/mdi/css/materialdesignicons.min.css">
<link rel="stylesheet" href="vendors/base/vendor.bundle.base.css">
<link rel="stylesheet" href="css/style.css">
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@500;600;700&display=swap');
.ca-card { background:#1B1633; border:1px solid #322A5C; border-radius:14px; padding:24px; box-shadow:0 4px 20px rgba(0,0,0,.35); margin-bottom:24px; font-family:'Inter',sans-serif; }
.ca-card h5 { color:#F3F0FF; font-weight:700; }
.ca-card .form-group label { color:#9691B8; font-size:11px; text-transform:uppercase; letter-spacing:.5px; font-weight:600; }
.ca-card .form-control { background:#0E0B1A; border:1.5px solid #322A5C; color:#F3F0FF; border-radius:10px; }
.ca-card .form-control::placeholder { color:#6B6690; }
.ca-card .form-control:focus { background:#0E0B1A; border-color:#22D3EE; color:#F3F0FF; box-shadow:none; }
.ca-card .btn-primary { background:#7C3AED; border:none; font-weight:700; text-transform:uppercase; letter-spacing:.4px; font-size:12.5px; border-radius:10px; }
.ca-card .btn-warning { background:#F5C542; border:none; color:#0E0B1A; font-weight:700; text-transform:uppercase; letter-spacing:.4px; font-size:12.5px; border-radius:10px; }
.ca-card .table { color:#F3F0FF; }
.ca-card .table th { background:#0E0B1A; color:#9691B8; font-size:10.5px; text-transform:uppercase; letter-spacing:.5px; border-color:#322A5C; }
.ca-card .table td { border-color:#322A5C; vertical-align:middle; }
.ca-card .table-hover tbody tr:hover { background:#211B3D; }
.ca-card code { background:#0E0B1A; color:#22D3EE; padding:4px 8px; border-radius:6px; font-family:'IBM Plex Mono',monospace; }
.cred-box { background:#0E0B1A; border:1px solid #F5C542; color:#F3F0FF; border-radius:14px; padding:22px; margin-bottom:24px; font-family:'IBM Plex Mono',monospace; }
.cred-box .row-item { display:flex; justify-content:space-between; padding:9px 0; border-bottom:1px solid #322A5C; }
.cred-box .row-item:last-child { border-bottom:none; }
.cred-box .label { color:#9691B8; text-transform:uppercase; font-size:10.5px; letter-spacing:.5px; }
.cred-box .value { font-weight:700; font-size:15px; }
.badge-active { background:rgba(34,211,238,.14); color:#22D3EE; padding:4px 11px; border-radius:20px; font-size:11px; font-weight:700; }
.badge-inactive { background:rgba(240,89,107,.14); color:#F0596B; padding:4px 11px; border-radius:20px; font-size:11px; font-weight:700; }
</style>
</head>
<body>
<div class="container-scroller">
  <nav class="navbar col-lg-12 col-12 p-0 fixed-top d-flex flex-row">
    <div class="text-center navbar-brand-wrapper d-flex align-items-center justify-content-center">
      <a class="navbar-brand brand-logo" href="dashboard.php"><img src="images/logo.png" alt="logo"/></a>
    </div>
    <div class="navbar-menu-wrapper d-flex align-items-center justify-content-end">
      <ul class="navbar-nav navbar-nav-right">
        <li class="nav-item dropdown d-flex mr-4">
          <a class="nav-link" href="logout.php"><i class="icon-power"></i> Logout</a>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid page-body-wrapper">
    <nav class="sidebar sidebar-offcanvas" id="sidebar">
      <?php include 'compass.php'; ?>
    </nav>
    <div class="main-panel">
      <div class="content-wrapper">
        <h4 class="font-weight-bold text-dark mb-4">👤 Agent তৈরি করো (Login Credentials সহ)</h4>

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

        <?php if ($created_credentials): ?>
        <div class="cred-box">
          <div class="row-item"><span class="label">Agent ID</span><span class="value">#<?= $created_credentials['id'] ?></span></div>
          <div class="row-item"><span class="label">Mobile / Login</span><span class="value"><?= htmlspecialchars($created_credentials['mobile']) ?></span></div>
          <div class="row-item"><span class="label">Password</span><span class="value"><?= htmlspecialchars($created_credentials['password']) ?></span></div>
          <?php if (!empty($created_credentials['owncode'])): ?>
          <div class="row-item"><span class="label">Invitation Code</span><span class="value" style="color:#F5C542;"><?= htmlspecialchars($created_credentials['owncode']) ?></span></div>
          <?php endif; ?>
          <?php if (isset($created_credentials['commission_rate'])): ?>
          <div class="row-item"><span class="label">Commission Type</span><span class="value" style="color:#F0A93A;"><?= $created_credentials['commission_type'] === 'deposit' ? 'Deposit Commission' : 'GGR Commission' ?></span></div>
          <div class="row-item"><span class="label">Commission Rate</span><span class="value" style="color:#22D3EE;"><?= htmlspecialchars($created_credentials['commission_rate']) ?>% of <?= $created_credentials['commission_type'] === 'deposit' ? 'Total Deposit' : 'GGR' ?></span></div>
          <?php endif; ?>
          <div class="row-item"><span class="label">Login URL</span><span class="value">yoursite.com/agent/</span></div>
        </div>
        <p class="text-muted" style="margin-top:-16px;">⚠️ এই তথ্যটা এখনই Agent-কে copy করে দাও — পরে password আর plain-text এ দেখা যাবে না।</p>
        <?php endif; ?>

        <!-- Card 1: নতুন Agent তৈরি -->
        <div class="ca-card">
          <h5 class="mb-3">➕ নতুন Agent তৈরি করো</h5>
          <form method="POST">
            <div class="row">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Mobile Number (এটাই Login ID হবে)</label>
                  <input type="text" name="mobile" class="form-control" placeholder="যেমন: 1812345678 (880 automatic যোগ হবে)" required pattern="[0-9]{7,15}">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Password</label>
                  <input type="text" name="password" class="form-control" placeholder="Agent-কে যা দেবে" required minlength="4">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Agent Name (ঐচ্ছিক)</label>
                  <input type="text" name="agent_name" class="form-control" placeholder="যেমন: Rahim Agency">
                </div>
              </div>
            </div>
            <div class="row">
              <div class="col-md-4">
                <div class="form-group">
                  <label>শুরুতে Coin (ঐচ্ছিক)</label>
                  <input type="number" name="initial_coin" class="form-control" placeholder="0" min="0" step="0.01">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Custom Invitation Code (ঐচ্ছিক)</label>
                  <input type="text" name="custom_owncode" class="form-control" placeholder="খালি রাখলে auto-generate হবে, যেমন: AUJ5678">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Gmail (Login Verification-এর জন্য)</label>
                  <input type="email" name="email" class="form-control" placeholder="agent@gmail.com" required>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Commission Type — এই Agent কোন হিসাবে Commission পাবে</label>
                  <div style="display:flex; gap:16px; margin-top:6px;">
                    <label style="font-weight:400; display:flex; align-items:center; gap:6px;">
                      <input type="radio" name="commission_type" value="ggr" checked> GGR Commission (Bet - Win ভিত্তিক)
                    </label>
                    <label style="font-weight:400; display:flex; align-items:center; gap:6px;">
                      <input type="radio" name="commission_type" value="deposit"> Deposit Commission (Deposit Amount ভিত্তিক)
                    </label>
                  </div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>Commission Rate (%)</label>
                  <input type="number" name="commission_rate" class="form-control" placeholder="30" min="0" max="100" step="0.1" value="30">
                </div>
              </div>
            </div>
            <button type="submit" name="create_agent" value="1" class="btn btn-primary">
              <i class="mdi mdi-account-plus"></i> Agent তৈরি করো
            </button>
          </form>
        </div>

        <!-- Card 2: Password Reset -->
        <div class="ca-card">
          <h5 class="mb-3">🔑 Existing Agent-এর Password Reset করো</h5>
          <form method="POST">
            <div class="row">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Agent ID</label>
                  <input type="number" name="reset_agent_id" class="form-control" placeholder="যেমন: 17" required min="1">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>নতুন Password</label>
                  <input type="text" name="new_password" class="form-control" placeholder="নতুন password" required minlength="4">
                </div>
              </div>
              <div class="col-md-4 d-flex align-items-end">
                <button type="submit" name="reset_password" value="1" class="btn btn-warning">
                  <i class="mdi mdi-lock-reset"></i> Reset করো
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- Card 2.5: Mobile Number পরিবর্তন -->
        <div class="ca-card">
          <h5 class="mb-3">📱 Existing Agent-এর Mobile Number পরিবর্তন করো</h5>
          <form method="POST">
            <div class="row">
              <div class="col-md-4">
                <div class="form-group">
                  <label>Agent ID</label>
                  <input type="number" name="cm_agent_id" class="form-control" placeholder="যেমন: 17" required min="1">
                </div>
              </div>
              <div class="col-md-4">
                <div class="form-group">
                  <label>নতুন Mobile Number</label>
                  <input type="text" name="new_mobile" class="form-control" placeholder="যেমন: 1812345678" required>
                </div>
              </div>
              <div class="col-md-4 d-flex align-items-end">
                <button type="submit" name="change_mobile" value="1" class="btn btn-warning">
                  <i class="mdi mdi-phone-settings"></i> Mobile পরিবর্তন করো
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- Card 3: All Agents -->
        <div class="ca-card">
          <h5 class="mb-3">📋 সব Agent — Invitation Code Health Check</h5>
          <div class="table-responsive">
            <table class="table table-bordered table-hover">
              <thead class="thead-dark">
                <tr><th>Agent ID</th><th>Mobile</th><th>Invitation Code</th><th>Code Status</th><th>Status</th><th>তৈরি হয়েছে</th></tr>
              </thead>
              <tbody>
                <?php while ($row = mysqli_fetch_assoc($agents)):
                    $code_empty = empty($row['owncode']);
                    $code_dup   = !$code_empty && (int)$row['code_count'] > 1;
                    $code_ok    = !$code_empty && !$code_dup;
                ?>
                <tr>
                  <td><strong>#<?= $row['userid'] ?></strong></td>
                  <td><?= htmlspecialchars($row['mobile']) ?></td>
                  <td>
                    <code style="cursor:pointer;" title="Click to copy" onclick="navigator.clipboard.writeText('<?= htmlspecialchars($row['owncode']) ?>');this.textContent='Copied!';setTimeout(()=>{this.textContent='<?= htmlspecialchars($row['owncode']) ?>';},1200);">
                      <?= $code_empty ? '(খালি)' : htmlspecialchars($row['owncode']) ?>
                    </code>
                  </td>
                  <td>
                    <?php if ($code_ok): ?>
                      <span class="badge-active">✅ OK</span>
                    <?php else: ?>
                      <span class="badge-inactive">
                        ⚠️ <?= $code_empty ? 'খালি' : 'Duplicate ('.$row['code_count'].'x)'; ?>
                      </span>
                      <form method="POST" style="display:inline;margin-left:6px;">
                        <input type="hidden" name="fix_agent_id" value="<?= $row['userid'] ?>">
                        <button type="submit" name="fix_code" value="1" class="btn btn-sm btn-warning" style="padding:2px 10px;font-size:11px;">Fix করো</button>
                      </form>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php if ((string)$row['status'] === '1'): ?>
                      <span class="badge-active">Active</span>
                    <?php else: ?>
                      <span class="badge-inactive">Inactive</span>
                    <?php endif; ?>
                  </td>
                  <td><?= htmlspecialchars($row['createdate']) ?></td>
                </tr>
                <?php endwhile; ?>
              </tbody>
            </table>
          </div>
        </div>

      </div>
    </div>
  </div>
</div>
<script src="vendors/base/vendor.bundle.base.js"></script>
</body>
</html>
