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

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

$user_logado = $_SESSION['name'];
$role_logada = $_SESSION['role'];

if (!in_array($role_logada, ['master', 'ultra-reseller', 'super-reseller'])) {
    die('Access denied');
}

/* =======================
   GET CREATOR CREDITS
======================= */
$myCredits = null;
if (in_array($role_logada, ['ultra-reseller','super-reseller'])) {
    $me = $db->select(
        'menualuser',
        'credits',
        'username = :u',
        '',
        [':u' => $user_logado]
    );
    $myCredits = $me[0]['credits'] ?? 0;
}

/* =======================
   CRIAR USUÁRIO
======================= */
if (isset($_POST['submit'])) {

    $username = sanitize($_POST['username']);
    $password = sanitize($_POST['password']);
    $credits  = isset($_POST['credits']) ? (int)$_POST['credits'] : 0;
    $unlimitedCredits = isset($_POST['unlimited_credits']) && $_POST['unlimited_credits'] === '1';

    $role = $_POST['role'] ?? null;
    $role = $role ? sanitize($role) : null;

    /* =======================
       ROLE RULES
    ======================= */
    if ($role_logada === 'super-reseller') {
        $role = 'reseller';
    } elseif ($role_logada === 'ultra-reseller' && !in_array($role, ['super-reseller','reseller'])) {
        $role = 'reseller';
    } elseif ($role_logada === 'master' && !in_array($role, ['ultra-reseller','super-reseller','reseller'])) {
        $role = 'reseller';
    }

    /* =======================
       CREDIT LIMIT
    ======================= */
    if ($unlimitedCredits && !can_grant_unlimited_credits($db, $role_logada, $user_logado)) {
        echo "<script>alert('No tienes permiso para asignar créditos ilimitados');</script>";
        exit;
    }

    if (!$unlimitedCredits && in_array($role_logada, ['ultra-reseller','super-reseller']) && !is_unlimited_credits($myCredits) && $credits > (int)$myCredits) {
        echo "<script>alert('Créditos insuficientes');</script>";
        exit;
    }

    /* =======================
       PARENT
    ======================= */
    $parent = ($role_logada === 'master') ? null : $user_logado;

    /* =======================
       USERNAME CHECK
    ======================= */
    $exists = $db->select(
        'menualuser',
        'id',
        'username = :u',
        '',
        [':u' => $username]
    );

    if ($exists) {
        echo "<script>alert('El nombre de usuario ya existe');</script>";
        exit;
    }

    /* =======================
       CRIAR USUÁRIO
    ======================= */
    $db->insert('menualuser', [
        'username' => $username,
        'password' => $password,
        'credits'  => ($unlimitedCredits ? -1 : $credits),
        'role'     => $role,
        'parent'   => $parent
    ]);

    /* =======================
       DEDUCT SUPER-RESELLER CREDITS
    ======================= */
    if (!$unlimitedCredits && in_array($role_logada, ['ultra-reseller','super-reseller']) && !is_unlimited_credits($myCredits) && $credits > 0) {
        $db->update(
            'menualuser',
            ['credits' => ((int)$myCredits - $credits)],
            'username = :u',
            [':u' => $user_logado]
        );
    }

    /* =======================
       CREDIT HISTORY
    ======================= */
    if ($credits > 0 || $unlimitedCredits) {
        $db->insert('credit_history', [
            'actor'  => $user_logado,
            'target' => $username,
            'action' => 'CREATE_USER',
            'amount' => ($unlimitedCredits ? -1 : $credits)
        ]);
    }

    echo "<script>
        alert('Usuario creado con éxito');
        window.location='adduser.php';
    </script>";
    exit;
}
?>

<div class="col-md-8 mx-auto">
    <div class="card-body">
        <div class="card text-white ctluser-main">
            <div class="card-header ctheading text-center">
                <h2><i class="fa fa-users"></i> CREAR USUARIO</h2>
            </div>

            <div class="card-body">
                <form method="post">

                    <div class="form-group">
                        <label>Usuario</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Contraseña</label>
                        <input type="text" name="password" class="form-control" required>
                    </div>

                    <div class="form-group">
                        <label>Créditos Iniciales</label>
                        <input
                            type="number"
                            name="credits"
                            id="initialCredits"
                            class="form-control"
                            value="0"
                            min="0"
                            <?=(in_array($role_logada, ['ultra-reseller','super-reseller']) && !is_unlimited_credits($myCredits) ? 'max="'.(int)$myCredits.'"' : '')?>
                        >
                        <?php if (in_array($role_logada, ['ultra-reseller','super-reseller'])): ?>
                            <small class="text-muted">
                                Créditos disponibles: <strong><?=display_credits($myCredits)?></strong>
                            </small>
                        <?php endif; ?>
                    </div>

                    <?php if (can_grant_unlimited_credits($db, $role_logada, $user_logado)): ?>
                    <div class="form-group form-check">
                        <input type="checkbox" name="unlimited_credits" value="1" class="form-check-input" id="unlimitedCredits">
                        <label class="form-check-label" for="unlimitedCredits">Activar créditos ilimitados</label>
                        <small class="form-text text-muted">Si marcas esta opción, este usuario no consumirá saldo al crear cuentas y podrá entregar ilimitados a sus dependientes según su rol.</small>
                    </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>Rol</label>
                        <select name="role" class="form-control" <?=($role_logada === 'super-reseller' ? 'disabled' : '')?>>
                            <?php if ($role_logada === 'master'): ?>
                                <option value="ultra-reseller">ULTRA REVENDEDOR</option>
                                <option value="super-reseller">SUPER REVENDEDOR</option>
                                <option value="reseller" selected>REVENDEDOR</option>
                            <?php elseif ($role_logada === 'ultra-reseller'): ?>
                                <option value="super-reseller">SUPER REVENDEDOR</option>
                                <option value="reseller" selected>REVENDEDOR</option>
                            <?php else: ?>
                                <option value="reseller" selected>REVENDEDOR</option>
                            <?php endif; ?>
                        </select>
                    </div>

                    <button type="submit" name="submit" class="btn btn-info">
                        <i class="fa fa-check"></i> Crear Usuario
                    </button>

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


<script>
function toggleUnlimitedCredits(){
    const chk = document.getElementById('unlimitedCredits');
    const credits = document.getElementById('initialCredits');
    if(!chk || !credits) return;
    if(chk.checked){
        credits.value = 0;
        credits.setAttribute('disabled', 'disabled');
    } else {
        credits.removeAttribute('disabled');
    }
}
document.addEventListener('DOMContentLoaded', function(){
    const chk = document.getElementById('unlimitedCredits');
    if(chk){
        chk.addEventListener('change', toggleUnlimitedCredits);
        toggleUnlimitedCredits();
    }
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>