<?php
include('includes/header.php');

if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$username = $_SESSION['name'];
$role     = $_SESSION['role'];

if ($role === 'reseller') {
    die('Access denied');
}

if (isset($_GET['block']) || isset($_GET['unblock'])) {
    $targetUser = sanitize($_GET['block'] ?? $_GET['unblock']);
    $newStatus  = isset($_GET['block']) ? 'blocked' : 'active';

    if ($role === 'master') {
        $db->update('menualuser', ['status' => $newStatus], 'username = :u AND role IN ("reseller","super-reseller")', [':u' => $targetUser]);
    } else {
        $db->update('menualuser', ['status' => $newStatus], 'username = :u AND role = "reseller" AND parent = :p', [':u' => $targetUser, ':p' => $username]);
    }
    echo "<script>alert('Estado actualizado'); window.location.href='myteam.php';</script>";
    exit;
}

if (isset($_POST['delete_user'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('Invalid CSRF token');
    }

    $targetUser = sanitize($_POST['username'] ?? '');
    if ($role === 'master') {
        $userCheck = $db->select('menualuser', 'role', 'username = :u AND role IN ("reseller","super-reseller")', '', [':u' => $targetUser]);
    } else {
        $userCheck = $db->select('menualuser', 'role', 'username = :u AND parent = :p AND role = "reseller"', '', [':u' => $targetUser, ':p' => $username]);
    }

    if ($userCheck) {
        $db->delete('menualuser', 'username = :u', [':u' => $targetUser]);
        $db->insert('credit_history', [
            'actor' => $username,
            'target' => $targetUser,
            'action' => 'USER_DELETED',
            'amount' => 0
        ]);
        echo "<script>alert('Usuario eliminado'); window.location='myteam.php';</script>";
    } else {
        echo "<script>alert('No tienes permiso para eliminar este usuario'); window.location='myteam.php';</script>";
    }
    exit;
}

if ($role === 'master') {
    $team = $db->select('menualuser', '*', 'role IN ("super-reseller","reseller")', 'role ASC, username ASC');
} else {
    $team = $db->select('menualuser', '*', 'parent = :p AND role = "reseller"', 'username ASC', [':p' => $username]);
}

$clientOwners = [];
if ($role === 'master') {
    $clientOwners = [];
} else {
    $clientOwners = get_visible_client_owners($db, $role, $username);
}

$clientCountByOwner = [];
if ($role === 'master') {
    $rows = $db->select('codes', 'owner', "owner != 'trial'", 'owner ASC');
    foreach ($rows as $r) {
        $owner = $r['owner'] ?? '';
        if ($owner === '') continue;
        $clientCountByOwner[$owner] = ($clientCountByOwner[$owner] ?? 0) + 1;
    }
} elseif ($clientOwners) {
    $in = build_in_clause_params($clientOwners, ':o');
    $rows = $db->select('codes', 'owner', "owner IN ({$in['sql']}) AND owner != 'trial'", 'owner ASC', $in['params']);
    foreach ($rows as $r) {
        $owner = $r['owner'] ?? '';
        if ($owner === '') continue;
        $clientCountByOwner[$owner] = ($clientCountByOwner[$owner] ?? 0) + 1;
    }
}
?>

<style>
.dashboard-card { border-radius: 5px; border: 1px solid rgba(255,255,255,0.1); background: rgba(0,0,0,0.2); margin-bottom: 20px; }
.actions-container { display: flex; gap: 8px; align-items: center; }
.status-badge { text-transform: uppercase; font-size: 0.8rem; }
</style>

<div class="col-md-12">
    <div class="card dashboard-card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h3 class="mb-0"><i class="fa fa-users"></i> Mi red de revendedores</h3>
            <a href="credit_history.php" class="btn btn-info btn-sm"><i class="fa fa-history"></i> Logs</a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-dark table-striped">
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Role</th>
                            <th>Créditos</th>
                            <th>Clientes</th>
                            <th>Parent</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($team)): ?>
                            <tr><td colspan="7" class="text-center">No team members found.</td></tr>
                        <?php else: ?>
                        <?php foreach ($team as $u): ?>
                            <tr>
                                <td><?=htmlspecialchars($u['username'])?></td>
                                <td><span class="badge badge-<?=($u['role']==='super-reseller'?'warning':'info')?>"><?=strtoupper($u['role'])?></span></td>
                                <td><strong><?=credits_display($u['credits'] ?? 0)?></strong></td>
                                <td><span class="badge badge-secondary"><?= (int)($clientCountByOwner[$u['username']] ?? 0) ?></span></td>
                                <td><?= $u['parent'] ? htmlspecialchars($u['parent']) : '<small class="text-muted">Master</small>' ?></td>
                                <td><span class="badge badge-<?=($u['status']==='blocked'?'danger':'success')?> status-badge"><?=strtoupper($u['status'] ?? 'ACTIVE')?></span></td>
                                <td>
                                    <div class="actions-container">
                                        <a href="edit_user.php?username=<?=urlencode($u['username'])?>" class="btn btn-sm btn-warning" title="Edit"><i class="fa fa-cog"></i></a>
                                        <?php if($u['status']==='active'): ?>
                                            <a href="?block=<?=urlencode($u['username'])?>" class="btn btn-sm btn-danger" onclick="return confirm('Block <?=htmlspecialchars($u['username'])?>?')"><i class="fa fa-ban"></i></a>
                                        <?php else: ?>
                                            <a href="?unblock=<?=urlencode($u['username'])?>" class="btn btn-sm btn-success" onclick="return confirm('Unblock <?=htmlspecialchars($u['username'])?>?')"><i class="fa fa-check"></i></a>
                                        <?php endif; ?>
                                        <form method="post" style="margin:0;">
                                            <input type="hidden" name="csrf_token" value="<?=$_SESSION['csrf_token']?>">
                                            <input type="hidden" name="username" value="<?=htmlspecialchars($u['username'])?>">
                                            <button type="submit" name="delete_user" class="btn btn-sm btn-dark" onclick="return confirm('Delete <?=htmlspecialchars($u['username'])?> permanently?')"><i class="fa fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include('includes/footer.php'); ?>
