<?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', '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
if ($role === 'master') {
    $userData = $db->select('menualuser', '*', "username = :u", '', [':u' => $targetUser]);
} elseif ($role === 'super-reseller') {
    $userData = $db->select('menualuser', '*', "username = :u AND parent = :p AND role = 'reseller'", '', [
        ':u' => $targetUser,
        ':p' => $currentUser
    ]);
} 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 super reseller
$superResellerCredits = 0;
if ($role === '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  = intval($_POST['credits']);
    $currentCredits = intval($user['credits']);

    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'])) {
                $updateData['role'] = $_POST['role'];
            }
        }

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

        // =======================
        // CRÉDITOS
        // =======================
        if ($creditsChange !== 0) {

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

                $newCredits = max(0, $currentCredits + $creditsChange);

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

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

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

                if ($creditsChange > 0) {

                    if ($creditsChange <= $superResellerCredits) {

                        $db->update('menualuser',
                            ['credits' => $superResellerCredits - $creditsChange],
                            'username = :u',
                            [':u' => $currentUser]
                        );

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

                        $_SESSION['credits'] = $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 ($currentCredits >= $remove) {

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

                        $db->update('menualuser',
                            ['credits' => $superResellerCredits + $remove],
                            'username = :u',
                            [':u' => $currentUser]
                        );

                        $_SESSION['credits'] = $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" 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> <?= $user['credits'] ?>
                        <?php if($role === 'super-reseller'): ?>
                            <br>
                            <strong class="text-warning">💰 Tus créditos disponibles:</strong> <?= $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($role === 'master'): ?>
                <div class="form-group">
                    <label><i class="fa fa-tag"></i> Rol</label>
                    <select name="role" class="form-control">
                        <option value="reseller" <?= $user['role'] == 'reseller' ? 'selected' : '' ?>>
                            Reseller
                        </option>
                        <option value="super-reseller" <?= $user['role'] == 'super-reseller' ? 'selected' : '' ?>>
                            Super Reseller
                        </option>
                    </select>
                    <small class="text-muted">Solo Master puede cambiar el 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="<?= strtoupper($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>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
