<?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');
}

/* =======================
   CREDIT MANAGEMENT WITH TRANSFER
======================= */
if (isset($_POST['credit_action'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['msg'] = 'Invalid CSRF token';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $targetUser = sanitize($_POST['username']);
    $amount = intval($_POST['amount']);

    if ($amount == 0) {
        $_SESSION['msg'] = 'Amount must be greater than 0 or less than 0';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    // Verify user exists and has permission
    if ($role === 'master') {
        $userCheck = $db->select('menualuser', 'credits, role, parent', 'username = :u', '', [':u'=>$targetUser]);
    } else {
        $userCheck = $db->select('menualuser', 'credits, role, parent', 'username = :u AND parent = :p AND role = "reseller"', '', [':u'=>$targetUser, ':p'=>$username]);
    }

    if (empty($userCheck)) {
        $_SESSION['msg'] = 'User not found or no permission';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $currentCredits = $userCheck[0]['credits'];

    // POSITIVE AMOUNT = ADD CREDITS (transfer from actor to target)
    if ($amount > 0) {
        if ($role !== 'master') {
            // Super Reseller: check if has enough credits
            $actorCredits = $db->select('menualuser', 'credits', 'username = :u', '', [':u'=>$username]);
            if ($actorCredits[0]['credits'] < $amount) {
                $_SESSION['msg'] = "❌ YNo tienes suficientes créditos! {$actorCredits[0]['credits']} credits";
                $_SESSION['msg_type'] = 'danger';
                header("Location: myteam.php");
                exit;
            }
            
            // Deduct from super reseller
            $newActorCredits = $actorCredits[0]['credits'] - $amount;
            $db->update('menualuser', ['credits' => $newActorCredits], 'username = :u', [':u'=>$username]);
            $_SESSION['credits'] = $newActorCredits;
            
            // Add to reseller
            $newCredits = $currentCredits + $amount;
            $db->update('menualuser', ['credits' => $newCredits], 'username = :u', [':u'=>$targetUser]);
            
            $msg = "✅ Tansferido +{$amount} créditos de tu parte a {$targetUser}";
            
            $db->insert('credit_history', [
                'actor' => $username,
                'target'=> $targetUser,
                'action'=> 'CREDIT_SENT_TO_RESELLER',
                'amount'=> $amount
            ]);
        } else {
            // Master: add credits for free
            $newCredits = $currentCredits + $amount;
            $db->update('menualuser', ['credits' => $newCredits], 'username = :u', [':u'=>$targetUser]);
            $msg = "✅ Added +{$amount} credits to {$targetUser}";
            
            $db->insert('credit_history', [
                'actor' => $username,
                'target'=> $targetUser,
                'action'=> 'CREDIT_ADDED_BY_MASTER',
                'amount'=> $amount
            ]);
        }
        
        $_SESSION['msg'] = $msg;
        $_SESSION['msg_type'] = 'success';
        
    // NEGATIVE AMOUNT = SUBTRACT CREDITS (transfer from target to actor)
    } elseif ($amount < 0) {
        $removeAmount = abs($amount);
        
        if ($currentCredits < $removeAmount) {
            $_SESSION['msg'] = "❌ U¡El usuario no tiene suficientes créditos! SOLO {$currentCredits} credits";
            $_SESSION['msg_type'] = 'danger';
            header("Location: myteam.php");
            exit;
        }
        
        // Subtract from reseller
        $newCredits = $currentCredits - $removeAmount;
        $db->update('menualuser', ['credits' => $newCredits], 'username = :u', [':u'=>$targetUser]);
        
        if ($role !== 'master') {
            // Add to super reseller
            $actorCredits = $db->select('menualuser', 'credits', 'username = :u', '', [':u'=>$username]);
            $newActorCredits = $actorCredits[0]['credits'] + $removeAmount;
            $db->update('menualuser', ['credits' => $newActorCredits], 'username = :u', [':u'=>$username]);
            $_SESSION['credits'] = $newActorCredits;
            
            $msg = "✅ Transferred -{$removeAmount} credits from {$targetUser} to you";
            
            $db->insert('credit_history', [
                'actor' => $username,
                'target'=> $targetUser,
                'action'=> 'CREDIT_RECEIVED_FROM_RESELLER',
                'amount'=> $removeAmount
            ]);
        } else {
            $msg = "⚠️ Removed -{$removeAmount} credits from {$targetUser}";
            
            $db->insert('credit_history', [
                'actor' => $username,
                'target'=> $targetUser,
                'action'=> 'CREDIT_REMOVED_BY_MASTER',
                'amount'=> $removeAmount
            ]);
        }
        
        $_SESSION['msg'] = $msg;
        $_SESSION['msg_type'] = 'success';
    }

    header("Location: myteam.php");
    exit;
}

/* =======================
   BLOCK / UNBLOCK RESELLER
======================= */
if (isset($_GET['block']) || isset($_GET['unblock'])) {

    $targetUser = sanitize($_GET['block'] ?? $_GET['unblock']);
    $newStatus  = isset($_GET['block']) ? 'blocked' : 'active';
    $actionText = isset($_GET['block']) ? 'blocked' : 'unblocked';

    // 🚫 Evitar que se bloquee a sí mismo
    if ($targetUser === $username) {
        $_SESSION['msg'] = "No puedes bloquearte a ti mismo";
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $updated = 0;

    if ($role === 'master') {

        // ✅ Master puede bloquear reseller y super-reseller (pero no otros master)
        $updated = $db->update(
            'menualuser',
            ['status' => $newStatus],
            'username = :u AND role IN ("reseller","super-reseller")',
            [':u' => $targetUser]
        );

    } elseif ($role === 'super-reseller') {

        // ✅ Solo sus resellers hijos
        $updated = $db->update(
            'menualuser',
            ['status' => $newStatus],
            'username = :u AND role = "reseller" AND parent = :p',
            [
                ':u' => $targetUser,
                ':p' => $username
            ]
        );
    }

    // 🔍 Validar si realmente se aplicó el cambio
    if ($updated > 0) {
        $_SESSION['msg'] = "User {$targetUser} {$actionText} successfully";
        $_SESSION['msg_type'] = 'success';
    } else {
        $_SESSION['msg'] = "No tienes permisos o el usuario no existe";
        $_SESSION['msg_type'] = 'danger';
    }

    header("Location: myteam.php");
    exit;
}

/* =======================
   DELETE USER (INDIVIDUAL)
======================= */
if (isset($_POST['delete_user'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['msg'] = 'Invalid CSRF token';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $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
        ]);

        $_SESSION['msg'] = "User {$targetUser} deleted successfully";
        $_SESSION['msg_type'] = 'success';
    } else {
        $_SESSION['msg'] = "Error deleting user {$targetUser}";
        $_SESSION['msg_type'] = 'danger';
    }

    header("Location: myteam.php");
    exit;
}

/* =======================
   BULK DELETE USERS
======================= */
if (isset($_POST['bulk_delete'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['msg'] = 'Invalid CSRF token';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    if (empty($_POST['users']) || !is_array($_POST['users'])) {
        $_SESSION['msg'] = 'No users selected';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $deletedCount = 0;
    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
            ]);
            $deletedCount++;
        }
    }

    $_SESSION['msg'] = "{$deletedCount} user(s) deleted successfully";
    $_SESSION['msg_type'] = 'success';
    header("Location: myteam.php");
    exit;
}

/* =======================
   DATA FETCH WITH PAGINATION AND SEARCH
======================= */
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';
$limit = 10;
$offset = ($page - 1) * $limit;

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

if (!empty($search)) {
    $allTeam = array_filter($allTeam, function($user) use ($search) {
        return stripos($user['username'], $search) !== false;
    });
}

$totalUsers = count($allTeam);
$totalPages = ceil($totalUsers / $limit);
$team = array_slice($allTeam, $offset, $limit);

// Get super reseller credits for display
$myCredits = 0;
if ($role === 'super-reseller') {
    $myData = $db->select('menualuser', 'credits', 'username = :u', '', [':u' => $username]);
    $myCredits = $myData[0]['credits'] ?? 0;
}
?>

<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; 
    flex-wrap: wrap; 
}
.status-badge { 
    text-transform: uppercase; 
    font-size: 0.8rem; 
}
.search-filter { 
    margin-bottom: 20px; 
}

/* MODAL SIMPLIFICADO */
.credit-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.85);
    z-index: 999999;
    display: none;
    justify-content: center;
    align-items: center;
}

.credit-modal-container {
    background: #2d2d2d;
    border-radius: 10px;
    width: 90%;
    max-width: 450px;
    box-shadow: 0 5px 30px rgba(0, 0, 0, 0.5);
    animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
    from {
        opacity: 0;
        transform: translateY(-30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.credit-modal-header {
    padding: 15px 20px;
    border-bottom: 1px solid #444;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.credit-modal-header h5 {
    margin: 0;
    color: #ffc107;
}

.credit-modal-close {
    background: none;
    border: none;
    color: white;
    font-size: 28px;
    cursor: pointer;
    padding: 0;
    line-height: 1;
}

.credit-modal-close:hover {
    color: #ffc107;
}

.credit-modal-body {
    padding: 20px;
}

.credit-modal-footer {
    padding: 15px 20px;
    border-top: 1px solid #444;
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.text-center { text-align: center; }
.text-warning { color: #ffc107; }
.text-info { color: #17a2b8; }
.text-danger { color: #dc3545; }
.text-success { color: #28a745; }
.mb-3 { margin-bottom: 15px; }
.mt-3 { margin-top: 15px; }
.mb-2 { margin-bottom: 10px; }
.font-weight-bold { font-weight: bold; }

.pagination { 
    margin-top: 20px; 
    justify-content: center; 
}
.page-link { 
    background: rgba(0,0,0,0.3); 
    border-color: rgba(255,255,255,0.1); 
    color: white; 
}
.page-item.active .page-link { 
    background: #007bff; 
    border-color: #007bff; 
}
</style>

<div class="col-md-12">
    <div class="card dashboard-card">
        <div class="card-header d-flex justify-content-between align-items-center flex-wrap">
            <h3 class="mb-0"><i class="fa fa-users"></i> My Team</h3>
            <div>
                <a href="credit_history.php" class="btn btn-info btn-sm"><i class="fa fa-history"></i> View Logs</a>
            </div>
        </div>

        <div class="card-body">
            <?php if(isset($_SESSION['msg'])): ?>
                <div class="alert alert-<?= $_SESSION['msg_type'] ?> alert-dismissible fade show" role="alert">
                    <i class="fa fa-<?= ($_SESSION['msg_type'] == 'success') ? 'check-circle' : 'exclamation-triangle' ?>"></i>
                    <?= $_SESSION['msg'] ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            <?php unset($_SESSION['msg'], $_SESSION['msg_type']); endif; ?>

            <!-- Search Filter -->
            <div class="search-filter">
                <form method="get" class="form-inline">
                    <div class="input-group" style="width: 100%;">
                        <input type="text" name="search" class="form-control" placeholder="Search by username..." value="<?= htmlspecialchars($search) ?>" style="flex: 1;">
                        <div class="input-group-append">
                            <button type="submit" class="btn btn-primary"><i class="fa fa-search"></i> Buscar</button>
                            <?php if(!empty($search)): ?>
                                <a href="myteam.php" class="btn btn-secondary"><i class="fa fa-times"></i> Limpiar</a>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
            </div>

            <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 width="30"><input type="checkbox" id="selectAll"></th>
                            <th>Usuario</th>
                            <th>Rol</th>
                            <th>Credits</th>
                            <th>Padre</th>
                            <th>Status</th>
                            <th width="200">Acciones</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><strong><?=htmlspecialchars($u['username'])?></strong></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-primary" title="Edit User">
                                            <i class="fa fa-pencil"></i>
                                        </a>
                                        <button type="button" class="btn btn-sm btn-warning" title="Manage Credits" 
                                                onclick="openCreditModal('<?=htmlspecialchars($u['username'])?>', <?=$u['credits']?>, <?=$myCredits?>)">
                                            <i class="fa fa-money"></i> <i class="fa fa-coin"></i>
                                        </button>
                                        <?php if($role==='master' || $role==='super-reseller'): ?>
                                            <?php if($u['status']==='active'): ?>
                                                <a href="?block=<?=urlencode($u['username'])?>" class="btn btn-sm btn-danger" title="Block User" 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" title="Unblock User" onclick="return confirm('Unblock <?=htmlspecialchars($u['username'])?>?')">
                                                    <i class="fa fa-check"></i>
                                                </a>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        <form method="post" style="margin:0;" onsubmit="return confirm('Delete <?=htmlspecialchars($u['username'])?> permanently?')">
                                            <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" title="Delete User">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if($totalPages > 1): ?>
            <nav>
                <ul class="pagination">
                    <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>">« Previous</a>
                    </li>
                    <?php for($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                            <a class="page-link" href="?page=<?= $i ?>&search=<?= urlencode($search) ?>"><?= $i ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?= $page >= $totalPages ? 'disabled' : '' ?>">
                        <a class="page-link" href="?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>">Next »</a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
            
            <div class="mt-3 d-flex justify-content-between align-items-center">
                <button type="submit" name="bulk_delete" class="btn btn-danger" onclick="return confirm('Delete selected users permanently?')">
                    <i class="fa fa-trash"></i> Eliminar seleccionados
                </button>
                <div class="text-muted">Showing <?= count($team) ?> of <?= $totalUsers ?> users</div>
            </div>
            </form>
        </div>
    </div>
</div>

<!-- MODAL SIMPLIFICADO - SOLO UN INPUT -->
<div id="creditModalOverlay" class="credit-modal-overlay">
    <div class="credit-modal-container">
        <div class="credit-modal-header">
            <h5><i class="fa fa-money"></i> Manage Credits</h5>
            <button class="credit-modal-close" onclick="closeCreditModal()">&times;</button>
        </div>
        <form method="post" id="creditFormModal">
            <div class="credit-modal-body">
                <input type="hidden" name="csrf_token" value="<?=$_SESSION['csrf_token']?>">
                <input type="hidden" name="username" id="creditUsernameModal">
                
                <div class="text-center mb-3">
                    <label>User:</label>
                    <h4><strong id="displayUsernameModal" class="text-warning"></strong></h4>
                </div>
                
                <div class="text-center mb-3">
                    <label>Créditos actuales:</label>
                    <h3><span id="currentCreditsModal" class="badge badge-info" style="font-size: 1.8rem; padding: 10px 20px;"></span></h3>
                </div>
                
                <?php if($role === 'super-reseller'): ?>
                <div class="text-center mb-3">
                    <label>Tus Creditos:</label>
                    <h4><span id="myCreditsModal" class="badge badge-warning" style="font-size: 1.2rem; padding: 8px 15px;"><?= $myCredits ?></span></h4>
                </div>
                <?php endif; ?>
                
                <hr class="mb-3">
                
                <div class="form-group">
                    <label class="font-weight-bold">Ajuste de Créditos:</label>
                    <div class="input-group">
                        <div class="input-group-prepend">
                            <span class="input-group-text bg-secondary text-white">+ / -</span>
                        </div>
                        <input type="number" name="amount" id="creditAmountModal" class="form-control" 
                               placeholder="Ej: 10 para agregar, -10 para restar" value="" step="1" autocomplete="off">
                    </div>
                    <small class="text-muted">
                        <span class="text-success">Números positivos (+)</span> = Agregar créditos<br>
                        <span class="text-danger">Números negativos (-)</span> = Restar créditos
                        <?php if($role === 'super-reseller'): ?>
                            <br><span class="text-info">⚠️ Los créditos que agregues se restarán de TU saldo</span>
                        <?php endif; ?>
                    </small>
                </div>
            </div>
            <div class="credit-modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeCreditModal()">Cancelar</button>
                <button type="submit" name="credit_action" class="btn btn-warning" id="submitCreditBtnModal">
                    <i class="fa fa-save"></i> Aplicar Cambios
                </button>
            </div>
        </form>
    </div>
</div>

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

function openCreditModal(username, currentCredits, myCredits = 0) {
    // Reset form
    document.getElementById('creditAmountModal').value = '';
    
    // Set user data
    document.getElementById('creditUsernameModal').value = username;
    document.getElementById('displayUsernameModal').textContent = username;
    document.getElementById('currentCreditsModal').textContent = currentCredits;
    
    // Set my credits if super reseller
    if (document.getElementById('myCreditsModal')) {
        document.getElementById('myCreditsModal').textContent = myCredits;
    }
    
    // Show modal
    document.getElementById('creditModalOverlay').style.display = 'flex';
    document.body.style.overflow = 'hidden';
    
    // Focus on input
    setTimeout(function() {
        document.getElementById('creditAmountModal').focus();
    }, 100);
}

function closeCreditModal() {
    document.getElementById('creditModalOverlay').style.display = 'none';
    document.body.style.overflow = '';
}

// Validate before submitting
document.getElementById('creditFormModal').addEventListener('submit', function(e) {
    let amount = parseInt(document.getElementById('creditAmountModal').value);
    let currentCredits = parseInt(document.getElementById('currentCreditsModal').textContent);
    let myCredits = document.getElementById('myCreditsModal') ? parseInt(document.getElementById('myCreditsModal').textContent) : null;
    let username = document.getElementById('displayUsernameModal').textContent;
    
    // Check if amount is valid
    if (isNaN(amount) || amount === 0) {
        e.preventDefault();
        alert('❌ Please enter a valid amount (positive or negative number)');
        return false;
    }
    
    // For negative amounts (subtract)
    if (amount < 0) {
        let subtractAmount = Math.abs(amount);
        if (currentCredits < subtractAmount) {
            e.preventDefault();
            alert(`❌ Cannot subtract ${subtractAmount} credits. User "${username}" only has ${currentCredits} credits.`);
            return false;
        }
    }
    
    // For positive amounts (add) - check if super reseller has enough credits
    if (amount > 0 && myCredits !== null) {
        if (myCredits < amount) {
            e.preventDefault();
            alert(`❌ You don't have enough credits! You have ${myCredits} credits. Cannot add ${amount} credits.`);
            return false;
        }
    }
    
    // Confirm action
    let actionText = amount > 0 ? `ADD +${amount} credits to` : `SUBTRACT ${amount} credits from`;
    let confirmMsg = `✅ Confirm: ${actionText} "${username}"?`;
    
    if (!confirm(confirmMsg)) {
        e.preventDefault();
        return false;
    }
    
    // Close modal before submit
    closeCreditModal();
    return true;
});

// Cerrar modal al hacer clic fuera
document.getElementById('creditModalOverlay').addEventListener('click', function(e) {
    if (e.target === this) {
        closeCreditModal();
    }
});

// Auto-hide alerts after 5 seconds
setTimeout(function() {
    let alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(function() {
            if(alert.parentNode) alert.parentNode.removeChild(alert);
        }, 500);
    });
}, 5000);

// Enter key submits form
document.getElementById('creditAmountModal').addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        document.getElementById('submitCreditBtnModal').click();
    }
});
</script>

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