<?php
include "../session.php"; 

if($role!="ADMIN"){
  header("Location:index.php");
  die();
}
include 'conect.php';

$usuario = $_POST['usuario'];
$rol = $_POST['rol'];

$permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyz';
$pass = substr(str_shuffle($permitted_chars), 0, 4);

date_default_timezone_set('America/Guatemala');
$date = date("d-m-Y");
$dateReg = date("Y-m-d");
$hora = date('H:i:s');

$consulta_nueva = mysqli_query($con, "SELECT * FROM users WHERE NAME='$usuario'");
$conteoNuevo = mysqli_num_rows($consulta_nueva);
if ($conteoNuevo > 0) {
    echo 2;
} else {
    // Cifrar la contraseña
    $password_hash = password_hash($pass, PASSWORD_DEFAULT);

    $ingreso = mysqli_query($con, "INSERT INTO users(NAME, PASSWORD, ROLE, DATE) VALUES ('$usuario', '$password_hash', '$rol', '$dateReg')");

    if ($ingreso) {
        $consulta_ingresado = mysqli_query($con, "SELECT * FROM users WHERE NAME='$usuario'");

        $conteoIng = mysqli_num_rows($consulta_ingresado);
        if ($conteoIng > 0) {
            while ($row3 = mysqli_fetch_array($consulta_ingresado)) {
                $userC = $row3['NAME'];
                $passC = $row3['PASSWORD'];

                // Verificar la contraseña descifrada
                if (password_verify($pass, $passC)) {
                    
                   // include ('../plugins/impresora/ticketUser.php');

                    echo "Usuario <b>" . $userC . "</b> Creado<br>
                        CONTRASEÑA: <b>" . $pass . "</b>";
                } else {
                    echo "Error al verificar la contraseña.";
                }
            }
        } else {
            echo 1;
        }
    }
}
?>
