<?php
require_once 'includes/config.php';
requireLogin();
$user = getCurrentUser();
$db   = getDB();

// Reseller or Admin  will be done
if (!isReseller()) {
    header('Location: dashboard.php'); exit;
}

$success = ''; $error = '';

// Add new user under this reseller
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_user') {
    $name     = sanitize($_POST['name'] ?? '');
    $username = sanitize($_POST['username'] ?? '');
    $phone    = sanitize($_POST['phone'] ?? '');
    $email    = sanitize($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $balance  = floatval($_POST['balance'] ?? 0);

    if (!$name || !$username || !$phone || !$password) {
        $error = 'Name, usernum, phone  password required!';
    } elseif (strlen($password) < 6) {
        $error = 'password at least  char  will be done!';
    } else {
        $check = $db->prepare("SELECT id FROM users WHERE username=? OR phone=?");
        $check->execute([$username, $phone]);
        if ($check->fetch()) {
            $error = 'This usernum or Phone Number   available!';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $db->prepare("INSERT INTO users (name,username,email,phone,password,balance,reseller_id,role,status) VALUES (?,?,?,?,?,?,?,'user','active')")
               ->execute([$name, $username, $email, $phone, $hash, $balance, $user['id']]);

            // Balance deduct from reseller if initial balance given
            if ($balance > 0) {
                if ($user['balance'] < $balance) {
                    // rollback — delete the just created user
                    $db->prepare("DELETE FROM users WHERE username=? AND phone=?")->execute([$username, $phone]);
                    $error = 'Insufficient balance! Your balance: ' . CURRENCY . number_format($user['balance'], 2);
                } else {
                    $newUserId = $db->lastInsertId();
                    $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$balance, $user['id']]);
                    $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
                       ->execute([$user['id'],'deposit',$balance,$balance,$user['balance'],$user['balance']-$balance,generateRef(),'success','Initial balance for new user: @'.$username]);
                    $success = "✅ user Successful Add done! Balance: " . CURRENCY . number_format($balance, 2) . " given done।";
                }
            } else {
                $success = "✅ user Successful Add done!";
            }
        }
    }
}

// Toggle user status
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle_user') {
    $uid = intval($_POST['uid']);
    // Only own users
    $check = $db->prepare("SELECT id FROM users WHERE id=? AND reseller_id=?");
    $check->execute([$uid, $user['id']]);
    if ($check->fetch()) {
        $db->prepare("UPDATE users SET status = CASE WHEN status='active' THEN 'suspended' ELSE 'active' END WHERE id=?")->execute([$uid]);
    }
    header('Location: reseller.php'); exit;
}

// Add balance to sub-user
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_balance') {
    $uid    = intval($_POST['uid']);
    $amount = floatval($_POST['amount']);
    $check  = $db->prepare("SELECT * FROM users WHERE id=? AND reseller_id=?");
    $check->execute([$uid, $user['id']]);
    $subUser = $check->fetch();
    if ($subUser && $amount > 0) {
        if ($user['balance'] < $amount) {
            $error = 'Insufficient balance!';
        } else {
            $db->prepare("UPDATE users SET balance = balance + ? WHERE id=?")->execute([$amount, $uid]);
            $db->prepare("UPDATE users SET balance = balance - ? WHERE id=?")->execute([$amount, $user['id']]);
            $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
               ->execute([$user['id'],'deposit',$amount,$amount,$user['balance'],$user['balance']-$amount,generateRef(),'success','Balance transfer to @'.$subUser['username']]);
            $success = "✅ " . CURRENCY . number_format($amount,2) . " Balance given done!";
        }
    }
}

// Refresh user
$user = getCurrentUser();

// Get sub-users
$subUsers = $db->prepare("SELECT * FROM users WHERE reseller_id=? ORDER BY created_at DESC");
$subUsers->execute([$user['id']]);
$users = $subUsers->fetchAll();

// Stats
$totalUsers    = count($users);
$activeUsers   = array_filter($users, function($u) { return $u['status'] === 'active'; });
$totalCommission = $db->prepare("SELECT COALESCE(SUM(commission_amount),0) FROM reseller_commissions WHERE reseller_id=? AND status='paid'");
$totalCommission->execute([$user['id']]);
$totalCommission = $totalCommission->fetchColumn();
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reseller Panel - <?= SITE_NAME ?></title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        *{margin:0;padding:0;box-sizing:border-box}
        :root{--primary:#1a3c8f;--secondary:#f5a623;--dark:#0d1f4e}
        body{font-family:'Segoe UI',sans-serif;background:#f5f7fa;padding-bottom:85px}

        .header{background:linear-gradient(135deg,var(--dark),var(--primary));padding:0 20px;position:sticky;top:0;z-index:100}
        .header-inner{display:flex;align-items:center;gap:15px;height:60px;max-width:500px;margin:0 auto}
        .back-btn{background:none;border:none;color:white;font-size:20px;cursor:pointer}
        .header-inner h2{color:white;font-size:18px;font-weight:700;flex:1}
        .add-btn-top{background:var(--secondary);color:var(--dark);border:none;padding:8px 14px;border-radius:20px;font-size:13px;font-weight:700;cursor:pointer;display:flex;align-items:center;gap:6px}

        .main{max-width:500px;margin:0 auto;padding:15px}

        /* Stats */
        .stats{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-bottom:16px}
        .stat{background:white;border-radius:14px;padding:14px;text-align:center;box-shadow:0 2px 10px rgba(0,0,0,0.05)}
        .stat h3{font-size:20px;font-weight:800;color:var(--primary)}
        .stat p{font-size:11px;color:#888;margin-top:3px}

        /* Balance Card */
        .bal-card{background:linear-gradient(135deg,var(--dark),var(--primary));border-radius:16px;padding:18px 20px;margin-bottom:16px;display:flex;align-items:center;justify-content:space-between}
        .bal-card .label{color:rgba(255,255,255,0.7);font-size:13px}
        .bal-card .amount{color:white;font-size:26px;font-weight:800;margin-top:4px}
        .deposit-btn{background:var(--secondary);color:var(--dark);border:none;padding:10px 18px;border-radius:10px;font-weight:700;font-size:13px;cursor:pointer}

        /* Alert */
        .alert{padding:12px 15px;border-radius:10px;margin-bottom:14px;font-size:14px}
        .alert-success{background:#f0fff4;color:#276749;border-left:4px solid #38a169}
        .alert-danger{background:#fff5f5;color:#e53e3e;border-left:4px solid #e53e3e}

        /* Section title */
        .sec-title{font-size:15px;font-weight:700;color:var(--primary);margin-bottom:12px;display:flex;align-items:center;justify-content:space-between}
        .sec-title button{background:var(--primary);color:white;border:none;padding:7px 14px;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;display:flex;align-items:center;gap:5px}

        /* User Cards */
        .user-card{background:white;border-radius:14px;padding:15px;margin-bottom:10px;box-shadow:0 2px 10px rgba(0,0,0,0.05)}
        .user-top{display:flex;align-items:center;gap:12px;margin-bottom:10px}
        .user-avatar{width:44px;height:44px;border-radius:12px;background:linear-gradient(135deg,var(--primary),#2856c8);display:flex;align-items:center;justify-content:center;color:white;font-size:16px;font-weight:800;flex-shrink:0}
        .user-info{flex:1;min-width:0}
        .user-info strong{display:block;font-size:14px;font-weight:700}
        .user-info span{font-size:12px;color:#888}
        .badge{display:inline-block;padding:3px 9px;border-radius:20px;font-size:11px;font-weight:700}
        .badge-active{background:#f0fff4;color:#38a169}
        .badge-suspended{background:#fff5f5;color:#e53e3e}
        .user-balance{text-align:right}
        .user-balance strong{display:block;font-size:16px;font-weight:800;color:var(--primary)}
        .user-balance span{font-size:11px;color:#888}
        .user-actions{display:flex;gap:8px}
        .btn-sm{padding:7px 14px;border:none;border-radius:8px;font-size:12px;font-weight:600;cursor:pointer;flex:1;transition:0.2s}
        .btn-add-bal{background:#f0f4ff;color:var(--primary)}
        .btn-add-bal:hover{background:var(--primary);color:white}
        .btn-toggle{background:#fff5f5;color:#e53e3e}
        .btn-toggle.active{background:#f0fff4;color:#38a169}

        /* Empty */
        .empty{text-align:center;padding:40px 20px;color:#aaa;background:white;border-radius:14px}
        .empty i{font-size:32px;display:block;margin-bottom:10px;color:#ddd}

        /* Modal */
        .modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:300;align-items:flex-end;justify-content:center}
        .modal.open{display:flex}
        .modal-box{background:white;border-radius:20px 20px 0 0;padding:24px 20px 36px;width:100%;max-width:500px;max-height:90vh;overflow-y:auto;animation:su 0.3s ease}
        @keyframes su{from{transform:translateY(100%)}to{transform:translateY(0)}}
        .modal-title{font-size:17px;font-weight:700;margin-bottom:18px;color:var(--dark);display:flex;align-items:center;gap:8px}
        .form-group{margin-bottom:14px}
        .form-group label{display:block;font-size:13px;color:#555;margin-bottom:5px;font-weight:600}
        .form-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .form-group input{width:100%;padding:12px 14px;border:2px solid #e8ecf4;border-radius:10px;font-size:14px;outline:none;transition:0.2s}
        .form-group input:focus{border-color:var(--primary)}
        .modal-btns{display:flex;gap:10px;margin-top:18px}
        .btn-submit{flex:1;padding:13px;background:linear-gradient(135deg,var(--primary),#2856c8);color:white;border:none;border-radius:10px;font-size:15px;font-weight:700;cursor:pointer}
        .btn-cancel{flex:1;padding:13px;background:#f0f0f0;color:#666;border:none;border-radius:10px;cursor:pointer}
        .balance-note{background:#fffaf0;border-radius:8px;padding:10px 12px;font-size:12px;color:#92400e;margin-top:6px}
    </style>
</head>
<body>

<div class="header">
    <div class="header-inner">
        <button class="back-btn" onclick="history.back()"><i class="fas fa-arrow-left"></i></button>
        <h2><i class="fas fa-users"></i> Reseller Panel</h2>
        <button class="add-btn-top" onclick="openAddUser()">
            <i class="fas fa-plus"></i>  User
        </button>
    </div>
</div>

<div class="main">
    <?php if ($error): ?>
    <div class="alert alert-danger"><i class="fas fa-times-circle"></i> <?= $error ?></div>
    <?php endif; ?>
    <?php if ($success): ?>
    <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
    <?php endif; ?>

    <!-- Balance Card -->
    <div class="bal-card">
        <div>
            <div class="label">your Balance</div>
            <div class="amount"><?= CURRENCY ?> <?= number_format($user['balance'],2) ?></div>
        </div>
        <button class="deposit-btn" onclick="location.href='deposit.php'">+ Add </button>
    </div>

    <!-- Stats -->
    <div class="stats">
        <div class="stat">
            <h3><?= $totalUsers ?></h3>
            <p>Total User</p>
        </div>
        <div class="stat">
            <h3><?= count($activeUsers) ?></h3>
            <p>Active User</p>
        </div>
        <div class="stat">
            <h3><?= CURRENCY ?><?= number_format($totalCommission,0) ?></h3>
            <p>Commission</p>
        </div>
    </div>

    <!-- User List -->
    <div class="sec-title">
        <span><i class="fas fa-users"></i> my Users (<?= $totalUsers ?>)</span>
        <button onclick="openAddUser()"><i class="fas fa-plus"></i>  User Add</button>
    </div>

    <?php if (empty($users)): ?>
    <div class="empty">
        <i class="fas fa-users"></i>
         any User Add not done<br>
        <small>after " User" Click button </small>
    </div>
    <?php else: ?>
    <?php foreach ($users as $u): ?>
    <div class="user-card">
        <div class="user-top">
            <div class="user-avatar"><?= strtoupper(substr($u['name'],0,1)) ?></div>
            <div class="user-info">
                <strong><?= htmlspecialchars($u['name']) ?></strong>
                <span>@<?= $u['username'] ?> &bull; <?= $u['phone'] ?></span>
            </div>
            <div class="user-balance">
                <strong><?= CURRENCY ?><?= number_format($u['balance'],2) ?></strong>
                <span><span class="badge badge-<?= $u['status'] === 'active' ? 'active' : 'suspended' ?>"><?= $u['status'] === 'active' ? 'Active' : 'Suspended' ?></span></span>
            </div>
        </div>
        <div class="user-actions">
            <button class="btn-sm btn-add-bal" onclick="openAddBalance(<?= $u['id'] ?>,'<?= htmlspecialchars($u['name']) ?>')">
                <i class="fas fa-plus"></i> Balance day
            </button>
            <form method="POST" style="flex:1">
                <input type="hidden" name="action" value="toggle_user">
                <input type="hidden" name="uid" value="<?= $u['id'] ?>">
                <button type="submit" class="btn-sm btn-toggle <?= $u['status']==='active'?'':'active' ?>" style="width:100%">
                    <i class="fas fa-<?= $u['status']==='active'?'ban':'check' ?>"></i>
                    <?= $u['status']==='active'?'Suspend':'Activate' ?>
                </button>
            </form>
        </div>
    </div>
    <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Add User Modal -->
<div class="modal" id="addUserModal">
    <div class="modal-box">
        <div class="modal-title"><i class="fas fa-user-plus" style="color:var(--primary)"></i>  User Add </div>
        <form method="POST">
            <input type="hidden" name="action" value="add_user">
            <div class="form-row">
                <div class="form-group">
                    <label> Name *</label>
                    <input type="text" name="name" placeholder="your Name" required>
                </div>
                <div class="form-group">
                    <label>usernum *</label>
                    <input type="text" name="username" placeholder="username" required>
                </div>
            </div>
            <div class="form-group">
                <label>Phone Number *</label>
                <input type="text" name="phone" placeholder="01XXXXXXXXX" required>
            </div>
            <div class="form-group">
                <label>Email (Optional)</label>
                <input type="email" name="email" placeholder="email@example.com">
            </div>
            <div class="form-group">
                <label>password *</label>
                <input type="text" name="password" placeholder="at least  char" required>
            </div>
            <div class="form-group">
                <label>Initial Balance ()</label>
                <input type="number" name="balance" placeholder="0" min="0" step="0.01" value="0">
                <div class="balance-note">
                    💡 From your balance will be deducted। current: <strong><?= CURRENCY ?><?= number_format($user['balance'],2) ?></strong>
                </div>
            </div>
            <div class="modal-btns">
                <button type="submit" class="btn-submit"><i class="fas fa-user-plus"></i> User Add </button>
                <button type="button" class="btn-cancel" onclick="closeModal('addUserModal')">Cancelled</button>
            </div>
        </form>
    </div>
</div>

<!-- Add Balance Modal -->
<div class="modal" id="addBalModal">
    <div class="modal-box">
        <div class="modal-title"><i class="fas fa-plus-circle" style="color:#38a169"></i> Balance day</div>
        <form method="POST">
            <input type="hidden" name="action" value="add_balance">
            <input type="hidden" name="uid" id="balUid">
            <div class="form-group">
                <label>User</label>
                <input type="text" id="balName" readonly style="background:#f8fafc;color:#666">
            </div>
            <div class="form-group">
                <label>Amount () *</label>
                <input type="number" name="amount" placeholder="0.00" min="1" step="0.01" required>
                <div class="balance-note">
                    Your balance: <strong><?= CURRENCY ?><?= number_format($user['balance'],2) ?></strong>
                </div>
            </div>
            <div class="modal-btns">
                <button type="submit" class="btn-submit"><i class="fas fa-paper-plane"></i> Send</button>
                <button type="button" class="btn-cancel" onclick="closeModal('addBalModal')">Cancelled</button>
            </div>
        </form>
    </div>
</div>

<script>
function openAddUser() {
    document.getElementById('addUserModal').classList.add('open');
}
function openAddBalance(uid, name) {
    document.getElementById('balUid').value = uid;
    document.getElementById('balName').value = name;
    document.getElementById('addBalModal').classList.add('open');
}
function closeModal(id) {
    document.getElementById(id).classList.remove('open');
}
// Close on outside click
document.querySelectorAll('.modal').forEach(m => {
    m.addEventListener('click', e => { if(e.target===m) m.classList.remove('open'); });
});
</script>
<?php include 'includes/bottom_nav.php'; ?>
<script>document.addEventListener("DOMContentLoaded",function(){ if(window.pageReady) window.pageReady(); });</script>
</body>
</html>
