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

// Create service access table
try { $db->exec("CREATE TABLE IF NOT EXISTS user_service_access (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, service VARCHAR(30) NOT NULL, is_enabled TINYINT(1) DEFAULT 1, UNIQUE KEY uq_user_svc (user_id, service))"); } catch(Exception $e) {}

$msg = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $id     = intval($_POST['user_id'] ?? 0);

    if ($action === 'toggle_status') {
        $db->prepare("UPDATE users SET status = CASE WHEN status='active' THEN 'suspended' ELSE 'active' END WHERE id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Status updated!'];

    } elseif ($action === 'add_balance') {
        $amount = floatval($_POST['amount']);
        $note   = sanitize($_POST['note'] ?? 'Admin deposit');
        $u = $db->prepare("SELECT * FROM users WHERE id=?"); $u->execute([$id]); $u=$u->fetch();
        if($u && $amount > 0) {
            $db->prepare("UPDATE users SET balance=balance+? WHERE id=?")->execute([$amount,$id]);
            $nb = $u['balance'] + $amount;
            $db->prepare("INSERT INTO transactions (user_id,type,amount,charge,net_amount,balance_before,balance_after,reference,status,note) VALUES (?,?,?,0,?,?,?,?,?,?)")
               ->execute([$id,'deposit',$amount,$amount,$u['balance'],$nb,generateRef(),'success',$note]);
            $msg = ['ok'=>true,'text'=>"৳".number_format($amount,2)." added!"];
        }

    } elseif ($action === 'edit_user') {
        $name   = sanitize($_POST['name'] ?? '');
        $phone  = sanitize($_POST['phone'] ?? '');
        $email  = sanitize($_POST['email'] ?? '');
        $role   = sanitize($_POST['role'] ?? 'user');
        $status = sanitize($_POST['status'] ?? 'active');
        $pkg    = intval($_POST['package_id'] ?? 1);
        $balance= floatval($_POST['balance'] ?? 0);
        $due    = floatval($_POST['due_balance'] ?? 0);
        $db->prepare("UPDATE users SET name=?,phone=?,email=?,role=?,status=?,package_id=?,balance=?,due_balance=? WHERE id=?")
           ->execute([$name,$phone,$email,$role,$status,$pkg,$balance,$due,$id]);
        if (!empty($_POST['new_password'])) {
            $db->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($_POST['new_password'],PASSWORD_DEFAULT),$id]);
        }
        $msg = ['ok'=>true,'text'=>'User updated!'];

    } elseif ($action === 'save_services') {
        $svcs = ['topup','drive','international','cards','manual_drive','mbanking','deposit','bill_pay'];
        foreach($svcs as $s) {
            $on = isset($_POST['svc_'.$s]) ? 1 : 0;
            $db->prepare("INSERT INTO user_service_access (user_id,service,is_enabled) VALUES (?,?,?) ON DUPLICATE KEY UPDATE is_enabled=?")->execute([$id,$s,$on,$on]);
        }
        $msg = ['ok'=>true,'text'=>'Services updated!'];
    }

    header('Location: users.php?msg='.urlencode($msg['text']??'').($id?'&open='.$id:''));
    exit;
}

// Messages
$flashMsg = $_GET['msg'] ?? null;
$openUserId = intval($_GET['open'] ?? 0);

// Filters
$search = sanitize($_GET['search'] ?? '');
$role   = sanitize($_GET['role']   ?? '');
$status = sanitize($_GET['status'] ?? '');
$where  = "WHERE u.role != 'admin'";
$params = [];
if ($search) { $where .= " AND (u.name LIKE ? OR u.username LIKE ? OR u.phone LIKE ?)"; $params=array_merge($params,["%$search%","%$search%","%$search%"]); }
if ($role)   { $where .= " AND u.role=?";   $params[]=$role; }
if ($status) { $where .= " AND u.status=?"; $params[]=$status; }

$users = $db->prepare("SELECT u.*, p.name as pkg_name FROM users u LEFT JOIN user_packages p ON u.package_id=p.id $where ORDER BY u.created_at DESC");
$users->execute($params); $users=$users->fetchAll();

// Packages list
$packages = $db->query("SELECT id,name,color FROM user_packages WHERE is_active=1 ORDER BY id")->fetchAll();

// Service access map
$svcRows = $db->query("SELECT user_id,service,is_enabled FROM user_service_access")->fetchAll();
$svcMap  = [];
foreach($svcRows as $r) $svcMap[$r['user_id']][$r['service']] = $r['is_enabled'];
$svcDefs = ['topup'=>'📱 Topup','drive'=>'⚡ Drive','international'=>'🌍 Intl','cards'=>'🎴 Cards','manual_drive'=>'📦 Manual Drive','mbanking'=>'🏦 M.Banking','deposit'=>'💰 Deposit','bill_pay'=>'🧾 Bill Pay'];

// Stats
$totalUsers   = $db->query("SELECT COUNT(*) FROM users WHERE role!='admin'")->fetchColumn();
$activeUsers  = $db->query("SELECT COUNT(*) FROM users WHERE role!='admin' AND status='active'")->fetchColumn();
$totalBalance = $db->query("SELECT COALESCE(SUM(balance),0) FROM users WHERE role!='admin'")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Users — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
/* Stats */
.stat-row{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:18px}
.stat-box{background:white;border-radius:14px;padding:16px;text-align:center;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
.stat-val{font-size:22px;font-weight:800;color:var(--primary)}
.stat-lbl{font-size:11px;color:#aaa;margin-top:3px;font-weight:600;text-transform:uppercase}

/* Filter */
.filter-bar{background:white;border-radius:14px;padding:14px 16px;margin-bottom:16px;display:flex;gap:8px;flex-wrap:wrap;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
.filter-bar input,.filter-bar select{padding:9px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;font-family:inherit}
.filter-bar input{flex:1;min-width:160px}
.filter-btn{padding:9px 16px;background:var(--primary);color:white;border:none;border-radius:10px;font-size:13px;font-weight:700;cursor:pointer;white-space:nowrap}

/* Table */
.tbl-wrap{background:white;border-radius:14px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,0.05)}
table{width:100%;border-collapse:collapse}
th{padding:11px 14px;font-size:11px;font-weight:700;color:#888;text-transform:uppercase;letter-spacing:0.4px;border-bottom:2px solid #f0f0f0;background:#fafbfc;text-align:left}
td{padding:12px 14px;border-bottom:1px solid #f5f5f5;font-size:13px;vertical-align:middle}
tr:last-child td{border:none}
tr:hover td{background:#fafbff;cursor:pointer}
.uname{font-weight:700;color:#1a1a2e}
.usub{font-size:11px;color:#aaa;margin-top:2px}
.badge{font-size:10px;font-weight:700;padding:3px 9px;border-radius:20px}
.badge-active,.badge-user{background:#f0fff4;color:#276749}
.badge-suspended{background:#fff5f5;color:#e53e3e}
.badge-pending{background:#fffbeb;color:#d69e2e}
.badge-reseller{background:#ebf8ff;color:#2b6cb0}
.btn-sm{padding:6px 10px;border:none;border-radius:8px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:4px}
.btn-blue{background:#ebf8ff;color:#2b6cb0}
.btn-green{background:#f0fff4;color:#276749}
.btn-red{background:#fff5f5;color:#e53e3e}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px;display:flex;align-items:center;gap:8px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}

/* Side Panel */
.panel-ov{position:fixed;inset:0;background:rgba(0,0,0,0);z-index:998;display:none;transition:background 0.3s}
.panel-ov.show{display:block;background:rgba(0,0,0,0.45)}
.side-panel{position:fixed;top:0;right:-520px;width:100%;max-width:500px;height:100%;background:white;z-index:999;overflow-y:auto;transition:right 0.35s cubic-bezier(0.4,0,0.2,1);box-shadow:-4px 0 20px rgba(0,0,0,0.12)}
.side-panel.open{right:0}
.sp-hdr{background:linear-gradient(135deg,#0d1f4e,#1a3c8f);padding:20px;display:flex;align-items:center;gap:12px;position:sticky;top:0;z-index:10}
.sp-avatar{width:48px;height:48px;border-radius:14px;background:rgba(255,255,255,0.2);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0}
.sp-name{color:white;font-size:16px;font-weight:800}
.sp-sub{color:rgba(255,255,255,0.6);font-size:12px;margin-top:2px}
.sp-close{margin-left:auto;background:rgba(255,255,255,0.15);border:none;color:white;width:34px;height:34px;border-radius:50%;font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.sp-body{padding:0}

/* Tabs */
.sp-tabs{display:flex;background:#f8fafc;border-bottom:2px solid #f0f0f0;overflow-x:auto}
.sp-tab{padding:12px 16px;font-size:12px;font-weight:700;color:#aaa;cursor:pointer;white-space:nowrap;border-bottom:2px solid transparent;margin-bottom:-2px;transition:0.2s}
.sp-tab.active{color:var(--primary);border-bottom-color:var(--primary);background:white}
.sp-pane{display:none;padding:18px}
.sp-pane.active{display:block}

/* Form elements in panel */
.pfg{margin-bottom:12px}
.pfg label{display:block;font-size:11px;font-weight:700;color:#888;text-transform:uppercase;margin-bottom:4px}
.pfg input,.pfg select{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;font-family:inherit}
.pfg input:focus,.pfg select:focus{border-color:var(--primary)}
.pfrow2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.save-btn{width:100%;padding:12px;background:var(--primary);color:white;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;margin-top:4px}
.save-btn:hover{background:#2856c8}
.sep{font-size:11px;font-weight:800;color:#888;text-transform:uppercase;border-bottom:1px solid #f0f0f0;padding-bottom:6px;margin:14px 0 10px}

/* Service toggles in panel */
.svc-tog-row{display:flex;align-items:center;justify-content:space-between;padding:10px 12px;border-radius:10px;border:2px solid #f0f0f0;background:#fafbfc;margin-bottom:8px;transition:0.2s}
.svc-tog-row.on{border-color:#c6f6d5;background:#f0fff4}
.svc-tog-row.off{border-color:#fed7d7;background:#fff5f5}
.tog-sw{position:relative;width:44px;height:24px;flex-shrink:0}
.tog-sw input{opacity:0;position:absolute;inset:0;cursor:pointer;z-index:2;margin:0}
.tog-track{width:44px;height:24px;border-radius:12px;transition:0.3s;position:relative}
.tog-track.on{background:#38a169}.tog-track.off{background:#ddd}
.tog-thumb{position:absolute;top:3px;width:18px;height:18px;border-radius:50%;background:white;transition:0.3s;box-shadow:0 1px 4px rgba(0,0,0,0.2)}
.tog-track.on .tog-thumb{left:23px}.tog-track.off .tog-thumb{left:3px}

/* Transaction list in panel */
.txn-item-sm{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:10px;background:#fafbfc;border:1px solid #f0f0f0;margin-bottom:8px}
.txn-ic-sm{width:34px;height:34px;border-radius:9px;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0}
.txn-ic-sm.success{background:#f0fff4;color:#38a169}
.txn-ic-sm.pending{background:#fffbeb;color:#d69e2e}
.txn-ic-sm.failed{background:#fff5f5;color:#e53e3e}
.info-grid{display:grid;grid-template-columns:1fr 1fr;gap:8px}
.info-box{background:#f8fafc;border-radius:10px;padding:10px 12px;border:1px solid #f0f0f0}
.info-lbl{font-size:10px;color:#aaa;font-weight:700;text-transform:uppercase;margin-bottom:3px}
.info-val{font-size:13px;font-weight:800;color:#1a1a2e}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">👥 User Management</span>
    </div>
    <div class="topbar-right">
        <span style="font-size:13px;color:#666"><?= count($users) ?> users</span>
    </div>
</div>
<div class="content">

<?php if($flashMsg): ?><div class="alert alert-ok"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($flashMsg) ?></div><?php endif; ?>

<!-- Stats -->
<div class="stat-row">
    <div class="stat-box"><div class="stat-val"><?= $totalUsers ?></div><div class="stat-lbl">Total Users</div></div>
    <div class="stat-box"><div class="stat-val"><?= $activeUsers ?></div><div class="stat-lbl">Active</div></div>
    <div class="stat-box"><div class="stat-val"><?= CURRENCY ?><?= number_format($totalBalance,0) ?></div><div class="stat-lbl">Total Balance</div></div>
</div>

<!-- Filters -->
<form method="GET" class="filter-bar">
    <input type="text" name="search" placeholder="Name / Username / Phone" value="<?= htmlspecialchars($search) ?>">
    <select name="role">
        <option value="">All Roles</option>
        <option value="user" <?= $role==='user'?'selected':'' ?>>User</option>
        <option value="reseller" <?= $role==='reseller'?'selected':'' ?>>Reseller</option>
    </select>
    <select name="status">
        <option value="">All Status</option>
        <option value="active" <?= $status==='active'?'selected':'' ?>>Active</option>
        <option value="suspended" <?= $status==='suspended'?'selected':'' ?>>Suspended</option>
        <option value="pending" <?= $status==='pending'?'selected':'' ?>>Pending</option>
    </select>
    <button type="submit" class="filter-btn"><i class="fas fa-search"></i> Filter</button>
</form>

<!-- Table -->
<div class="tbl-wrap">
<table>
    <thead>
        <tr><th>#</th><th>User</th><th>Phone</th><th>Balance</th><th>Package</th><th>Role</th><th>Status</th><th>Joined</th></tr>
    </thead>
    <tbody>
    <?php foreach($users as $u): ?>
    <tr onclick="openPanel(<?= $u['id'] ?>)">
        <td style="color:#ccc;font-size:11px"><?= $u['id'] ?></td>
        <td><div class="uname"><?= htmlspecialchars($u['name']) ?></div><div class="usub">@<?= $u['username'] ?></div></td>
        <td style="font-family:monospace;font-size:12px"><?= $u['phone'] ?></td>
        <td><strong style="color:var(--primary)"><?= CURRENCY ?><?= number_format($u['balance'],2) ?></strong></td>
        <td><span style="font-size:11px;background:#f0f4ff;color:var(--primary);padding:2px 8px;border-radius:20px;font-weight:700"><?= htmlspecialchars($u['pkg_name']??'Basic') ?></span></td>
        <td><span class="badge badge-<?= $u['role'] ?>"><?= ucfirst($u['role']) ?></span></td>
        <td><span class="badge badge-<?= $u['status'] ?>"><?= ucfirst($u['status']) ?></span></td>
        <td style="font-size:11px;color:#aaa"><?= date('d M y',strtotime($u['created_at'])) ?></td>
    </tr>
    <?php endforeach; ?>
    <?php if(empty($users)): ?><tr><td colspan="8" style="text-align:center;padding:30px;color:#ccc">No users found</td></tr><?php endif; ?>
    </tbody>
</table>
</div>

</div></div>

<!-- Overlay -->
<div class="panel-ov" id="panelOv" onclick="closePanel()"></div>

<!-- Side Panel -->
<div class="side-panel" id="sidePanel">
    <div class="sp-hdr">
        <div class="sp-avatar" id="spAvatar">👤</div>
        <div>
            <div class="sp-name" id="spName">—</div>
            <div class="sp-sub" id="spSub">—</div>
        </div>
        <button class="sp-close" onclick="closePanel()">✕</button>
    </div>
    <!-- Tabs -->
    <div class="sp-tabs">
        <div class="sp-tab active" onclick="switchTab(0)">📋 Info</div>
        <div class="sp-tab" onclick="switchTab(1)">✏️ Edit</div>
        <div class="sp-tab" onclick="switchTab(2)">💰 Balance</div>
        <div class="sp-tab" onclick="switchTab(3)">⚙️ Services</div>
        <div class="sp-tab" onclick="switchTab(4)">📱 Devices</div>
        <div class="sp-tab" onclick="switchTab(5)">📜 Transactions</div>
    </div>

    <!-- TAB 0: Info -->
    <div class="sp-pane active" id="spTab0">
        <div class="info-grid" id="spInfoGrid">
            <div class="info-box"><div class="info-lbl">Balance</div><div class="info-val" id="si_balance">—</div></div>
            <div class="info-box"><div class="info-lbl">Due</div><div class="info-val" id="si_due">—</div></div>
            <div class="info-box"><div class="info-lbl">Phone</div><div class="info-val" id="si_phone">—</div></div>
            <div class="info-box"><div class="info-lbl">Email</div><div class="info-val" id="si_email">—</div></div>
            <div class="info-box"><div class="info-lbl">Role</div><div class="info-val" id="si_role">—</div></div>
            <div class="info-box"><div class="info-lbl">Status</div><div class="info-val" id="si_status">—</div></div>
            <div class="info-box"><div class="info-lbl">Package</div><div class="info-val" id="si_pkg">—</div></div>
            <div class="info-box"><div class="info-lbl">Joined</div><div class="info-val" id="si_joined">—</div></div>
        </div>
        <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap" id="spQuickActions"></div>
    </div>

    <!-- TAB 1: Edit -->
    <div class="sp-pane" id="spTab1">
        <form method="POST" id="editForm">
            <input type="hidden" name="action" value="edit_user">
            <input type="hidden" name="user_id" id="ef_uid">
            <div class="sep">Basic Info</div>
            <div class="pfrow2">
                <div class="pfg"><label>Full Name</label><input name="name" id="ef_name" required></div>
                <div class="pfg"><label>Phone</label><input name="phone" id="ef_phone" required></div>
            </div>
            <div class="pfg"><label>Email</label><input name="email" id="ef_email" type="email"></div>
            <div class="sep">Account</div>
            <div class="pfrow2">
                <div class="pfg"><label>Role</label>
                    <select name="role" id="ef_role">
                        <option value="user">User</option>
                        <option value="reseller">Reseller</option>
                    </select>
                </div>
                <div class="pfg"><label>Status</label>
                    <select name="status" id="ef_status">
                        <option value="active">✅ Active</option>
                        <option value="suspended">❌ Suspended</option>
                        <option value="pending">⏳ Pending</option>
                    </select>
                </div>
            </div>
            <div class="pfg"><label>Package</label>
                <select name="package_id" id="ef_pkg">
                    <?php foreach($packages as $p): ?>
                    <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="sep">Balance</div>
            <div class="pfrow2">
                <div class="pfg"><label>Balance (৳)</label><input type="number" step="0.01" name="balance" id="ef_balance"></div>
                <div class="pfg"><label>Due Balance (৳)</label><input type="number" step="0.01" name="due_balance" id="ef_due"></div>
            </div>
            <div class="sep">Change Password</div>
            <div class="pfg"><label>New Password <span style="color:#aaa;font-weight:400">(leave blank to keep)</span></label><input type="password" name="new_password" placeholder="Min 6 characters"></div>
            <button type="submit" class="save-btn"><i class="fas fa-save"></i> Save Changes</button>
        </form>
    </div>

    <!-- TAB 2: Add Balance -->
    <div class="sp-pane" id="spTab2">
        <form method="POST">
            <input type="hidden" name="action" value="add_balance">
            <input type="hidden" name="user_id" id="bal_uid">
            <div class="pfg"><label>Amount (৳)</label><input type="number" name="amount" step="0.01" min="1" required placeholder="Enter amount"></div>
            <div class="pfg"><label>Note</label><input type="text" name="note" placeholder="Reason..." value="Admin deposit"></div>
            <div style="display:grid;grid-template-columns:repeat(4,1fr);gap:6px;margin-bottom:12px">
                <?php foreach([100,200,500,1000] as $q): ?>
                <button type="button" onclick="document.querySelector('[name=amount]').value=<?= $q ?>" style="padding:8px;background:#f0f4ff;color:var(--primary);border:none;border-radius:8px;font-size:13px;font-weight:700;cursor:pointer">+<?= $q ?></button>
                <?php endforeach; ?>
            </div>
            <button type="submit" class="save-btn" style="background:#38a169"><i class="fas fa-plus-circle"></i> Add Balance</button>
        </form>
    </div>

    <!-- TAB 3: Services -->
    <div class="sp-pane" id="spTab3">
        <form method="POST" id="svcForm">
            <input type="hidden" name="action" value="save_services">
            <input type="hidden" name="user_id" id="svc_uid">
            <div style="font-size:12px;color:#888;margin-bottom:12px">On/Off করুন এবং Save করুন</div>
            <div id="svcToggles"></div>
            <button type="submit" class="save-btn"><i class="fas fa-save"></i> Save Services</button>
        </form>
    </div>

    <!-- TAB 4: Devices -->
    <div class="sp-pane" id="spTab4">
        <div id="deviceList">
            <div style="text-align:center;padding:30px;color:#ccc">Loading...</div>
        </div>
    </div>

    <!-- TAB 5: Transactions -->
    <div class="sp-pane" id="spTab5">
        <div id="txnList" style="max-height:60vh;overflow-y:auto">
            <div style="text-align:center;padding:30px;color:#ccc">Loading...</div>
        </div>
    </div>
</div>

<script>
// Data
const USERS = <?= json_encode(array_column($users, null, 'id'), JSON_UNESCAPED_UNICODE) ?>;
const SVC_MAP = <?= json_encode($svcMap, JSON_UNESCAPED_UNICODE) ?>;
const SVC_DEFS = <?= json_encode($svcDefs, JSON_UNESCAPED_UNICODE) ?>;
const CURRENCY = '<?= CURRENCY ?>';
let currentUserId = 0;

function openPanel(id) {
    const u = USERS[id];
    if (!u) return;
    currentUserId = id;

    // Header
    document.getElementById('spAvatar').textContent = u.name.charAt(0).toUpperCase();
    document.getElementById('spName').textContent = u.name;
    document.getElementById('spSub').textContent = '@' + u.username + ' · ' + u.phone;

    // Info tab
    document.getElementById('si_balance').textContent = CURRENCY + parseFloat(u.balance).toFixed(2);
    document.getElementById('si_due').textContent = CURRENCY + parseFloat(u.due_balance||0).toFixed(2);
    document.getElementById('si_phone').textContent = u.phone;
    document.getElementById('si_email').textContent = u.email || '—';
    document.getElementById('si_role').textContent = u.role.charAt(0).toUpperCase()+u.role.slice(1);
    document.getElementById('si_status').textContent = u.status.charAt(0).toUpperCase()+u.status.slice(1);
    document.getElementById('si_pkg').textContent = u.pkg_name || 'Basic';
    document.getElementById('si_joined').textContent = u.created_at ? u.created_at.split(' ')[0] : '—';

    // Quick actions
    document.getElementById('spQuickActions').innerHTML = `
        <button class="btn-sm btn-blue" onclick="switchTab(1)"><i class="fas fa-edit"></i> Edit</button>
        <button class="btn-sm btn-green" onclick="switchTab(2)"><i class="fas fa-plus"></i> Add Balance</button>
        <button class="btn-sm ${u.status==='active'?'btn-red':'btn-green'}" onclick="toggleStatus(${id})">
            <i class="fas fa-${u.status==='active'?'ban':'check'}"></i> ${u.status==='active'?'Suspend':'Activate'}
        </button>`;

    // Edit form
    document.getElementById('ef_uid').value = id;
    document.getElementById('ef_name').value = u.name;
    document.getElementById('ef_phone').value = u.phone;
    document.getElementById('ef_email').value = u.email || '';
    document.getElementById('ef_role').value = u.role;
    document.getElementById('ef_status').value = u.status;
    document.getElementById('ef_pkg').value = u.package_id || 1;
    document.getElementById('ef_balance').value = parseFloat(u.balance).toFixed(2);
    document.getElementById('ef_due').value = parseFloat(u.due_balance||0).toFixed(2);

    // Balance tab
    document.getElementById('bal_uid').value = id;

    // Services tab
    document.getElementById('svc_uid').value = id;
    const userSvcs = SVC_MAP[id] || {};
    let svcHtml = '';
    for (const [key, label] of Object.entries(SVC_DEFS)) {
        const on = userSvcs[key] !== undefined ? userSvcs[key]==1 : true;
        svcHtml += `<label class="svc-tog-row ${on?'on':'off'}" id="strow_${id}_${key}">
            <span style="font-size:13px;font-weight:700;color:#333">${label}</span>
            <div class="tog-sw">
                <input type="checkbox" name="svc_${key}" value="1" ${on?'checked':''} onchange="svcTogChange(this,'${id}','${key}')">
                <div class="tog-track ${on?'on':'off'}" id="sttrack_${id}_${key}"><div class="tog-thumb"></div></div>
            </div>
        </label>`;
    }
    document.getElementById('svcToggles').innerHTML = svcHtml;

    // Transactions
    loadTransactions(id);

    // Show
    switchTab(0);
    document.getElementById('panelOv').classList.add('show');
    document.getElementById('sidePanel').classList.add('open');
    document.body.style.overflow = 'hidden';
}

function closePanel() {
    document.getElementById('panelOv').classList.remove('show');
    document.getElementById('sidePanel').classList.remove('open');
    document.body.style.overflow = '';
}

function switchTab(n) {
    document.querySelectorAll('.sp-tab').forEach((t,i)=>t.classList.toggle('active',i===n));
    document.querySelectorAll('.sp-pane').forEach((p,i)=>p.classList.toggle('active',i===n));
    if(n===4 && currentUserId) loadDevices(currentUserId);
    if(n===5 && currentUserId) loadTransactions(currentUserId);
}

function loadDevices(uid) {
    const el = document.getElementById('deviceList');
    el.innerHTML = '<div style="text-align:center;padding:20px;color:#aaa"><i class="fas fa-spinner fa-spin"></i></div>';
    fetch(`ajax/user_devices.php?user_id=${uid}`)
    .then(r=>r.json())
    .then(data=>{
        if(!data.length){
            el.innerHTML='<div style="text-align:center;padding:30px;color:#ccc"><i class="fas fa-mobile-alt" style="font-size:28px;display:block;margin-bottom:8px"></i>No devices registered</div>';
            return;
        }
        el.innerHTML = data.map(d=>`
        <div style="display:flex;align-items:center;gap:10px;padding:12px 0;border-bottom:1px solid #f5f5f5">
            <div style="width:38px;height:38px;border-radius:10px;background:${d.is_blocked?'#fff5f5':'#f0f4ff'};display:flex;align-items:center;justify-content:center;font-size:16px;flex-shrink:0">
                ${d.os&&d.os.includes('Android')?'📱':d.os&&d.os.includes('iOS')?'🍎':'💻'}
            </div>
            <div style="flex:1;min-width:0">
                <div style="font-size:13px;font-weight:700">${d.device_name||'Unknown'}</div>
                <div style="font-size:11px;color:#aaa;margin-top:2px">🌐 ${d.ip_address||'—'} ${d.city?'· 📍'+d.city+', '+d.country:''}</div>
                <div style="font-size:11px;color:#aaa">🕐 ${d.last_seen} · ${d.login_count} logins</div>
            </div>
            <span style="font-size:10px;font-weight:700;padding:3px 8px;border-radius:8px;background:${d.is_blocked?'#fff5f5':'#f0fff4'};color:${d.is_blocked?'#e53e3e':'#276749'};flex-shrink:0">
                ${d.is_blocked?'🚫 Blocked':'✅ Active'}
            </span>
            <div style="display:flex;gap:4px;flex-shrink:0">
                ${d.is_blocked
                    ? `<button onclick="deviceAction('unblock',${d.id},${uid})" style="padding:5px 9px;border:none;border-radius:7px;background:#f0fff4;color:#276749;font-size:11px;font-weight:700;cursor:pointer"><i class="fas fa-unlock"></i> Unblock</button>`
                    : `<button onclick="deviceAction('block',${d.id},${uid})" style="padding:5px 9px;border:none;border-radius:7px;background:#fff5f5;color:#e53e3e;font-size:11px;font-weight:700;cursor:pointer"><i class="fas fa-ban"></i> Block</button>`
                }
                <button onclick="deviceAction('delete',${d.id},${uid})" style="padding:5px 9px;border:none;border-radius:7px;background:#f5f5f5;color:#888;font-size:11px;cursor:pointer" title="Delete"><i class="fas fa-trash"></i></button>
            </div>
        </div>`).join('');
    }).catch(()=>{el.innerHTML='<div style="text-align:center;padding:20px;color:#e53e3e">Error loading devices</div>';});
}

function deviceAction(action, devId, uid) {
    if(action==='block' && !confirm('Block this device?')) return;
    if(action==='delete' && !confirm('Delete this device?')) return;
    const f = document.createElement('form');
    f.method = 'POST';
    f.action = 'devices.php';
    f.innerHTML = `<input name="action" value="${action}"><input name="dev_id" value="${devId}">`;
    // After submit redirect back
    f.addEventListener('submit', e=>{
        e.preventDefault();
        fetch('devices.php',{method:'POST',body:new FormData(f)})
        .then(()=>loadDevices(uid));
    });
    document.body.appendChild(f); f.dispatchEvent(new Event('submit'));
}

function toggleStatus(id) {
    const f = document.createElement('form');
    f.method = 'POST';
    f.innerHTML = `<input name="action" value="toggle_status"><input name="user_id" value="${id}">`;
    document.body.appendChild(f); f.submit();
}

function svcTogChange(cb, uid, key) {
    const on = cb.checked;
    const row   = document.getElementById('strow_'+uid+'_'+key);
    const track = document.getElementById('sttrack_'+uid+'_'+key);
    if(row)   row.className = 'svc-tog-row '+(on?'on':'off');
    if(track) track.className = 'tog-track '+(on?'on':'off');
}

function loadTransactions(id) {
    const el = document.getElementById('txnList');
    el.innerHTML = '<div style="text-align:center;padding:20px;color:#aaa"><i class="fas fa-spinner fa-spin"></i></div>';
    fetch(`ajax/user_transactions.php?user_id=${id}`)
        .then(r=>r.json())
        .then(data=>{
            if(!data.length){el.innerHTML='<div style="text-align:center;padding:30px;color:#ccc">No transactions</div>';return;}
            const typeIcons = {topup:'📱',drive:'⚡',deposit:'💰',commission:'💸',refund:'↩️',international:'🌍',card:'🎴',manual_drive:'📦',mbanking:'🏦',pin:'🔑'};
            const plus = ['deposit','commission','refund'];
            el.innerHTML = data.map(t=>`
            <div class="txn-item-sm">
                <div class="txn-ic-sm ${t.status}">${typeIcons[t.type]||'💳'}</div>
                <div style="flex:1;min-width:0">
                    <div style="font-size:12px;font-weight:700">${(t.type||'').replace('_',' ').replace(/\b\w/g,c=>c.toUpperCase())}</div>
                    <div style="font-size:11px;color:#aaa">${t.phone_number||t.reference} · ${t.created_at.slice(0,16)}</div>
                </div>
                <div style="text-align:right;flex-shrink:0">
                    <div style="font-size:13px;font-weight:800;color:${plus.includes(t.type)?'#38a169':'#e53e3e'}">${plus.includes(t.type)?'+':'-'}${CURRENCY}${parseFloat(t.amount).toFixed(2)}</div>
                    <div style="font-size:10px;color:#aaa">${t.status}</div>
                </div>
            </div>`).join('');
        }).catch(()=>{el.innerHTML='<div style="text-align:center;padding:20px;color:#e53e3e">Failed to load</div>';});
}

// Auto-open if redirected back
<?php if($openUserId): ?>
document.addEventListener('DOMContentLoaded',()=>openPanel(<?= $openUserId ?>));
<?php endif; ?>
</script>
</body>
</html>
