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

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

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

    $username = sanitize($_POST['username']);
    $password = sanitize($_POST['password']);
    $credits  = (int)$_POST['credits'];

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

    /* =======================
       ROLE RULES
    ======================= */
    if ($role_logada === 'super-reseller') {
        $role = 'reseller';
    }

    /* =======================
       CREDIT LIMIT
    ======================= */
    if ($role_logada === 'super-reseller' && $credits > $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'  => $credits,
        'role'     => $role,
        'parent'   => $parent
    ]);

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

    /* =======================
       CREDIT HISTORY
    ======================= */
    if ($credits > 0) {
        $db->insert('credit_history', [
            'actor'  => $user_logado,
            'target' => $username,
            'action' => 'CREATE_USER',
            'amount' => $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 Inicialess</label>
                        <input
                            type="number"
                            name="credits"
                            class="form-control"
                            value="0"
                            min="0"
                            <?=($role_logada === 'super-reseller' ? 'max="'.$myCredits.'"' : '')?>
                        >
                        <?php if ($role_logada === 'super-reseller'): ?>
                            <small class="text-muted">
                                Créditos disponibles: <strong><?=$myCredits?></strong>
                            </small>
                        <?php endif; ?>
                    </div>

                    <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="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> Crear Usuario
                    </button>

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

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