<?php
session_start();
if (!isset($_SESSION['unohs'])) {
    header("Location: index.php");
    exit();
}
include "conn.php";

/* ══════════════════════════════════════════════════════════
   নতুন যোগ — tb_agent টেবিলে commission_rate কলাম না থাকলে
   নিজে থেকেই তৈরি হয়ে যাবে
   ══════════════════════════════════════════════════════════ */
$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'");
}

// remove_agent.php থেকে ফিরে আসার পর success/error message দেখানো
$message = '';
if (isset($_GET['msg'])) {
    switch ($_GET['msg']) {
        case 'enabled':  $message = '✅ Agent সফলভাবে Enable করা হয়েছে।'; break;
        case 'disabled': $message = '✅ Agent সফলভাবে Disable/Remove করা হয়েছে — এখন সে আর Login করতে পারবে না।'; break;
        case 'wallet_saved': $message = '✅ Agent-এর Nagad/bKash Number ও Commission Rate সংরক্ষণ হয়েছে।'; break;
        case 'coin_removed': $message = '✅ Agent-এর Coin balance সফলভাবে কমানো হয়েছে।'; break;
        case 'coin_added': $message = '✅ Agent-এর Coin balance সফলভাবে বাড়ানো হয়েছে।'; break;
        case 'limit_exceeded': $message = '❌ একবারে এত বেশি Coin Add করা যাবে না — Per-Transaction Limit ছাড়িয়ে গেছে।'; break;
        case 'insufficient':  $message = '❌ Agent-এর balance-এ এত Coin নেই — এত পরিমাণ কমানো যাবে না।'; break;
        case 'error':    $message = '❌ কিছু একটা সমস্যা হয়েছে, আবার চেষ্টা করুন।'; break;
        case 'invalid':  $message = '❌ ভুল request।'; break;
    }
}

// সব Agent-এর তালিকা আনা
// ✅ নতুন যোগ — Master Admin হলে সবার Agent দেখাবে, নাহলে শুধু নিজের
$myAdminId = $_SESSION['unohs'];
$myAdminRow = $conn->query("SELECT is_master FROM nirvahaka_shonu WHERE unohs = '$myAdminId'")->fetch_assoc();
$isMasterAdmin = $myAdminRow && intval($myAdminRow['is_master']) === 1;

$isolationWhere = $isMasterAdmin ? "" : "WHERE a.created_by_admin = '$myAdminId'";

$agents = [];
$result = $conn->query("
    SELECT a.id, a.userid, a.mobile, a.type, a.salary, a.salarypercent,
           a.minrecharge, a.createdate, a.status, a.contact_mobile,
           a.nagad_number, a.bkash_number, a.commission_rate, a.commission_type,
           s.owncode, k.motta AS coin_balance
    FROM tb_agent a
    LEFT JOIN shonu_subjects s ON s.id = a.userid
    LEFT JOIN shonu_kaichila k ON k.balakedara = a.userid
    $isolationWhere
    ORDER BY a.status DESC, a.createdate DESC
");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $agents[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Agents - RAJ365 Admin</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="admin-gold-theme.css">
    <style>
        body { background: #0A0A0A; padding: 20px; }
        .agent-card {
            background: #171512;
            border: 1px solid rgba(212,175,55,.25);
            border-radius: 14px;
            padding: 16px 18px;
            margin-bottom: 14px;
        }
        .agent-card.disabled { opacity: .55; border-color: rgba(220,38,38,.4); }
        .status-badge {
            font-size: 11px;
            font-weight: 700;
            padding: 3px 10px;
            border-radius: 999px;
            letter-spacing: .3px;
        }
        .status-active { background: rgba(31,185,121,.15); color: #1FB979; }
        .status-disabled { background: rgba(220,38,38,.15); color: #E8544A; }
        .agent-meta { color: #8A8270; font-size: 12.5px; }
        .agent-name { color: #F5EFDC; font-weight: 700; font-size: 15px; }
    </style>
</head>
<body>
<div class="container" style="max-width:720px;">
    <h3 style="color:#D4AF37; margin-bottom:20px;">🧑‍💼 Manage Agents</h3>

    <?php if ($message): ?>
        <div class="alert" style="background:#171512; border:1px solid #D4AF37; color:#F5EFDC;">
            <?= htmlspecialchars($message) ?>
        </div>
    <?php endif; ?>

    <?php if (empty($agents)): ?>
        <p style="color:#8A8270;">কোনো Agent পাওয়া যায়নি।</p>
    <?php else: ?>
        <?php foreach ($agents as $agent): ?>
            <?php $isActive = intval($agent['status']) === 1; ?>
            <div class="agent-card <?= $isActive ? '' : 'disabled' ?>">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <div class="agent-name">
                            Agent #<?= htmlspecialchars($agent['id']) ?>
                            <span class="status-badge <?= $isActive ? 'status-active' : 'status-disabled' ?>">
                                <?= $isActive ? 'ACTIVE' : 'DISABLED' ?>
                            </span>
                        </div>
                        <div style="color:#D4AF37; font-weight:700; font-size:15px; margin:4px 0;">
                            🪙 Coin Balance: <?= number_format((float)($agent['coin_balance'] ?? 0), 2) ?>
                        </div>
                        <form method="POST" action="remove_agent_coin.php" style="display:flex; gap:6px; align-items:center; margin:6px 0;"
                              onsubmit="return confirm('এই Agent-এর balance থেকে সত্যিই এই পরিমাণ Coin কমাতে চান?');">
                            <input type="hidden" name="agent_userid" value="<?= htmlspecialchars($agent['userid']) ?>">
                            <input type="number" name="remove_amount" min="0.01" step="0.01"
                                   max="<?= htmlspecialchars($agent['coin_balance'] ?? 0) ?>"
                                   placeholder="কত Coin কমাবে"
                                   style="width:130px; padding:4px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12.5px;"
                                   required>
                            <button type="submit" class="btn btn-sm" style="background:#B45309; color:#fff; border-radius:8px; font-weight:600; font-size:12px;">
                                Coin Remove
                            </button>
                        </form>
                        <form method="POST" action="add_agent_coin.php" style="display:flex; gap:6px; align-items:center; margin:6px 0;"
                              onsubmit="return confirm('এই Agent-এর balance-এ সত্যিই এই পরিমাণ Coin যোগ করতে চান?');">
                            <input type="hidden" name="agent_userid" value="<?= htmlspecialchars($agent['userid']) ?>">
                            <input type="number" name="add_amount" min="0.01" step="0.01" max="100000"
                                   placeholder="কত Coin দেবে"
                                   style="width:130px; padding:4px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12.5px;"
                                   required>
                            <button type="submit" class="btn btn-sm" style="background:#1FB979; color:#032B1B; border-radius:8px; font-weight:600; font-size:12px;">
                                Coin Add
                            </button>
                        </form>
                        <div class="agent-meta">
                            🆔 UID: <?= htmlspecialchars($agent['userid']) ?>
                            &nbsp;|&nbsp;
                            📱 Mobile: <?= htmlspecialchars($agent['mobile'] ?: 'N/A') ?>
                            <?php if (!empty($agent['contact_mobile'])): ?>
                                &nbsp;|&nbsp; ☎ Contact: <?= htmlspecialchars($agent['contact_mobile']) ?>
                            <?php endif; ?>
                        </div>
                        <form method="POST" action="update_agent_wallet.php" style="display:flex; gap:6px; margin-top:8px; flex-wrap:wrap;">
                            <input type="hidden" name="agent_id" value="<?= htmlspecialchars($agent['id']) ?>">
                            <input type="text" name="nagad_number" placeholder="Nagad Number"
                                   value="<?= htmlspecialchars($agent['nagad_number'] ?? '') ?>"
                                   style="width:150px; padding:5px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12px;">
                            <input type="text" name="bkash_number" placeholder="bKash Number"
                                   value="<?= htmlspecialchars($agent['bkash_number'] ?? '') ?>"
                                   style="width:150px; padding:5px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12px;">
                            <input type="number" name="commission_rate" placeholder="Commission %" min="0" max="100" step="0.1"
                                   value="<?= htmlspecialchars($agent['commission_rate'] ?? 30) ?>"
                                   style="width:120px; padding:5px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12px;">
                            <select name="commission_type" style="width:150px; padding:5px 8px; border-radius:6px; border:1px solid #3A3226; background:#0A0A0A; color:#F5EFDC; font-size:12px;">
                                <option value="ggr" <?= ($agent['commission_type'] ?? 'ggr') === 'ggr' ? 'selected' : '' ?>>GGR Commission</option>
                                <option value="deposit" <?= ($agent['commission_type'] ?? 'ggr') === 'deposit' ? 'selected' : '' ?>>Deposit Commission</option>
                            </select>
                            <button type="submit" class="btn btn-sm" style="background:#D4AF37; color:#1A1400; font-weight:600;">Save</button>
                        </form>
                        <div class="agent-meta">
                            🔑 Owncode: <?= htmlspecialchars($agent['owncode'] ?: 'N/A') ?>
                            &nbsp;|&nbsp; Commission: <span style="color:#22D3EE; font-weight:700;"><?= htmlspecialchars($agent['commission_rate'] ?? 30) ?>% (<?= ($agent['commission_type'] ?? 'ggr') === 'deposit' ? 'Deposit' : 'GGR' ?>)</span>
                            &nbsp;|&nbsp; Type: <?= htmlspecialchars($agent['type']) ?>
                            &nbsp;|&nbsp; যোগদান: <?= htmlspecialchars($agent['createdate']) ?>
                        </div>
                    </div>
                    <!-- এই form এখন remove_agent.php (আলাদা action-file) কে call করে -->
                    <form method="POST" action="remove_agent.php" onsubmit="return confirm('<?= $isActive ? 'এই Agent-কে Disable/Remove করতে চান? সে আর Login করতে পারবে না।' : 'এই Agent-কে আবার Enable করতে চান?' ?>');">
                        <input type="hidden" name="agent_id" value="<?= htmlspecialchars($agent['id']) ?>">
                        <input type="hidden" name="new_status" value="<?= $isActive ? 0 : 1 ?>">
                        <?php if ($isActive): ?>
                            <button type="submit" class="btn btn-sm" style="background:#E8544A; color:#fff; border-radius:8px; font-weight:600;">
                                Remove
                            </button>
                        <?php else: ?>
                            <button type="submit" class="btn btn-sm" style="background:#1FB979; color:#fff; border-radius:8px; font-weight:600;">
                                Enable
                            </button>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <a href="dashboard.php" style="color:#D4AF37;">← Dashboard-এ ফিরে যান</a>
</div>
</body>
</html>
