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

/* =======================
   SECURITY & CSRF
======================= */
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');
}

/* =======================
   BLOCK / UNBLOCK RESELLER
======================= */
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="reseller"', [':u'=>$targetUser]);
    } elseif ($role === 'super-reseller') {
        $db->update('menualuser', ['status' => $newStatus], 'username = :u AND role="reseller" AND parent = :p', [':u'=>$targetUser, ':p'=>$username]);
    } else {
        die('Permission denied');
    }

    echo "<script>alert('User {$targetUser} {$newStatus} successfully'); window.location.href='myteam.php';</script>";
    exit;
}

/* =======================
   DELETE USER (INDIVIDUAL)
======================= */
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', '', [':u'=>$targetUser]);
    } else {
        $userCheck = $db->select('menualuser', 'role', 'username = :u AND parent = :p AND role = "reseller"', '', [':u'=>$targetUser, ':p'=>$username]);
    }

    if (!empty($userCheck) && $userCheck[0]['role'] !== 'master') {
        $db->delete('menualuser', 'username = :u', [':u'=>$targetUser]);

        $db->insert('credit_history', [
            'actor' => $username,
            'target'=> $targetUser,
            'action'=> 'USER_DELETED',
            'amount'=> 0
        ]);

        echo "<script>alert('User deleted successfully'); window.location='myteam.php';</script>";
    } else {
        echo "<script>alert('Error deleting user'); window.location='myteam.php';</script>";
    }
    exit;
}

/* =======================
   BULK DELETE USERS
======================= */
if (isset($_POST['bulk_delete'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('Invalid CSRF token');
    }

    if (empty($_POST['users']) || !is_array($_POST['users'])) {
        echo "<script>alert('No users selected'); window.location='myteam.php';</script>";
        exit;
    }

    foreach ($_POST['users'] as $targetUserRaw) {
        $targetUser = sanitize($targetUserRaw);

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

        if (!empty($userCheck) && $userCheck[0]['role'] !== 'master') {
            $db->delete('menualuser', 'username = :u', [':u'=>$targetUser]);

            $db->insert('credit_history', [
                'actor' => $username,
                'target'=> $targetUser,
                'action'=> 'USER_DELETED_BULK',
                'amount'=> 0
            ]);
        }
    }

    echo "<script>alert('Selected users deleted successfully'); window.location='myteam.php';</script>";
    exit;
}

/* =======================
   DATA FETCH
======================= */
if ($role === 'master') {
    $team = $db->select('menualuser', 'username, role, credits, parent, status', "role != 'master'", 'role DESC, username ASC', []);
} else {
    $team = $db->select('menualuser', 'username, role, credits, parent, status', "parent = :parent AND role = 'reseller'", 'username ASC', [':parent' => $username]);
}
?>

<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> My Team</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">

            <form method="post" id="bulkForm">
            <input type="hidden" name="csrf_token" value="<?=$_SESSION['csrf_token']?>">

            <div class="table-responsive">
                <table class="table table-dark table-striped">
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAll"></th>
                            <th>Username</th>
                            <th>Role</th>
                            <th>Créditos</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>
                                    <input type="checkbox" name="users[]" value="<?=htmlspecialchars($u['username'])?>">
                                </td>

                                <td><?=htmlspecialchars($u['username'])?></td>
                                <td><span class="badge badge-<?=($u['role']==='super-reseller'?'warning':'info')?>"><?=strtoupper($u['role'])?></span></td>
                                <td><strong><?=$u['credits']?></strong></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">
                                            <i class="fa fa-cog"></i>
                                        </a>

                                        <?php if($role==='master' || $role==='super-reseller'): ?>
                                            <?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; ?>
                                        <?php endif; ?>

                                        <!-- DELETE INDIVIDUAL -->
                                        <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>

            <!-- BULK BUTTON -->
            <div class="mt-2">
                <button type="submit" name="bulk_delete" class="btn btn-danger"
                    onclick="return confirm('Delete selected users permanently?')">
                    <i class="fa fa-trash"></i> Delete Selected
                </button>
            </div>

            </form>

        </div>
    </div>
</div>

<script>
document.getElementById('selectAll').addEventListener('click', function() {
    let checkboxes = document.querySelectorAll('input[name="users[]"]');
    checkboxes.forEach(cb => cb.checked = this.checked);
});
</script>

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