<?php
ob_start();
session_start();

require_once __DIR__ . '/includes/header.php';

// =======================
// VALIDACIÓN DE SESIÓN
// =======================
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));
}

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

if (!in_array($role, ['master', 'ultra-reseller', 'super-reseller', 'reseller'])) {
    die('Acceso denegado');
}

// =======================
// OBTENER USUARIO
// =======================
$targetUser = sanitize($_GET['username'] ?? '');

if (empty($targetUser)) {
    $_SESSION['msg'] = 'Usuario no especificado';
    $_SESSION['msg_type'] = 'danger';
    header("Location: myteam.php");
    exit;
}

// Obtener datos
$allowedChildRoles = child_roles_for($role);
$canGrantUnlimited = can_grant_unlimited_credits($db, $role, $currentUser);

if ($role === 'master') {
    $userData = $db->select('menualuser', '*', "username = :u AND role != 'master'", '', [':u' => $targetUser]);
} elseif (in_array($role, ['ultra-reseller','super-reseller'])) {
    $userData = $db->select('menualuser', '*', "username = :u AND parent = :p", '', [
        ':u' => $targetUser,
        ':p' => $currentUser
    ]);
    if (!empty($userData) && !in_array($userData[0]['role'], $allowedChildRoles)) {
        $userData = [];
    }
} else {
    die('Acceso denegado');
}

if (!$userData) {
    $_SESSION['msg'] = 'Usuario no encontrado o acceso denegado';
    $_SESSION['msg_type'] = 'danger';
    header("Location: myteam.php");
    exit;
}

$user = $userData[0];

// Créditos del usuario superior
$superResellerCredits = 0;
if (in_array($role, ['ultra-reseller','super-reseller'])) {
    $superData = $db->select('menualuser', 'credits', "username = :u", '', [':u' => $currentUser]);
    $superResellerCredits = $superData[0]['credits'] ?? 0;
}

// =======================
// PROCESAR FORMULARIO (ANTES DEL HTML)
// =======================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_changes'])) {

    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        $_SESSION['msg'] = 'Token inválido';
        $_SESSION['msg_type'] = 'danger';
        header("Location: myteam.php");
        exit;
    }

    $error = false;

    $newPass        = sanitize($_POST['password']);
    $creditsChange  = isset($_POST['credits']) ? intval($_POST['credits']) : 0;
    $currentCredits = $user['credits'];
    $setUnlimited = isset($_POST['set_unlimited_credits']) && $_POST['set_unlimited_credits'] === '1';

    if (empty($newPass)) {
        $_SESSION['msg'] = 'La contraseña no puede estar vacía';
        $_SESSION['msg_type'] = 'danger';
        $error = true;
    }

    if (!$error) {

        // ACTUALIZAR PASSWORD
        $updateData = ['password' => $newPass];

        if ($role === 'master' && isset($_POST['role'])) {
            if (in_array($_POST['role'], ['reseller', 'super-reseller', 'ultra-reseller'])) {
                $updateData['role'] = $_POST['role'];
            }
        } elseif ($role === 'ultra-reseller' && isset($_POST['role'])) {
            if (in_array($_POST['role'], ['reseller', 'super-reseller'])) {
                $updateData['role'] = $_POST['role'];
            }
        }

        $db->update('menualuser', $updateData, 'username = :u', [':u' => $targetUser]);

        // =======================
        // CRÉDITOS
        // =======================
        if ($setUnlimited) {
            if ($canGrantUnlimited) {
                $db->update('menualuser', ['credits' => -1], 'username = :u', [':u' => $targetUser]);
                $_SESSION['msg'] = "✅ Créditos ilimitados activados correctamente";
                $_SESSION['msg_type'] = "success";
                $creditsChange = 0;
            } else {
                $_SESSION['msg'] = "❌ No tienes permiso para activar créditos ilimitados";
                $_SESSION['msg_type'] = "danger";
                $error = true;
            }
        } elseif (is_unlimited_credits($currentCredits) && $canGrantUnlimited) {
            $newFiniteCredits = max(0, $creditsChange);
            $db->update('menualuser', ['credits' => $newFiniteCredits], 'username = :u', [':u' => $targetUser]);
            $_SESSION['msg'] = "✅ Créditos ilimitados desactivados. Nuevo saldo: {$newFiniteCredits}";
            $_SESSION['msg_type'] = "success";
            $creditsChange = 0;
        }

        if (!$error && $creditsChange !== 0) {

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

                $newCredits = is_unlimited_credits($currentCredits) ? -1 : max(0, (int)$currentCredits + $creditsChange);

                $db->update('menualuser', ['credits' => $newCredits], 'username = :u', [':u' => $targetUser]);

                $_SESSION['msg'] = "✅ Créditos actualizados correctamente";
                $_SESSION['msg_type'] = "success";

            } elseif (in_array($role, ['ultra-reseller','super-reseller'])) {

                if ($creditsChange > 0) {

                    if (is_unlimited_credits($superResellerCredits) || $creditsChange <= (int)$superResellerCredits) {

                        if (!is_unlimited_credits($superResellerCredits)) {
                            $db->update('menualuser',
                                ['credits' => (int)$superResellerCredits - $creditsChange],
                                'username = :u',
                                [':u' => $currentUser]
                            );
                        }

                        $db->update('menualuser',
                            ['credits' => is_unlimited_credits($currentCredits) ? -1 : ((int)$currentCredits + $creditsChange)],
                            'username = :u',
                            [':u' => $targetUser]
                        );

                        if (!is_unlimited_credits($superResellerCredits)) { $_SESSION['credits'] = (int)$superResellerCredits - $creditsChange; }

                        $_SESSION['msg'] = "✅ Créditos transferidos correctamente";
                        $_SESSION['msg_type'] = "success";

                    } else {
                        $_SESSION['msg'] = "❌ No tienes suficientes créditos";
                        $_SESSION['msg_type'] = "danger";
                        $error = true;
                    }

                } else {

                    $remove = abs($creditsChange);

                    if (!is_unlimited_credits($currentCredits) && (int)$currentCredits >= $remove) {

                        $db->update('menualuser',
                            ['credits' => (int)$currentCredits - $remove],
                            'username = :u',
                            [':u' => $targetUser]
                        );

                        if (!is_unlimited_credits($superResellerCredits)) {
                            $db->update('menualuser',
                                ['credits' => (int)$superResellerCredits + $remove],
                                'username = :u',
                                [':u' => $currentUser]
                            );
                        }

                        if (!is_unlimited_credits($superResellerCredits)) { $_SESSION['credits'] = (int)$superResellerCredits + $remove; }

                        $_SESSION['msg'] = "⚠️ Créditos devueltos correctamente";
                        $_SESSION['msg_type'] = "success";

                    } else {
                        $_SESSION['msg'] = "❌ El usuario no tiene suficientes créditos";
                        $_SESSION['msg_type'] = "danger";
                        $error = true;
                    }
                }
            }
        } else {
            $_SESSION['msg'] = "✅ Usuario actualizado correctamente";
            $_SESSION['msg_type'] = "success";
        }
    }

    // 🔥 SIEMPRE REDIRIGE
    header("Location: myteam.php");
    exit;
}
?>

<div class="col-md-8 mx-auto">
    <div class="card text-white bg-dark shadow">
        <div class="card-header bg-warning text-dark">
            <h4 class="mb-0">
                <i class="fa fa-pencil-square-o"></i> Editar Usuario: <?= htmlspecialchars($targetUser) ?>
            </h4>
        </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']); ?>
            <?php endif; ?>
            
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                
                <div class="form-group">
                    <label><i class="fa fa-user"></i> Usuario</label>
                    <input type="text" class="form-control bg-secondary text-white" 
                           value="<?= htmlspecialchars($user['username']) ?>" readonly>
                </div>
                
                <div class="form-group">
                    <label><i class="fa fa-lock"></i> Contraseña</label>
                    <input type="text" name="password" class="form-control" 
                           value="<?= htmlspecialchars($user['password']) ?>" required>
                    <small class="text-muted">Puedes cambiar la contraseña del usuario</small>
                </div>
                
                <div class="form-group">
                    <label><i class="fa fa-money"></i> 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="credits" id="editCredits" class="form-control" value="0" 
                               placeholder="Ej: 10 para agregar, -10 para restar">
                    </div>
                    <small class="text-muted">
                        <strong>Créditos actuales del usuario:</strong> <?= display_credits($user['credits']) ?>
                        <?php if(in_array($role, ['ultra-reseller','super-reseller'])): ?>
                            <br>
                            <strong class="text-warning">💰 Tus créditos disponibles:</strong> <?= display_credits($superResellerCredits) ?>
                            <br>
                            <span class="text-info">
                                <i class="fa fa-info-circle"></i> 
                                Al AGREGAR créditos (+), se restarán de TU saldo.<br>
                                Al RESTAR créditos (-), se sumarán a TU saldo.
                            </span>
                        <?php endif; ?>
                    </small>
                </div>
                
                <?php if($canGrantUnlimited): ?>
                <div class="form-group form-check">
                    <input type="checkbox" name="set_unlimited_credits" value="1" class="form-check-input" id="setUnlimitedCredits" <?= is_unlimited_credits($user['credits']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="setUnlimitedCredits">Activar créditos ilimitados para este usuario</label>
                    <small class="form-text text-muted">Al guardar, este usuario quedará con saldo ilimitado. Si desmarcas esta casilla, el número de arriba quedará como nuevo saldo.</small>
                </div>
                <?php endif; ?>

                <?php if($role === 'master' || $role === 'ultra-reseller'): ?>
                <div class="form-group">
                    <label><i class="fa fa-tag"></i> Rol</label>
                    <select name="role" class="form-control">
                        <?php if($role === 'master'): ?>
                        <option value="ultra-reseller" <?= $user['role'] == 'ultra-reseller' ? 'selected' : '' ?>>
                            Ultra Revendedor
                        </option>
                        <?php endif; ?>
                        <option value="super-reseller" <?= $user['role'] == 'super-reseller' ? 'selected' : '' ?>>
                            Super Revendedor
                        </option>
                        <option value="reseller" <?= $user['role'] == 'reseller' ? 'selected' : '' ?>>
                            Revendedor
                        </option>
                    </select>
                    <small class="text-muted">Solo el rol superior autorizado puede cambiar este rol</small>
                </div>
                <?php else: ?>
                <div class="form-group">
                    <label><i class="fa fa-tag"></i> Rol</label>
                    <input type="text" class="form-control bg-secondary text-white" 
                           value="<?= role_label_es($user['role']) ?>" readonly>
                </div>
                <?php endif; ?>
                
                <div class="form-group">
                    <label><i class="fa fa-users"></i> Parent / Superior</label>
                    <input type="text" class="form-control bg-secondary text-white" 
                           value="<?= $user['parent'] ? htmlspecialchars($user['parent']) : 'Master' ?>" readonly>
                </div>
                
                <hr>
                
                <div class="row">
                    <div class="col-md-6">
                        <button type="submit" name="save_changes" class="btn btn-warning btn-block">
                            <i class="fa fa-save"></i> Guardar Cambios
                        </button>
                    </div>
                    <div class="col-md-6">
                        <a href="myteam.php" class="btn btn-secondary btn-block">
                            <i class="fa fa-arrow-left"></i> Cancelar
                        </a>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
function toggleEditUnlimitedCredits(){
    const chk = document.getElementById('setUnlimitedCredits');
    const credits = document.getElementById('editCredits');
    if(!chk || !credits) return;
    if(chk.checked){
        credits.placeholder = 'Desmarca ilimitados para fijar un saldo manual';
    } else {
        credits.placeholder = 'Si estaba ilimitado, este número será el nuevo saldo. Ej: 20';
    }
}
document.addEventListener('DOMContentLoaded', function(){
    const chk = document.getElementById('setUnlimitedCredits');
    if(chk){
        chk.addEventListener('change', toggleEditUnlimitedCredits);
        toggleEditUnlimitedCredits();
    }
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
