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

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', 'super-reseller'], true)) {
    die('Access denied');
}

$me = $db->select('menualuser', 'credits', 'username = :u', '', [':u' => $user_logado]);
$myCredits = $me[0]['credits'] ?? 0;
$myUnlimited = is_unlimited_credits($myCredits);

if (isset($_POST['submit'])) {
    $username = sanitize($_POST['username'] ?? '');
    $password = sanitize($_POST['password'] ?? '');
    $role = sanitize($_POST['role'] ?? 'reseller');
    $creditsInput = $_POST['credits'] ?? 0;
    $creditsUnlimited = isset($_POST['credits_unlimited']) && $_POST['credits_unlimited'] === '1';

    if ($role_logada === 'super-reseller') {
        $role = 'reseller';
        $creditsUnlimited = false;
    }

    if (!in_array($role, ['reseller', 'super-reseller'], true)) {
        $role = 'reseller';
    }

    $credits = ($role_logada === 'master' && $creditsUnlimited) ? -1 : max(0, (int)$creditsInput);

    if ($username === '' || $password === '') {
        echo "<script>alert('Completa usuario y contraseña');</script>";
    } else {
        $exists = $db->select('menualuser', 'id', 'username = :u', '', [':u' => $username]);
        if ($exists) {
            echo "<script>alert('El nombre de usuario ya existe');</script>";
        } else {
            if ($role_logada === 'super-reseller' && !$myUnlimited && $credits > (int)$myCredits) {
                echo "<script>alert('Créditos insuficientes');</script>";
            } else {
                $parent = ($role_logada === 'master') ? null : $user_logado;

                $db->insert('menualuser', [
                    'username' => $username,
                    'password' => $password,
                    'credits'  => $credits,
                    'role'     => $role,
                    'parent'   => $parent,
                    'status'   => 'active'
                ]);

                if ($role_logada === 'super-reseller' && !$myUnlimited && $credits > 0) {
                    $db->update('menualuser', ['credits' => ((int)$myCredits - $credits)], 'username = :u', [':u' => $user_logado]);
                }

                $db->insert('credit_history', [
                    'actor'  => $user_logado,
                    'target' => $username,
                    'action' => is_unlimited_credits($credits) ? 'CREATE_USER_UNLIMITED' : 'CREATE_USER',
                    'amount' => is_unlimited_credits($credits) ? 0 : $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> CRIAR USUÁRIO</h2>
            </div>

            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label>Usuário</label>
                        <input type="text" name="username" class="form-control" required>
                    </div>

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

                    <div class="form-group">
                        <label>Créditos Iniciais</label>
                        <input
                            type="number"
                            name="credits"
                            id="creditsInput"
                            class="form-control"
                            value="0"
                            min="0"
                            <?=($role_logada === 'super-reseller' && !$myUnlimited ? 'max="'.(int)$myCredits.'"' : '')?>
                        >
                        <?php if ($role_logada === 'super-reseller'): ?>
                            <small class="text-muted">
                                Créditos disponíveis: <strong><?=credits_display($myCredits)?></strong>
                            </small>
                        <?php endif; ?>
                    </div>

                    <?php if ($role_logada === 'master'): ?>
                    <div class="form-group form-check">
                        <input type="checkbox" class="form-check-input" id="creditsUnlimited" name="credits_unlimited" value="1" onchange="toggleUnlimitedCredits()">
                        <label class="form-check-label" for="creditsUnlimited">Asignar créditos ilimitados</label>
                        <small class="form-text text-muted">Un reseller o super reseller con créditos ilimitados puede vender ilimitado.</small>
                    </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>Função</label>
                        <select name="role" class="form-control" <?=($role_logada === 'super-reseller' ? 'disabled' : '')?>>
                            <?php if ($role_logada === 'master'): ?>
                                <option value="super-reseller">SUPER REVENDEDOR</option>
                            <?php endif; ?>
                            <option value="reseller" selected>REVENDEDOR</option>
                        </select>
                    </div>

                    <button type="submit" name="submit" class="btn btn-info">
                        <i class="fa fa-check"></i> Criar Usuário
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function toggleUnlimitedCredits() {
    var chk = document.getElementById('creditsUnlimited');
    var input = document.getElementById('creditsInput');
    if (!chk || !input) return;
    input.disabled = chk.checked;
    if (chk.checked) {
        input.dataset.prev = input.value;
        input.value = 0;
    } else if (input.dataset.prev !== undefined) {
        input.value = input.dataset.prev || 0;
    }
}
</script>

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